{"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 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": "15 puzzle game", "language": "Javascript", "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": "var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;\nfunction getPossibles() {\n var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1];\n possibles = [];\n for( var i = 0; i < 4; i++ ) {\n ii = zx + cx[i]; jj = zy + cy[i];\n if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue;\n possibles.push( { x: ii, y: jj } );\n }\n}\nfunction updateBtns() {\n var b, v, id;\n for( var j = 0; j < 4; j++ ) {\n for( var i = 0; i < 4; i++ ) {\n id = \"btn\" + ( i + j * 4 );\n b = document.getElementById( id );\n v = board[i][j];\n if( v < 16 ) {\n b.innerHTML = ( \"\" + v );\n b.className = \"button\"\n }\n else {\n b.innerHTML = ( \"\" );\n b.className = \"empty\";\n }\n }\n }\n clickCounter.innerHTML = \"Clicks: \" + clicks;\n}\nfunction shuffle() {\n var v = 0, t; \n do {\n getPossibles();\n while( true ) {\n t = possibles[Math.floor( Math.random() * possibles.length )];\n console.log( t.x, oldzx, t.y, oldzy )\n if( t.x != oldzx || t.y != oldzy ) break;\n }\n oldzx = zx; oldzy = zy;\n board[zx][zy] = board[t.x][t.y];\n zx = t.x; zy = t.y;\n board[zx][zy] = 16; \n } while( ++v < 200 );\n}\nfunction restart() {\n shuffle();\n clicks = 0;\n updateBtns();\n}\nfunction checkFinished() {\n var a = 0;\n for( var j = 0; j < 4; j++ ) {\n for( var i = 0; i < 4; i++ ) {\n if( board[i][j] < a ) return false;\n a = board[i][j];\n }\n }\n return true;\n}\nfunction btnHandle( e ) {\n getPossibles();\n var c = e.target.i, r = e.target.j, p = -1;\n for( var i = 0; i < possibles.length; i++ ) {\n if( possibles[i].x == c && possibles[i].y == r ) {\n p = i;\n break;\n }\n }\n if( p > -1 ) {\n clicks++;\n var t = possibles[p];\n board[zx][zy] = board[t.x][t.y];\n zx = t.x; zy = t.y;\n board[zx][zy] = 16;\n updateBtns();\n if( checkFinished() ) {\n setTimeout(function(){ \n alert( \"WELL DONE!\" );\n restart();\n }, 1);\n }\n }\n}\nfunction createBoard() {\n board = new Array( 4 );\n for( var i = 0; i < 4; i++ ) {\n board[i] = new Array( 4 );\n }\n for( var j = 0; j < 4; j++ ) {\n for( var i = 0; i < 4; i++ ) {\n board[i][j] = ( i + j * 4 ) + 1;\n }\n }\n zx = zy = 3; board[zx][zy] = 16;\n}\nfunction createBtns() {\n var b, d = document.createElement( \"div\" );\n d.className += \"board\";\n document.body.appendChild( d );\n for( var j = 0; j < 4; j++ ) {\n for( var i = 0; i < 4; i++ ) {\n b = document.createElement( \"button\" );\n b.id = \"btn\" + ( i + j * 4 );\n b.i = i; b.j = j;\n b.addEventListener( \"click\", btnHandle, false );\n b.appendChild( document.createTextNode( \"\" ) );\n d.appendChild( b );\n }\n }\n clickCounter = document.createElement( \"p\" );\n clickCounter.className += \"txt\";\n document.body.appendChild( clickCounter );\n}\nfunction start() {\n createBtns();\n createBoard();\n restart();\n}\n"} {"title": "21 game", "language": "Javascript", "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\n\n \n \n \n \n \n \n \n \n \n 21 Game\n \n \n \n\n \n\n\n\n

\n 21 Game in ECMA Script (Java Script)\n

\n\n

\n 21 is a two player game, the game is played by choosing a number\n (1, 2, or 3) to be added to the running total. The game is won by\n the player whose chosen number causes the running total to reach\n exactly 21. The running total starts at zero.\n

\n\n

Use buttons to play.

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

\n\n \n\n \n\n\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/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": "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": "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": "9 billion names of God the integer", "language": "JavaScript from Python", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"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": "(function () {\n var cache = [\n [1]\n ];\n//this was never needed.\n /* function PyRange(start, end, step) {\n step = step || 1;\n if (!end) {\n end = start;\n start = 0;\n }\n var arr = [];\n for (var i = start; i < end; i += step) arr.push(i);\n return arr;\n }*/ \n\n function cumu(n) {\n var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this\n r, l, x, Aa, Mi;\n // for (ll in ra) { too pythony\n for (l=cache.length;l\n\n
\n
\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": "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": "AVL tree", "language": "Javascript", "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": "function tree(less, val, more) {\n return {\n depth: 1+Math.max(less.depth, more.depth),\n less: less,\n val: val,\n more: more,\n };\n}\n\nfunction node(val) {\n return tree({depth: 0}, val, {depth: 0});\n}\n\nfunction insert(x,y) {\n if (0 == y.depth) return x;\n if (0 == x.depth) return y;\n if (1 == x.depth && 1 == y.depth) {\n switch (Math.sign(y.val)-x.val) {\n case -1: return tree(y, x.val, {depth: 0});\n case 0: return y;\n case 1: return tree(x, y.val, {depth: 0});\n }\n }\n switch (Math.sign(y.val-x.val)) {\n case -1: return balance(insert(x.less, y), x.val, x.more);\n case 0: return balance(insert(x.less, y.less), x.val, insert(x.more, y.more));\n case 1: return balance(x.less. x.val, insert(x.more, y));\n }\n}\n\nfunction balance(less,val,more) {\n if (2 > Math.abs(less.depth-more.depth))\n return tree(less,val,more);\n if (more.depth > less.depth) {\n if (more.more.depth >= more.less.depth) {\n // 'more' was heavy\n return moreHeavy(less, val, more);\n } else {\n return moreHeavy(less,val,lessHeavy(more.less, more.val, more.more));\n }\n } else {\n if(less.less.depth >= less.more.depth) {\n return lessHeavy(less, val, more);\n } else {\n return lessHeavy(moreHeavy(less.less, less.val, less.more), val, more);\n }\n }\n}\n\nfunction moreHeavy(less,val,more) {\n return tree(tree(less,val,more.less), more.val, more.more)\n}\n\nfunction lessHeavy(less,val,more) {\n return tree(less.less, less.val, tree(less.more, val, more));\n}\n\nfunction remove(val, y) {\n switch (y.depth) {\n case 0: return y;\n case 1:\n if (val == y.val) {\n return y.less;\n } else {\n return y;\n }\n default:\n switch (Math.sign(y.val - val)) {\n case -1: return balance(y.less, y.val, remove(val, y.more));\n case 0: return insert(y.less, y.more);\n case 1: return balance(remove(val, y.less), y.val, y.more)\n }\n }\n}\n\nfunction lookup(val, y) {\n switch (y.depth) {\n case 0: return y;\n case 1: if (val == y.val) {\n return y;\n } else {\n return {depth: 0};\n }\n default: \n switch (Math.sign(y.val-val)) {\n case -1: return lookup(val, y.more);\n case 0: return y;\n case 1: return lookup(val, y.less);\n }\n }\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, 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, 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": "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": "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": "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": "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": "Angle difference between two bearings", "language": "Javascript", "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": "function relativeBearing(b1Rad, b2Rad)\n{\n\tb1y = Math.cos(b1Rad);\n\tb1x = Math.sin(b1Rad);\n\tb2y = Math.cos(b2Rad);\n\tb2x = Math.sin(b2Rad);\n\tcrossp = b1y * b2x - b2y * b1x;\n\tdotp = b1x * b2x + b1y * b2y;\n\tif(crossp > 0.)\n\t\treturn Math.acos(dotp);\n\treturn -Math.acos(dotp);\n}\n\nfunction test()\n{\n\tvar deg2rad = 3.14159265/180.0;\n\tvar rad2deg = 180.0/3.14159265;\n\treturn \"Input in -180 to +180 range\\n\"\n\t\t+relativeBearing(20.0*deg2rad, 45.0*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-45.0*deg2rad, 45.0*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-85.0*deg2rad, 90.0*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-95.0*deg2rad, 90.0*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-45.0*deg2rad, 125.0*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-45.0*deg2rad, 145.0*deg2rad)*rad2deg+\"\\n\"\n\n\t\t+relativeBearing(29.4803*deg2rad, -88.6381*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-78.3251*deg2rad, -159.036*deg2rad)*rad2deg+\"\\n\"\n\t\n\t\t+ \"Input in wider range\\n\"\n\t\t+relativeBearing(-70099.74233810938*deg2rad, 29840.67437876723*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(-165313.6666297357*deg2rad, 33693.9894517456*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(1174.8380510598456*deg2rad, -154146.66490124757*deg2rad)*rad2deg+\"\\n\"\n\t\t+relativeBearing(60175.77306795546*deg2rad, 42213.07192354373*deg2rad)*rad2deg+\"\\n\";\n\n}"} {"title": "Anti-primes", "language": "Javascript", "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": "function factors(n) {\n var factors = [];\n for (var i = 1; i <= n; i++) {\n if (n % i == 0) {\n factors.push(i);\n }\n }\n return factors;\n}\n\nfunction generateAntiprimes(n) {\n var antiprimes = [];\n var maxFactors = 0;\n for (var i = 1; antiprimes.length < n; i++) {\n var ifactors = factors(i);\n if (ifactors.length > maxFactors) {\n antiprimes.push(i);\n maxFactors = ifactors.length;\n }\n }\n return antiprimes;\n}\n\nfunction go() {\n var number = document.getElementById(\"n\").value;\n document.body.removeChild(document.getElementById(\"result-list\"));\n document.body.appendChild(showList(generateAntiprimes(number)));\n}\n\nfunction showList(array) {\n var list = document.createElement(\"ul\");\n list.id = \"result-list\";\n for (var i = 0; i < array.length; i++) {\n var item = document.createElement(\"li\");\n item.appendChild(document.createTextNode(array[i]));\n list.appendChild(item);\n }\n return list;\n}\n"} {"title": "Arithmetic-geometric mean", "language": "JavaScript", "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": "(() => {\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 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": "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": "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": "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": "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": "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/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": "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": "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": "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": "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": "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": "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} 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/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": "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": "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 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": "Calculating the value of e", "language": "Javascript", "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": "(() => {\n \"use strict\";\n\n // - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --\n\n // eApprox : Int -> Float\n const eApprox = n =>\n sum(\n scanl(mul)(1)(\n enumFromTo(1)(n)\n )\n .map(x => 1 / x)\n );\n\n\n // ---------------------- TEST -----------------------\n const main = () =>\n eApprox(20);\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\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 // mul (*) :: Num a => a -> a -> a\n const mul = a =>\n // The arithmetic product of a and b.\n b => a * b;\n\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n // The series of interim values arising\n // from a catamorphism. Parallel to foldl.\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n\n return [v, a[1].concat(v)];\n }, [startValue, [startValue]])[1];\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 // MAIN ---\n return main();\n})();"} {"title": "Call a function", "language": "JavaScript", "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": "var mutate = function(victim) {\n victim[0] = null;\n victim = 42;\n};\nvar foo = [1, 2, 3];\nmutate(foo) // foo is now [null, 2, 3], not 42"} {"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": "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": "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": "Casting out nines", "language": "JavaScript", "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": "function main(s, e, bs, pbs) {\n bs = bs || 10;\n pbs = pbs || 10\n document.write('start:', toString(s), ' end:', toString(e),\n ' base:', bs, ' printBase:', pbs)\n document.write('
castOutNine: ');\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": "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": "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": "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": "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": "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": "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 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": "Church numerals", "language": "Javascript", "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": "(() => {\n 'use strict';\n\n // ----------------- CHURCH NUMERALS -----------------\n\n const churchZero = f =>\n identity;\n\n\n const churchSucc = n =>\n f => compose(f)(n(f));\n\n\n const churchAdd = m =>\n n => f => compose(n(f))(m(f));\n\n\n const churchMult = m =>\n n => f => n(m(f));\n\n\n const churchExp = m =>\n n => n(m);\n\n\n const intFromChurch = n =>\n n(succ)(0);\n\n\n const churchFromInt = n =>\n compose(\n foldl(compose)(identity)\n )(\n replicate(n)\n );\n\n\n // Or, by explicit recursion:\n const churchFromInt_ = x => {\n const go = i =>\n 0 === i ? (\n churchZero\n ) : churchSucc(go(pred(i)));\n return go(x);\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n const [cThree, cFour] = map(churchFromInt)([3, 4]);\n\n return map(intFromChurch)([\n churchAdd(cThree)(cFour),\n churchMult(cThree)(cFour),\n churchExp(cFour)(cThree),\n churchExp(cThree)(cFour),\n ]);\n };\n\n\n // --------------------- GENERIC ---------------------\n\n // compose (>>>) :: (a -> b) -> (b -> c) -> a -> c\n const compose = f =>\n g => x => f(g(x));\n\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = f =>\n a => xs => [...xs].reduce(\n (x, y) => f(x)(y),\n a\n );\n\n\n // identity :: a -> a\n const identity = x => x;\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 // pred :: Enum a => a -> a\n const pred = x =>\n x - 1;\n\n\n // replicate :: Int -> a -> [a]\n const replicate = n =>\n // n instances of x.\n x => Array.from({\n length: n\n }, () => x);\n\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // MAIN ---\n console.log(JSON.stringify(main()));\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": "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": "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": "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": "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": "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 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": "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": "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": "Currency", "language": "JavaScript", "task": "Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n\nDollar signs and thousands separators are optional.\n\n", "solution": "const money = require('money-math') \n\nlet hamburgers = 4000000000000000 \nlet hamburgerPrice = 5.50 \n\nlet shakes = 2 \nlet shakePrice = 2.86 \n\nlet tax = 7.65 \n\nlet hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice)) \nlet shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice)) \n\nlet subTotal = money.add(hamburgerTotal, shakeTotal) \n\nlet taxTotal = money.percent(subTotal, tax) \n\nlet total = money.add(subTotal, taxTotal) \n\nconsole.log('Hamburger Total:', hamburgerTotal) \nconsole.log('Shake Total:', shakeTotal) \nconsole.log('Sub Total:', subTotal) \nconsole.log('Tax:', taxTotal) \nconsole.log('Total:', total) \n"} {"title": "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": "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": "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": "Department numbers", "language": "Javascript", "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": "(function () {\n 'use strict';\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n };\n\n return '(Police, Sanitation, Fire)\\n' +\n concatMap(function (x) {\n return concatMap(function (y) {\n return concatMap(function (z) {\n return z !== y && 1 <= z && z <= 7 ? [\n [x, y, z]\n ] : [];\n }, [12 - (x + y)]);\n }, [1, 2, 3, 4, 5, 6, 7]);\n }, [2, 4, 6])\n .map(JSON.stringify)\n .join('\\n');\n})();"} {"title": "Department numbers", "language": "Javascript from Haskell", "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": "(() => {\n \"use strict\";\n\n // -------------- NUMBERING CONSTRAINTS --------------\n\n // options :: Int -> Int -> Int -> [(Int, Int, Int)]\n const options = lo => hi => total => {\n const\n bind = xs => f => xs.flatMap(f),\n ds = enumFromTo(lo)(hi);\n\n return bind(ds.filter(even))(\n x => bind(ds.filter(d => d !== x))(\n y => bind([total - (x + y)])(\n z => (z !== y && lo <= z && z <= hi) ? [\n [x, y, z]\n ] : []\n )\n )\n );\n };\n\n // ---------------------- TEST -----------------------\n const main = () => {\n const\n label = \"(Police, Sanitation, Fire)\",\n solutions = options(1)(7)(12),\n n = solutions.length,\n list = solutions\n .map(JSON.stringify)\n .join(\"\\n\");\n\n return (\n `${label}\\n\\n${list}\\n\\nNumber of options: ${n}`\n );\n };\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // even :: Integral a => a -> Bool\n const even = n => n % 2 === 0;\n\n // MAIN ---\n return main();\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": "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": "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 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 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": "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": "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": "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": "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": "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": "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": "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 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 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": "Dutch national flag problem", "language": "Javascript", "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": "const dutchNationalFlag = () => {\n\n /**\n * Return the name of the given number in this way:\n * 0 = Red\n * 1 = White\n * 2 = Blue\n * @param {!number} e\n */\n const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red';\n\n /**\n * Given an array of numbers return true if each number is bigger than\n * or the same as the previous\n * @param {!Array} arr\n */\n const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]);\n\n /**\n * Generator that keeps yielding a random int between 0(inclusive) and\n * max(exclusive), up till n times, and then is done.\n * @param max\n * @param n\n */\n function* randomGen (max, n) {\n let i = 0;\n while (i < n) {\n i += 1;\n yield Math.floor(Math.random() * max);\n }\n }\n\n /**\n * An array of random integers between 0 and 3\n * @type {[!number]}\n */\n const mixedBalls = [...(randomGen(3, 22))];\n\n /**\n * Sort the given array into 3 sub-arrays and then concatenate those.\n */\n const sortedBalls = mixedBalls\n .reduce((p,c) => p[c].push(c) && p, [[],[],[]])\n .reduce((p,c) => p.concat(c), []);\n\n /**\n * A verbatim implementation of the Wikipedia pseudo-code\n * @param {!Array} A\n * @param {!number} mid The value of the 'mid' number. In our case 1 as\n * low is 0 and high is 2\n */\n const dutchSort = (A, mid) => {\n let i = 0;\n let j = 0;\n let n = A.length - 1;\n while(j <= n) {\n if (A[j] < mid) {\n [A[i], A[j]] = [A[j], A[i]];\n i += 1;\n j += 1;\n } else if (A[j] > mid) {\n [A[j], A[n]] = [A[n], A[j]];\n n -= 1\n } else {\n j += 1;\n }\n }\n };\n\n console.log(`Mixed balls : ${mixedBalls.map(name).join()}`);\n console.log(`Is sorted: ${isSorted(mixedBalls)}`);\n\n console.log(`Sorted balls : ${sortedBalls.map(name).join()}`);\n console.log(`Is sorted: ${isSorted(sortedBalls)}`);\n\n // Only do the dutch sort now as it mutates the mixedBalls array in place.\n dutchSort(mixedBalls, 1);\n console.log(`Dutch Sorted balls: ${mixedBalls.map(name).join()}`);\n console.log(`Is sorted: ${isSorted(mixedBalls)}`);\n};\ndutchNationalFlag();\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": "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": "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": "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 {\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": "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": "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": "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": "Execute HQ9+", "language": "JavaScript", "task": "Implement a ''' [[HQ9+]] ''' interpreter or compiler.\n\n", "solution": "function hq9plus(code) {\n var out = '';\n var acc = 0;\n \n for (var i=0; i1; j--) {\n out += j + \" bottles of beer on the wall, \" + j + \" bottles of beer.\\n\";\n out += \"Take one down and pass it around, \" + (j-1) + \" bottles of beer.\\n\\n\";\n }\n out += \"1 bottle of beer on the wall, 1 bottle of beer.\\n\" +\n \"Take one down and pass it around, no more bottles of beer on the wall.\\n\\n\" +\n \"No more bottles of beer on the wall, no more bottles of beer.\\n\" +\n \"Go to the store and buy some more, 99 bottles of beer on the wall.\\n\";\n break;\n case '+': acc++; break;\n }\n }\n return out;\n}"} {"title": "FASTA format", "language": "JavaScript", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "const fs = require(\"fs\");\nconst readline = require(\"readline\");\n \nconst args = process.argv.slice(2);\nif (!args.length) {\n console.error(\"must supply file name\");\n process.exit(1);\n}\n \nconst fname = args[0];\n \nconst readInterface = readline.createInterface({\n input: fs.createReadStream(fname),\n console: false,\n});\n \nlet sep = \"\";\nreadInterface.on(\"line\", (line) => {\n if (line.startsWith(\">\")) {\n process.stdout.write(sep);\n sep = \"\\n\";\n process.stdout.write(line.substring(1) + \": \");\n } else {\n process.stdout.write(line);\n }\n});\n\nreadInterface.on(\"close\", () => process.stdout.write(\"\\n\"));\n"} {"title": "Fairshare between two and more", "language": "JavaScript", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "(() => {\n 'use strict';\n\n // thueMorse :: Int -> [Int]\n const thueMorse = base =>\n // Thue-Morse sequence for a given base\n fmapGen(baseDigitsSumModBase(base))(\n enumFrom(0)\n )\n\n // baseDigitsSumModBase :: Int -> Int -> Int\n const baseDigitsSumModBase = base =>\n // For any integer n, the sum of its digits\n // in a given base, modulo that base.\n n => sum(unfoldl(\n x => 0 < x ? (\n Just(quotRem(x)(base))\n ) : Nothing()\n )(n)) % base\n\n\n // ------------------------TEST------------------------\n const main = () =>\n console.log(\n fTable(\n 'First 25 fairshare terms for a given number of players:'\n )(str)(\n xs => '[' + map(\n compose(justifyRight(2)(' '), str)\n )(xs) + ' ]'\n )(\n compose(take(25), thueMorse)\n )([2, 3, 5, 11])\n );\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fTable :: String -> (a -> String) -> (b -> String)\n // -> (a -> b) -> [a] -> String\n const fTable = s => xShow => fxShow => f => xs => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n a => b => a.padStart(w, ' ') + ' -> ' + b\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f to each element of xs.\n // (The image of xs under f).\n xs => (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = m => n =>\n Tuple(Math.floor(m / n))(\n m % n\n );\n\n // str :: a -> String\n const str = x => x.toString();\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\n const unfoldl = f => v => {\n // Dual to reduce or foldl.\n // Where these reduce a list to a summary value, unfoldl\n // builds a list from a seed value.\n // Where f returns Just(a, b), a is appended to the list,\n // and the residual b is used as the argument for the next\n // application of f.\n // Where f returns Nothing, the completed list is returned.\n let\n xr = [v, v],\n xs = [];\n while (true) {\n const mb = f(xr[0]);\n if (mb.Nothing) {\n return xs\n } else {\n xr = mb.Just;\n xs = [xr[1]].concat(xs);\n }\n }\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Fast Fourier transform", "language": "JavaScript", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "/*\ncomplex fast fourier transform and inverse from\nhttp://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B\n*/\nfunction icfft(amplitudes)\n{\n\tvar N = amplitudes.length;\n\tvar iN = 1 / N;\n\t\n\t//conjugate if imaginary part is not 0\n\tfor(var i = 0 ; i < N; ++i)\n\t\tif(amplitudes[i] instanceof Complex)\n\t\t\tamplitudes[i].im = -amplitudes[i].im;\n\t\t\t\n\t//apply fourier transform\n\tamplitudes = cfft(amplitudes)\n\t\n\tfor(var i = 0 ; i < N; ++i)\n\t{\n\t\t//conjugate again\n\t\tamplitudes[i].im = -amplitudes[i].im;\n\t\t//scale\n\t\tamplitudes[i].re *= iN;\n\t\tamplitudes[i].im *= iN;\n\t}\n\treturn amplitudes;\n}\n\nfunction cfft(amplitudes)\n{\n\tvar N = amplitudes.length;\n\tif( N <= 1 )\n\t\treturn amplitudes;\n\t\n\tvar hN = N / 2;\n\tvar even = [];\n\tvar odd = [];\n\teven.length = hN;\n\todd.length = hN;\n\tfor(var i = 0; i < hN; ++i)\n\t{\n\t\teven[i] = amplitudes[i*2];\n\t\todd[i] = amplitudes[i*2+1];\n\t}\n\teven = cfft(even);\n\todd = cfft(odd);\n\t\n\tvar a = -2*Math.PI;\n\tfor(var k = 0; k < hN; ++k)\n\t{\n\t\tif(!(even[k] instanceof Complex))\n\t\t\teven[k] = new Complex(even[k], 0);\n\t\tif(!(odd[k] instanceof Complex))\n\t\t\todd[k] = new Complex(odd[k], 0);\n\t\tvar p = k/N;\n\t\tvar t = new Complex(0, a * p);\n\t\tt.cexp(t).mul(odd[k], t);\n\t\tamplitudes[k] = even[k].add(t, odd[k]);\n\t\tamplitudes[k + hN] = even[k].sub(t, even[k]);\n\t}\n\treturn amplitudes;\n}\n\n//test code\n//console.log( cfft([1,1,1,1,0,0,0,0]) );\n//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );"} {"title": "Fibonacci n-step number sequences", "language": "JavaScript", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "function fib(arity, len) {\n return nacci(nacci([1,1], arity, arity), arity, len);\n}\n\nfunction lucas(arity, len) {\n return nacci(nacci([2,1], arity, arity), arity, len);\n}\n\nfunction nacci(a, arity, len) {\n while (a.length < len) {\n var sum = 0;\n for (var i = Math.max(0, a.length - arity); i < a.length; i++)\n sum += a[i];\n a.push(sum);\n }\n return a;\n}\n\nfunction main() {\n for (var arity = 2; arity <= 10; arity++)\n console.log(\"fib(\" + arity + \"): \" + fib(arity, 15));\n for (var arity = 2; arity <= 10; arity++)\n console.log(\"lucas(\" + arity + \"): \" + lucas(arity, 15));\n}\n\nmain();"} {"title": "Fibonacci word", "language": "JavaScript", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "//makes outputting a table possible in environments \n//that don't support console.table() \nfunction console_table(xs) {\n function pad(n,s) {\n var res = s;\n for (var i = s.length; i < n; i++)\n res += \" \";\n return res;\n }\n\n if (xs.length === 0)\n console.log(\"No data\");\n else {\n var widths = [];\n var cells = [];\n for (var i = 0; i <= xs.length; i++)\n cells.push([]);\n \n for (var s in xs[0]) {\n var len = s.length;\n cells[0].push(s);\n \n for (var i = 0; i < xs.length; i++) {\n var ss = \"\" + xs[i][s];\n len = Math.max(len, ss.length);\n cells[i+1].push(ss);\n }\n widths.push(len);\n }\n var s = \"\";\n for (var x = 0; x < cells.length; x++) {\n for (var y = 0; y < widths.length; y++)\n s += \"|\" + pad(widths[y], cells[x][y]);\n s += \"|\\n\";\n }\n console.log(s);\n }\n}\n\n//returns the entropy of a string as a number \nfunction entropy(s) {\n //create an object containing each individual char\n\t//and the amount of iterations per char \n function prob(s) {\n var h = Object.create(null);\n s.split('').forEach(function(c) {\n h[c] && h[c]++ || (h[c] = 1); \n });\n return h;\n }\n \n s = s.toString(); //just in case \n var e = 0, l = s.length, h = prob(s);\n \n for (var i in h ) {\n var p = h[i]/l;\n e -= p * Math.log(p) / Math.log(2);\n }\n return e;\n}\n\n//creates Fibonacci Word to n as described on Rosetta Code\n//see rosettacode.org/wiki/Fibonacci_word\nfunction fibWord(n) {\n var wOne = \"1\", wTwo = \"0\", wNth = [wOne, wTwo], w = \"\", o = [];\n \n for (var i = 0; i < n; i++) {\n if (i === 0 || i === 1) {\n w = wNth[i];\n } else {\n w = wNth[i - 1] + wNth[i - 2];\n wNth.push(w);\n }\n var l = w.length;\n var e = entropy(w);\n \n if (l <= 21) {\n \to.push({\n \tN: i + 1,\n \tLength: l,\n \tEntropy: e,\n \tWord: w\n \t});\n } else {\n \to.push({\n \tN: i + 1,\n \tLength: l,\n \tEntropy: e,\n \tWord: \"...\"\n \t});\n } \n }\n \n try {\n \tconsole.table(o);\n } catch (err) {\n \tconsole_table(o);\n }\n}\n\nfibWord(37);"} {"title": "File extension is in extensions list", "language": "JavaScript", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "function fileExtensionInExtensionsList(filename) {\n\tlet foundIt = false;\n\tlet filenameLC = filename.toLowerCase();\n\tlet extensions = [\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\" ,\"tar.bz2\"];\n\textensions.forEach(extension => {\n\t\tif (filenameLC.endsWith(\".\" + extension.toLowerCase())) { foundIt = true; }\n\t} );\n\treturn foundIt;\n}\n\n// perform tests below\n\nvar fileNamesToTest = [\n\t\"MyData.a##\"\n\t,\"MyData.tar.Gz\"\n\t,\"MyData.gzip\"\n\t,\"MyData.7z.backup\"\n\t,\"MyData...\"\n\t,\"MyData\"\n\t,\"MyData_v1.0.tar.bz2\"\n\t,\"MyData_v1.0.bz2\"\n];\n\nfileNamesToTest.forEach(filename => {\n\tconsole.log(filename + \" -> \" + fileExtensionInExtensionsList(filename));\n});\n"} {"title": "Find limit of recursion", "language": "JavaScript", "task": "{{selection|Short Circuit|Console Program Basics}}\n\n \n\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "function recurse(depth)\n{\n try\n {\n return recurse(depth + 1);\n }\n catch(ex)\n {\n return depth;\n }\n}\n\nvar maxRecursion = recurse(1);\ndocument.write(\"Recursion depth on this system is \" + maxRecursion);"} {"title": "Find palindromic numbers in both binary and ternary bases", "language": "JavaScript from Haskell", "task": "* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':\n:::* base 2\n:::* base 3\n* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\n\nIt's permissible to assume the first two numbers and simply list them.\n\n\n;See also\n* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "(() => {\n 'use strict';\n\n // GENERIC FUNCTIONS\n\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // compose :: (b -> c) -> (a -> b) -> (a -> c)\n const compose = (f, g) => x => f(g(x));\n\n // listApply :: [(a -> b)] -> [a] -> [b]\n const listApply = (fs, xs) =>\n [].concat.apply([], fs.map(f =>\n [].concat.apply([], xs.map(x => [f(x)]))));\n\n // pure :: a -> [a]\n const pure = x => [x];\n\n // curry :: Function -> Function\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :\n function () {\n return go(xs.concat([].slice.apply(arguments)));\n };\n return go([].slice.call(args, 1));\n };\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map(row => row[iCol]));\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n typeof xs === 'string' ? (\n xs.split('')\n .reverse()\n .join('')\n ) : xs.slice(0)\n .reverse();\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, n);\n\n // drop :: Int -> [a] -> [a]\n const drop = (n, xs) => xs.slice(n);\n\n // maximum :: [a] -> a\n const maximum = xs =>\n xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined);\n\n // quotRem :: Integral a => a -> a -> (a, a)\n const quotRem = (m, n) => [Math.floor(m / n), m % n];\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // justifyLeft :: Int -> Char -> Text -> Text\n const justifyLeft = (n, cFiller, strText) =>\n n > strText.length ? (\n (strText + cFiller.repeat(n))\n .substr(0, n)\n ) : strText;\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n\n // BASES AND PALINDROMES\n\n // show, showBinary, showTernary :: Int -> String\n const show = n => n.toString(10);\n const showBinary = n => n.toString(2);\n const showTernary = n => n.toString(3);\n\n // readBase3 :: String -> Int\n const readBase3 = s => parseInt(s, 3);\n\n // base3Palindrome :: Int -> String\n const base3Palindrome = n => {\n const s = showTernary(n);\n return s + '1' + reverse(s);\n };\n\n // isBinPal :: Int -> Bool\n const isBinPal = n => {\n const\n s = showBinary(n),\n [q, r] = quotRem(s.length, 2);\n return (r !== 0) && drop(q + 1, s) === reverse(take(q, s));\n };\n\n // solutions :: [Int]\n const solutions = [0, 1].concat(range(1, 10E5)\n .map(compose(readBase3, base3Palindrome))\n .filter(isBinPal));\n\n // TABULATION\n\n // cols :: [[Int]]\n const cols = transpose(\n [\n ['Decimal', 'Ternary', 'Binary']\n ].concat(\n solutions.map(\n compose(\n xs => listApply([show, showTernary, showBinary], xs),\n pure\n )\n )\n )\n );\n\n return unlines(\n transpose(cols.map(col => col.map(\n curry(justifyLeft)(maximum(col.map(length)) + 1, ' ')\n )))\n .map(unwords));\n})();"} {"title": "Find the intersection of two lines", "language": "JavaScript from Haskell", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "(() => {\n 'use strict';\n // INTERSECTION OF TWO LINES ----------------------------------------------\n\n // intersection :: Line -> Line -> Either String (Float, Float)\n const intersection = (ab, pq) => {\n const\n delta = f => x => f(fst(x)) - f(snd(x)),\n [abDX, pqDX, abDY, pqDY] = apList(\n [delta(fst), delta(snd)], [ab, pq]\n ),\n determinant = abDX * pqDY - abDY * pqDX;\n\n return determinant !== 0 ? Right((() => {\n const [abD, pqD] = map(\n ([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),\n [ab, pq]\n );\n return apList(\n [([pq, ab]) =>\n (abD * pq - ab * pqD) / determinant\n ], [\n [pqDX, abDX],\n [pqDY, abDY]\n ]\n );\n })()) : Left('(Parallel lines \u2013 no intersection)');\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: 'Either',\n Left: x\n });\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: 'Either',\n Right: x\n });\n\n // A list of functions applied to a list of arguments\n // <*> :: [(a -> b)] -> [a] -> [b]\n const apList = (fs, xs) => //\n [].concat.apply([], fs.map(f => //\n [].concat.apply([], xs.map(x => [f(x)]))));\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // show :: a -> String\n const show = x => JSON.stringify(x); //, null, 2);\n\n\n // TEST --------------------------------------------------\n\n // lrIntersection ::Either String Point\n const lrIntersection = intersection([\n [4.0, 0.0],\n [6.0, 10.0]\n ], [\n [0.0, 3.0],\n [10.0, 7.0]\n ]);\n return show(lrIntersection.Left || lrIntersection.Right);\n})();"} {"title": "Find the last Sunday of each month", "language": "JavaScript", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "function lastSundayOfEachMonths(year) {\n\tvar lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tvar sundays = [];\n\tvar date, month;\n\tif (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {\n\t\tlastDay[2] = 29;\n\t}\n\tfor (date = new Date(), month = 0; month < 12; month += 1) {\n\t\tdate.setFullYear(year, month, lastDay[month]);\n\t\tdate.setDate(date.getDate() - date.getDay());\n\t\tsundays.push(date.toISOString().substring(0, 10));\n\t}\n\treturn sundays;\n}\n\nconsole.log(lastSundayOfEachMonths(2013).join('\\n'));"} {"title": "Find the missing permutation", "language": "JavaScript", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "(function (strList) {\n\n // [a] -> [[a]]\n function permutations(xs) {\n return xs.length ? (\n chain(xs, function (x) {\n return chain(permutations(deleted(x, xs)), function (ys) {\n return [[x].concat(ys).join('')];\n })\n })) : [[]];\n }\n\n // Monadic bind/chain for lists\n // [a] -> (a -> b) -> [b]\n function chain(xs, f) {\n return [].concat.apply([], xs.map(f));\n }\n\n // a -> [a] -> [a]\n function deleted(x, xs) {\n return xs.length ? (\n x === xs[0] ? xs.slice(1) : [xs[0]].concat(\n deleted(x, xs.slice(1))\n )\n ) : [];\n }\n\n // Provided subset\n var lstSubSet = strList.split('\\n');\n\n // Any missing permutations\n // (we can use fold/reduce, filter, or chain (concat map) here)\n return chain(permutations('ABCD'.split('')), function (x) {\n return lstSubSet.indexOf(x) === -1 ? [x] : [];\n });\n\n})(\n 'ABCD\\nCABD\\nACDB\\nDACB\\nBCDA\\nACBD\\nADCB\\nCDAB\\nDABC\\nBCAD\\nCADB\\n\\\nCDBA\\nCBAD\\nABDC\\nADBC\\nBDCA\\nDCBA\\nBACD\\nBADC\\nBDAC\\nCBDA\\nDBCA\\nDCAB'\n);"} {"title": "Find the missing permutation", "language": "JavaScript from Haskell", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "(() => {\n 'use strict';\n\n // MISSING PERMUTATION ---------------------------------------------------\n\n // missingPermutation :: [String] -> String\n const missingPermutation = xs =>\n map(\n // Rarest letter,\n compose([\n sort,\n group,\n curry(minimumBy)(comparing(length)),\n head\n ]),\n\n // in each column.\n transpose(map(stringChars, xs))\n )\n .join('');\n\n\n // GENERIC FUNCTIONAL PRIMITIVES -----------------------------------------\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map(row => row[iCol]));\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.sort();\n\n // group :: Eq a => [a] -> [[a]]\n const group = xs => groupBy((a, b) => a === b, xs);\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = (f, xs) => {\n const dct = xs.slice(1)\n .reduce((a, x) => {\n const\n h = a.active.length > 0 ? a.active[0] : undefined,\n blnGroup = h !== undefined && f(h, x);\n\n return {\n active: blnGroup ? a.active.concat(x) : [x],\n sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])\n };\n }, {\n active: xs.length > 0 ? [xs[0]] : [],\n sofar: []\n });\n return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);\n };\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n };\n\n // minimumBy :: (a -> a -> Ordering) -> [a] -> a\n const minimumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) < 0 ? x : a\n ), undefined);\n\n // head :: [a] -> a\n const head = xs => xs.length ? xs[0] : undefined;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f)\n\n // compose :: [(a -> a)] -> (a -> a)\n const compose = fs => x => fs.reduce((a, f) => f(a), x);\n\n // curry :: ((a, b) -> c) -> a -> b -> c\n const curry = f => a => b => f(a, b);\n\n // stringChars :: String -> [Char]\n const stringChars = s => s.split('');\n\n\n // TEST ------------------------------------------------------------------\n\n return missingPermutation([\"ABCD\", \"CABD\", \"ACDB\", \"DACB\", \"BCDA\", \"ACBD\",\n \"ADCB\", \"CDAB\", \"DABC\", \"BCAD\", \"CADB\", \"CDBA\", \"CBAD\", \"ABDC\", \"ADBC\",\n \"BDCA\", \"DCBA\", \"BACD\", \"BADC\", \"BDAC\", \"CBDA\", \"DBCA\", \"DCAB\"\n ]);\n\n // -> \"DBAC\"\n})();"} {"title": "First-class functions/Use numbers analogously", "language": "JavaScript", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "const x = 2.0;\nconst xi = 0.5;\nconst y = 4.0;\nconst yi = 0.25;\nconst z = x + y;\nconst zi = 1.0 / (x + y);\nconst pairs = [[x, xi], [y, yi], [z, zi]];\nconst testVal = 0.5;\n\nconst multiplier = (a, b) => m => a * b * m;\n\nconst test = () => {\n return pairs.map(([a, b]) => {\n const f = multiplier(a, b);\n const result = f(testVal);\n return `${a} * ${b} * ${testVal} = ${result}`;\n });\n}\n\ntest().join('\\n');"} {"title": "First perfect square in base n with n unique digits", "language": "JavaScript from Python", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "(() => {\n 'use strict';\n\n // allDigitSquare :: Int -> Int\n const allDigitSquare = base => {\n const bools = replicate(base, false);\n return untilSucc(\n allDigitsUsedAtBase(base, bools),\n ceil(sqrt(parseInt(\n '10' + '0123456789abcdef'.slice(2, base),\n base\n )))\n );\n };\n\n // allDigitsUsedAtBase :: Int -> [Bool] -> Int -> Bool\n const allDigitsUsedAtBase = (base, bools) => n => {\n // Fusion of representing the square of integer N at a given base\n // with checking whether all digits of that base contribute to N^2.\n // Sets the bool at a digit position to True when used.\n // True if all digit positions have been used.\n const ds = bools.slice(0);\n let x = n * n;\n while (x) {\n ds[x % base] = true;\n x = floor(x / base);\n }\n return ds.every(x => x)\n };\n\n // showBaseSquare :: Int -> String\n const showBaseSquare = b => {\n const q = allDigitSquare(b);\n return justifyRight(2, ' ', str(b)) + ' -> ' +\n justifyRight(8, ' ', showIntAtBase(b, digit, q, '')) +\n ' -> ' + showIntAtBase(b, digit, q * q, '');\n };\n\n // TEST -----------------------------------------------\n const main = () => {\n // 1-12 only - by 15 the squares are truncated by\n // JS integer limits.\n\n // Returning values through console.log \u2013\n // in separate events to avoid asynchronous disorder.\n print('Smallest perfect squares using all digits in bases 2-12:\\n')\n (id > 0 ? chars.substr(id, 1) : \" \") print('Base Root Square')\n\n print(showBaseSquare(2));\n print(showBaseSquare(3));\n print(showBaseSquare(4));\n print(showBaseSquare(5));\n print(showBaseSquare(6));\n print(showBaseSquare(7));\n print(showBaseSquare(8));\n print(showBaseSquare(9));\n print(showBaseSquare(10));\n print(showBaseSquare(11));\n print(showBaseSquare(12));\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n \n const\n ceil = Math.ceil,\n floor = Math.floor,\n sqrt = Math.sqrt;\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // digit :: Int -> Char\n const digit = n =>\n // Digit character for given integer.\n '0123456789abcdef' [n];\n\n // enumFromTo :: (Int, Int) -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // print :: a -> IO ()\n const print = x => console.log(x)\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = (m, n) =>\n Tuple(Math.floor(m / n), m % n);\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, x) =>\n Array.from({\n length: n\n }, () => x);\n\n // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String\n const showIntAtBase = (base, toChr, n, rs) => {\n const go = ([n, d], r) => {\n const r_ = toChr(d) + r;\n return 0 !== n ? (\n go(Array.from(quotRem(n, base)), r_)\n ) : r_;\n };\n return 1 >= base ? (\n 'error: showIntAtBase applied to unsupported base'\n ) : 0 > n ? (\n 'error: showIntAtBase applied to negative number'\n ) : go(Array.from(quotRem(n, base)), rs);\n };\n\n // Abbreviation for quick testing - any 2nd arg interpreted as indent size\n\n // sj :: a -> String\n function sj() {\n const args = Array.from(arguments);\n return JSON.stringify.apply(\n null,\n 1 < args.length && !isNaN(args[0]) ? [\n args[1], null, args[0]\n ] : [args[0], null, 2]\n );\n }\n\n // str :: a -> String\n const str = x => x.toString();\n\n // untilSucc :: (Int -> Bool) -> Int -> Int\n const untilSucc = (p, x) => {\n // The first in a chain of successive integers\n // for which p(x) returns true.\n let v = x;\n while (!p(v)) v = 1 + v;\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Fivenum", "language": "JavaScript", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "function median(arr) {\n let mid = Math.floor(arr.length / 2);\n return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid];\n}\n\nArray.prototype.fiveNums = function() {\n this.sort(function(a, b) { return a - b} );\n let mid = Math.floor(this.length / 2),\n loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1),\n hiQ = this.slice(mid);\n return [ this[0],\n median(loQ),\n median(this),\n median(hiQ),\n this[this.length-1] ];\n}\n\n// testing\nlet test = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43];\nconsole.log( test.fiveNums() );\n\ntest = [0, 0, 1, 2, 63, 61, 27, 13];\nconsole.log( test.fiveNums() );\n\ntest = [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578];\nconsole.log( test.fiveNums() );\n"} {"title": "Flatten a list", "language": "JavaScript", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "(function () {\n 'use strict';\n\n // flatten :: Tree a -> [a]\n function flatten(t) {\n return (t instanceof Array ? concatMap(flatten, t) : t);\n }\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n function concatMap(f, xs) {\n return [].concat.apply([], xs.map(f));\n }\n\n return flatten(\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\n );\n\n})();"} {"title": "Flipping bits game", "language": "JavaScript", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "function numOfRows(board) { return board.length; }\nfunction numOfCols(board) { return board[0].length; }\nfunction boardToString(board) {\n // First the top-header\n var header = ' ';\n for (var c = 0; c < numOfCols(board); c++)\n header += c + ' ';\n \n // Then the side-header + board\n var sideboard = [];\n for (var r = 0; r < numOfRows(board); r++) {\n sideboard.push(r + ' [' + board[r].join(' ') + ']');\n }\n \n return header + '\\n' + sideboard.join('\\n');\n}\nfunction flipRow(board, row) {\n for (var c = 0; c < numOfCols(board); c++) {\n board[row][c] = 1 - board[row][c];\n }\n}\nfunction flipCol(board, col) {\n for (var r = 0; r < numOfRows(board); r++) {\n board[r][col] = 1 - board[r][col];\n }\n}\n\nfunction playFlippingBitsGame(rows, cols) {\n rows = rows | 3;\n cols = cols | 3;\n var targetBoard = [];\n var manipulatedBoard = [];\n // Randomly generate two identical boards.\n for (var r = 0; r < rows; r++) {\n targetBoard.push([]);\n manipulatedBoard.push([]);\n for (var c = 0; c < cols; c++) {\n targetBoard[r].push(Math.floor(Math.random() * 2));\n manipulatedBoard[r].push(targetBoard[r][c]);\n }\n }\n // Naive-scramble one of the boards.\n while (boardToString(targetBoard) == boardToString(manipulatedBoard)) {\n var scrambles = rows * cols;\n while (scrambles-- > 0) {\n if (0 == Math.floor(Math.random() * 2)) {\n flipRow(manipulatedBoard, Math.floor(Math.random() * rows));\n }\n else {\n flipCol(manipulatedBoard, Math.floor(Math.random() * cols));\n }\n }\n }\n // Get the user to solve.\n alert(\n 'Try to match both boards.\\n' +\n 'Enter `r` or `c` to manipulate a row or col or enter `q` to quit.'\n );\n var input = '', letter, num, moves = 0;\n while (boardToString(targetBoard) != boardToString(manipulatedBoard) && input != 'q') {\n input = prompt(\n 'Target:\\n' + boardToString(targetBoard) +\n '\\n\\n\\n' +\n 'Board:\\n' + boardToString(manipulatedBoard)\n );\n try {\n letter = input.charAt(0);\n num = parseInt(input.slice(1));\n if (letter == 'q')\n\t\t\t\tbreak;\n if (isNaN(num)\n || (letter != 'r' && letter != 'c')\n || (letter == 'r' && num >= rows)\n || (letter == 'c' && num >= cols)\n ) {\n throw new Error('');\n }\n if (letter == 'r') {\n flipRow(manipulatedBoard, num);\n }\n else {\n flipCol(manipulatedBoard, num);\n }\n moves++;\n }\n catch(e) {\n alert('Uh-oh, there seems to have been an input error');\n }\n }\n if (input == 'q') {\n alert('~~ Thanks for playing ~~');\n }\n else {\n alert('Completed in ' + moves + ' moves.');\n }\n}"} {"title": "Floyd's triangle", "language": "JavaScript", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "(function () {\n 'use strict';\n\n // FLOYD's TRIANGLE -------------------------------------------------------\n\n // floyd :: Int -> [[Int]]\n function floyd(n) {\n return snd(mapAccumL(function (start, row) {\n return [start + row + 1, enumFromTo(start, start + row)];\n }, 1, enumFromTo(0, n - 1)));\n };\n\n // showFloyd :: [[Int]] -> String\n function showFloyd(xss) {\n var ws = map(compose([succ, length, show]), last(xss));\n return unlines(map(function (xs) {\n return concat(zipWith(function (w, x) {\n return justifyRight(w, ' ', show(x));\n }, ws, xs));\n }, xss));\n };\n\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // compose :: [(a -> a)] -> (a -> a)\n function compose(fs) {\n return function (x) {\n return fs.reduceRight(function (a, f) {\n return f(a);\n }, x);\n };\n };\n\n // concat :: [[a]] -> [a] | [String] -> String\n function concat(xs) {\n if (xs.length > 0) {\n var unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n } else return [];\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n function enumFromTo(m, n) {\n return Array.from({\n length: Math.floor(n - m) + 1\n }, function (_, i) {\n return m + i;\n });\n };\n\n // justifyRight :: Int -> Char -> Text -> Text\n function justifyRight(n, cFiller, strText) {\n return n > strText.length ? (cFiller.repeat(n) + strText)\n .slice(-n) : strText;\n };\n\n // last :: [a] -> a\n function last(xs) {\n return xs.length ? xs.slice(-1)[0] : undefined;\n };\n\n // length :: [a] -> Int\n function length(xs) {\n return xs.length;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n function map(f, xs) {\n return xs.map(f);\n };\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See hoogle )\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n function mapAccumL(f, acc, xs) {\n return xs.reduce(function (a, x) {\n var pair = f(a[0], x);\n\n return [pair[0], a[1].concat([pair[1]])];\n }, [acc, []]);\n };\n\n // show ::\n // (a -> String) f, Num n =>\n // a -> maybe f -> maybe n -> String\n var show = JSON.stringify;\n\n // snd :: (a, b) -> b\n function snd(tpl) {\n return Array.isArray(tpl) ? tpl[1] : undefined;\n };\n\n // succ :: Int -> Int\n function succ(x) {\n return x + 1;\n };\n\n // unlines :: [String] -> String\n function unlines(xs) {\n return xs.join('\\n');\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n function zipWith(f, xs, ys) {\n var ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map(function (x, i) {\n return f(x, ys[i]);\n });\n };\n\n // TEST ( n=5 and n=14 rows ) ---------------------------------------------\n\n return unlines(map(function (n) {\n return showFloyd(floyd(n)) + '\\n';\n }, [5, 14]));\n})();"} {"title": "Floyd's triangle", "language": "JavaScript from Haskell", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "(() => {\n 'use strict';\n\n // FLOYD's TRIANGLE -------------------------------------------------------\n\n // floyd :: Int -> [[Int]]\n const floyd = n => snd(mapAccumL(\n (start, row) => [start + row + 1, enumFromTo(start, start + row)],\n 1, enumFromTo(0, n - 1)\n ));\n\n // showFloyd :: [[Int]] -> String\n const showFloyd = xss => {\n const ws = map(compose([succ, length, show]), last(xss));\n return unlines(\n map(xs => concat(zipWith(\n (w, x) => justifyRight(w, ' ', show(x)), ws, xs\n )),\n xss\n )\n );\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // compose :: [(a -> a)] -> (a -> a)\n const compose = fs => x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a] | [String] -> String\n const concat = xs => {\n if (xs.length > 0) {\n const unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n } else return [];\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (cFiller.repeat(n) + strText)\n .slice(-n)\n ) : strText;\n\n // last :: [a] -> a\n const last = xs => xs.length ? xs.slice(-1)[0] : undefined;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f)\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See hoogle )\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = (f, acc, xs) =>\n xs.reduce((a, x) => {\n const pair = f(a[0], x);\n\n return [pair[0], a[1].concat([pair[1]])];\n }, [acc, []]);\n\n // show ::\n // (a -> String) f, Num n =>\n // a -> maybe f -> maybe n -> String\n const show = JSON.stringify;\n\n // snd :: (a, b) -> b\n const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined;\n\n // succ :: Int -> Int\n const succ = x => x + 1\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map((x, i) => f(x, ys[i]));\n };\n\n // TEST ( n=5 and n=14 rows ) ---------------------------------------------\n\n return unlines(map(n => showFloyd(floyd(n)) + '\\n', [5, 14]))\n})();"} {"title": "Four bit adder", "language": "JavaScript", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "// basic building blocks allowed by the rules are ~, &, and |, we'll fake these\n// in a way that makes what they do (at least when you use them) more obvious \n// than the other available options do.\n\nfunction not(a) {\n if (arePseudoBin(a))\n return a == 1 ? 0 : 1;\n}\n\nfunction and(a, b) {\n if (arePseudoBin(a, b))\n return a + b < 2 ? 0 : 1;\n}\n\nfunction nand(a, b) {\n if (arePseudoBin(a, b))\n return not(and(a, b));\n}\n\nfunction or(a, b) {\n if (arePseudoBin(a, b))\n return nand(nand(a,a), nand(b,b));\n}\n\nfunction xor(a, b) {\n if (arePseudoBin(a, b))\n return nand(nand(nand(a,b), a), nand(nand(a,b), b));\n}\n\nfunction halfAdder(a, b) {\n if (arePseudoBin(a, b))\n return { carry: and(a, b), sum: xor(a, b) };\n}\n\nfunction fullAdder(a, b, c) {\n if (arePseudoBin(a, b, c)) {\n var h0 = halfAdder(a, b), \n h1 = halfAdder(h0.sum, c);\n return {carry: or(h0.carry, h1.carry), sum: h1.sum };\n }\n}\n\nfunction fourBitAdder(a, b) {\n if (typeof a.length == 'undefined' || typeof b.length == 'undefined')\n throw new Error('bad values');\n // not sure if the rules allow this, but we need to pad the values \n // if they're too short and trim them if they're too long\n var inA = Array(4), \n inB = Array(4), \n out = Array(4), \n i = 4, \n pass;\n \n while (i--) {\n inA[i] = a[i] != 1 ? 0 : 1;\n inB[i] = b[i] != 1 ? 0 : 1;\n }\n\n // now we can start adding... I'd prefer to do this in a loop, \n // but that wouldn't be \"connecting the other 'constructive blocks', \n // in turn made of 'simpler' and 'smaller' ones\"\n \n pass = halfAdder(inA[3], inB[3]);\n out[3] = pass.sum;\n pass = fullAdder(inA[2], inB[2], pass.carry);\n out[2] = pass.sum;\n pass = fullAdder(inA[1], inB[1], pass.carry);\n out[1] = pass.sum;\n pass = fullAdder(inA[0], inB[0], pass.carry);\n out[0] = pass.sum;\n return out.join('');\n}\n"} {"title": "Four is magic", "language": "JavaScript", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "const reverseOrderedNumberToTextMap = (function () {\n const rawNumberToTextMapping = { // Ported over from the Python solution.\n [1n]: \"one\",\n [2n]: \"two\",\n [3n]: \"three\",\n [4n]: \"four\",\n [5n]: \"five\",\n [6n]: \"six\",\n [7n]: \"seven\",\n [8n]: \"eight\",\n [9n]: \"nine\",\n [10n]: \"ten\",\n [11n]: \"eleven\",\n [12n]: \"twelve\",\n [13n]: \"thirteen\",\n [14n]: \"fourteen\",\n [15n]: \"fifteen\",\n [16n]: \"sixteen\",\n [17n]: \"seventeen\",\n [18n]: \"eighteen\",\n [19n]: \"nineteen\",\n [20n]: \"twenty\",\n [30n]: \"thirty\",\n [40n]: \"forty\",\n [50n]: \"fifty\",\n [60n]: \"sixty\",\n [70n]: \"seventy\",\n [80n]: \"eighty\",\n [90n]: \"ninety\",\n [100n]: \"hundred\",\n [1000n]: \"thousand\",\n [10n ** 6n]: \"million\",\n [10n ** 9n]: \"billion\",\n [10n ** 12n]: \"trillion\",\n [10n ** 15n]: \"quadrillion\",\n [10n ** 18n]: \"quintillion\",\n [10n ** 21n]: \"sextillion\",\n [10n ** 24n]: \"septillion\",\n [10n ** 27n]: \"octillion\",\n [10n ** 30n]: \"nonillion\",\n [10n ** 33n]: \"decillion\",\n [10n ** 36n]: \"undecillion\",\n [10n ** 39n]: \"duodecillion\",\n [10n ** 42n]: \"tredecillion\",\n [10n ** 45n]: \"quattuordecillion\",\n [10n ** 48n]: \"quinquadecillion\",\n [10n ** 51n]: \"sedecillion\",\n [10n ** 54n]: \"septendecillion\",\n [10n ** 57n]: \"octodecillion\",\n [10n ** 60n]: \"novendecillion\",\n [10n ** 63n]: \"vigintillion\",\n [10n ** 66n]: \"unvigintillion\",\n [10n ** 69n]: \"duovigintillion\",\n [10n ** 72n]: \"tresvigintillion\",\n [10n ** 75n]: \"quattuorvigintillion\",\n [10n ** 78n]: \"quinquavigintillion\",\n [10n ** 81n]: \"sesvigintillion\",\n [10n ** 84n]: \"septemvigintillion\",\n [10n ** 87n]: \"octovigintillion\",\n [10n ** 90n]: \"novemvigintillion\",\n [10n ** 93n]: \"trigintillion\",\n [10n ** 96n]: \"untrigintillion\",\n [10n ** 99n]: \"duotrigintillion\",\n [10n ** 102n]: \"trestrigintillion\",\n [10n ** 105n]: \"quattuortrigintillion\",\n [10n ** 108n]: \"quinquatrigintillion\",\n [10n ** 111n]: \"sestrigintillion\",\n [10n ** 114n]: \"septentrigintillion\",\n [10n ** 117n]: \"octotrigintillion\",\n [10n ** 120n]: \"noventrigintillion\",\n [10n ** 123n]: \"quadragintillion\",\n [10n ** 153n]: \"quinquagintillion\",\n [10n ** 183n]: \"sexagintillion\",\n [10n ** 213n]: \"septuagintillion\",\n [10n ** 243n]: \"octogintillion\",\n [10n ** 273n]: \"nonagintillion\",\n [10n ** 303n]: \"centillion\",\n [10n ** 306n]: \"uncentillion\",\n [10n ** 309n]: \"duocentillion\",\n [10n ** 312n]: \"trescentillion\",\n [10n ** 333n]: \"decicentillion\",\n [10n ** 336n]: \"undecicentillion\",\n [10n ** 363n]: \"viginticentillion\",\n [10n ** 366n]: \"unviginticentillion\",\n [10n ** 393n]: \"trigintacentillion\",\n [10n ** 423n]: \"quadragintacentillion\",\n [10n ** 453n]: \"quinquagintacentillion\",\n [10n ** 483n]: \"sexagintacentillion\",\n [10n ** 513n]: \"septuagintacentillion\",\n [10n ** 543n]: \"octogintacentillion\",\n [10n ** 573n]: \"nonagintacentillion\",\n [10n ** 603n]: \"ducentillion\",\n [10n ** 903n]: \"trecentillion\",\n [10n ** 1203n]: \"quadringentillion\",\n [10n ** 1503n]: \"quingentillion\",\n [10n ** 1803n]: \"sescentillion\",\n [10n ** 2103n]: \"septingentillion\",\n [10n ** 2403n]: \"octingentillion\",\n [10n ** 2703n]: \"nongentillion\",\n [10n ** 3003n]: \"millinillion\"\n };\n\n return new Map(Object.entries(rawNumberToTextMapping)\n .sort((a, b) => BigInt(a[0]) > BigInt(b[0]) ? -1 : 1)\n .map(numberAndText => [BigInt(numberAndText[0]), numberAndText[1]]));\n})();\n\n\nfunction getCardinalRepresentation(number)\n{\n if (number == 0n)\n {\n return \"zero\";\n }\n\n function* generateCardinalRepresentationTokens(number)\n {\n if (number <= 0n)\n {\n yield \"negative\";\n number *= -1n;\n }\n\n for (const [currentEntryNumber, currentEntryText] of reverseOrderedNumberToTextMap.entries())\n {\n if (number >= currentEntryNumber)\n {\n if (currentEntryNumber >= 100n)\n {\n yield* generateCardinalRepresentationTokens(number / currentEntryNumber);\n }\n\n yield currentEntryText;\n number -= currentEntryNumber;\n }\n }\n }\n\n\n return [...generateCardinalRepresentationTokens(number)].join(\" \");\n}\n\nfunction* generateFourIsMagicParts(number)\n{\n if (typeof number != \"bigint\")\n {\n number = BigInt(number);\n }\n\n if (number == 4n)\n {\n yield \"four is magic\";\n }\n else\n {\n const cardinalRepresentation = getCardinalRepresentation(number);\n yield `${cardinalRepresentation} is ${getCardinalRepresentation(BigInt(cardinalRepresentation.length))}`;\n yield* generateFourIsMagicParts(cardinalRepresentation.length);\n }\n\n}\n\nfunction capitalizeFirstLetter(str)\n{\n return str.replace(/^([a-z])/, chr => chr.toUpperCase());\n}\n\nfunction fourIsMagic(number)\n{\n return capitalizeFirstLetter(`${[...generateFourIsMagicParts(number)].join(\", \")}.`);\n}\n\n[\n 0,\n -150,\n 210,\n 10n ** 2703n + 1225n,\n 4,\n -4,\n 10n ** 3003n + 42n\n].map(fourIsMagic).join(\"\\n\\n\");"} {"title": "Function prototype", "language": "JavaScript", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "// A prototype declaration for a function that does not require arguments\nfunction List() {}\n\nList.prototype.push = function() {\n return [].push.apply(this, arguments);\n};\n\nList.prototype.pop = function() {\n return [].pop.call(this);\n};\n\nvar l = new List();\nl.push(5);\nl.length; // 1\nl[0]; 5\nl.pop(); // 5\nl.length; // 0\n\n// A prototype declaration for a function that utilizes varargs\nfunction List() {\n this.push.apply(this, arguments);\n}\n\nList.prototype.push = function() {\n return [].push.apply(this, arguments);\n};\n\nList.prototype.pop = function() {\n return [].pop.call(this);\n};\n\nvar l = new List(5, 10, 15);\nl.length; // 3\nl[0]; 5\nl.pop(); // 15\nl.length; // 2\n\n"} {"title": "Functional coverage tree", "language": "JavaScript", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "Parsing the outline text to a tree structure, and traversing this with two computations (one bottom-up, and one top-down), before serialising the updated tree to a new outline text.\n\n"} {"title": "Functional coverage tree", "language": "JavaScript from Python", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "(() => {\n 'use strict';\n\n // updatedCoverageOutline :: String -> String\n const updatedCoverageOutline = outlineText => {\n const\n delimiter = '|',\n indentedLines = indentLevelsFromLines(lines(outlineText)),\n columns = init(tokenizeWith(delimiter)(snd(indentedLines[0])));\n\n // SERIALISATION OF UPDATED PARSE TREE (TO NEW OUTLINE TEXT)\n return tabulation(delimiter)(\n columns.concat('SHARE OF RESIDUE\\n')\n ) + unlines(\n indentedLinesFromTree(\n showCoverage(delimiter))(' ')(\n\n // TWO TRAVERSAL COMPUTATIONS\n\n withResidueShares(1.0)(\n foldTree(weightedCoverage)(\n\n // PARSE TREE (FROM OUTLINE TEXT)\n fmapTree(compose(\n partialRecord, tokenizeWith(delimiter)\n ))(fst(\n forestFromLineIndents(tail(indentedLines))\n ))\n )\n ))\n );\n };\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () =>\n console.log(\n // strOutline is included as literal text\n // at the foot of this code listing.\n updatedCoverageOutline(strOutline)\n );\n\n // COVERAGE AND SHARES OF RESIDUE ---------------------\n\n // weightedCoverage :: Dict -> Forest Dict -> Tree Dict\n const weightedCoverage = x => xs => {\n const\n cws = map(compose(\n fanArrow(x => x.coverage)(x => x.weight),\n root\n ))(xs),\n totalWeight = cws.reduce((a, tpl) => a + snd(tpl), 0);\n return Node(\n insertDict('coverage')(\n cws.reduce((a, tpl) => {\n const [c, w] = Array.from(tpl);\n return a + (c * w);\n }, x.coverage) / (\n 0 < totalWeight ? totalWeight : 1\n )\n )(x)\n )(xs);\n };\n\n\n // withResidueShares :: Float -> Tree Dict -> Tree Dict\n const withResidueShares = shareOfTotal => tree => {\n const go = fraction => node => {\n const\n nodeRoot = node.root,\n forest = node.nest,\n weights = forest.map(x => x.root.weight),\n weightTotal = sum(weights);\n return Node(\n insertDict('share')(\n fraction * (1 - nodeRoot.coverage)\n )(nodeRoot)\n )(\n zipWith(go)(\n weights.map(w => fraction * (w / weightTotal))\n )(forest)\n );\n };\n return go(shareOfTotal)(tree);\n };\n\n\n // OUTLINE PARSED TO TREE -----------------------------\n\n // forestFromLineIndents :: [(Int, String)] -> [Tree String]\n const forestFromLineIndents = tuples => {\n const go = xs =>\n 0 < xs.length ? (() => {\n const [n, s] = Array.from(xs[0]);\n // Lines indented under this line,\n // tupled with all the rest.\n const [firstTreeLines, rest] = Array.from(\n span(x => n < x[0])(xs.slice(1))\n );\n // This first tree, and then the rest.\n return [Node(s)(go(firstTreeLines))]\n .concat(go(rest));\n })() : [];\n return go(tuples);\n };\n\n // indentLevelsFromLines :: [String] -> [(Int, String)]\n const indentLevelsFromLines = xs => {\n const\n indentTextPairs = xs.map(compose(\n firstArrow(length), span(isSpace)\n )),\n indentUnit = minimum(indentTextPairs.flatMap(pair => {\n const w = fst(pair);\n return 0 < w ? [w] : [];\n }));\n return indentTextPairs.map(\n firstArrow(flip(div)(indentUnit))\n );\n };\n\n // partialRecord :: [String] -> Dict\n const partialRecord = xs => {\n const [name, weightText, coverageText] = take(3)(\n xs.concat(['', '', ''])\n );\n return {\n name: name || '?',\n weight: parseFloat(weightText) || 1.0,\n coverage: parseFloat(coverageText) || 0.0,\n share: 0.0\n };\n };\n\n // tokenizeWith :: String -> String -> [String]\n const tokenizeWith = delimiter =>\n // A sequence of trimmed tokens obtained by\n // splitting s on the supplied delimiter.\n s => s.split(delimiter).map(x => x.trim());\n\n\n // TREE SERIALIZED TO OUTLINE -------------------------\n\n // indentedLinesFromTree :: (String -> a -> String) ->\n // String -> Tree a -> [String]\n const indentedLinesFromTree = showRoot =>\n strTab => tree => {\n const go = indent =>\n node => [showRoot(indent)(node.root)]\n .concat(node.nest.flatMap(go(strTab + indent)));\n return go('')(tree);\n };\n\n // showN :: Int -> Float -> String\n const showN = p =>\n n => justifyRight(7)(' ')(n.toFixed(p));\n\n // showCoverage :: String -> String -> Dict -> String\n const showCoverage = delimiter =>\n indent => x => tabulation(delimiter)(\n [indent + x.name, showN(0)(x.weight)]\n .concat([x.coverage, x.share].map(showN(4)))\n );\n\n // tabulation :: String -> [String] -> String\n const tabulation = delimiter =>\n // Up to 4 tokens drawn from the argument list,\n // as a single string with fixed left-justified\n // white-space widths, between delimiters.\n compose(\n intercalate(delimiter + ' '),\n zipWith(flip(justifyLeft)(' '))([31, 9, 9, 9])\n );\n\n\n // GENERIC AND REUSABLE FUNCTIONS ---------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = v => xs => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // div :: Int -> Int -> Int\n const div = x => y => Math.floor(x / y);\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = fl => fr => e =>\n 'Either' === e.type ? (\n undefined !== e.Left ? (\n fl(e.Left)\n ) : fr(e.Right)\n ) : undefined;\n\n // Compose a function from a simple value to a tuple of\n // the separate outputs of two different functions\n\n // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))\n const fanArrow = f => g => x => Tuple(f(x))(\n g(x)\n );\n\n // Lift a simple function to one which applies to a tuple,\n // transforming only the first item of the tuple\n\n // firstArrow :: (a -> b) -> ((a, c) -> (b, c))\n const firstArrow = f => xy => Tuple(f(xy[0]))(\n xy[1]\n );\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = f => tree => {\n const go = node => Node(f(node.root))(\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // foldTree :: (a -> [b] -> b) -> Tree a -> b\n const foldTree = f => tree => {\n const go = node => f(node.root)(\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n const foldl1 = f => xs =>\n 1 < xs.length ? xs.slice(1)\n .reduce(uncurry(f), xs[0]) : xs[0];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // init :: [a] -> [a]\n const init = xs =>\n 0 < xs.length ? (\n xs.slice(0, -1)\n ) : undefined;\n\n // insertDict :: String -> a -> Dict -> Dict\n const insertDict = k => v => dct =>\n Object.assign({}, dct, {\n [k]: v\n });\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = sep =>\n xs => xs.join(sep);\n\n // isSpace :: Char -> Bool\n const isSpace = c => /\\s/.test(c);\n\n // justifyLeft :: Int -> Char -> String -> String\n const justifyLeft = n => cFiller => s =>\n n > s.length ? (\n s.padEnd(n, cFiller)\n ) : s;\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n => cFiller => s =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // lines :: String -> [String]\n const lines = s => s.split(/[\\r\\n]/);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // minimum :: Ord a => [a] -> a\n const minimum = xs =>\n 0 < xs.length ? (\n foldl1(a => x => x < a ? x : a)(xs)\n ) : undefined;\n\n // root :: Tree a -> a\n const root = tree => tree.root;\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // span :: (a -> Bool) -> [a] -> ([a], [a])\n const span = p => xs => {\n const iLast = xs.length - 1;\n return splitAt(\n until(i => iLast < i || !p(xs[i]))(\n succ\n )(0)\n )(xs);\n };\n\n // splitAt :: Int -> [a] -> ([a], [a])\n const splitAt = n => xs =>\n Tuple(xs.slice(0, n))(\n xs.slice(n)\n );\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // sum :: [Num] -> Num\n const sum = xs =>\n xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs =>\n 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // SOURCE OUTLINE -----------------------------------------\n\n const strOutline = `NAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |`;\n\n // MAIN ---\n return main();\n})();"} {"title": "Fusc sequence", "language": "Javascript from Python", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "(() => {\n \"use strict\";\n\n // ---------------------- FUSC -----------------------\n\n // fusc :: Int -> Int\n const fusc = i => {\n const go = n =>\n 0 === n ? [\n 1, 0\n ] : (() => {\n const [x, y] = go(Math.floor(n / 2));\n\n return 0 === n % 2 ? (\n [x + y, y]\n ) : [x, x + y];\n })();\n\n return 1 > i ? (\n 0\n ) : go(i - 1)[0];\n };\n\n\n // ---------------------- TEST -----------------------\n const main = () => {\n const terms = enumFromTo(0)(60).map(fusc);\n\n return [\n \"First 61 terms:\",\n `[${terms.join(\",\")}]`,\n \"\",\n \"(Index, Value):\",\n firstWidths(5).reduce(\n (a, x) => [x.slice(1), ...a],\n []\n )\n .map(([i, x]) => `(${i}, ${x})`)\n .join(\"\\n\")\n ]\n .join(\"\\n\");\n };\n\n\n // firstWidths :: Int -> [(Int, Int)]\n const firstWidths = n => {\n const nxtWidth = xs => {\n const\n fi = fanArrow(fusc)(x => x),\n [w, i] = xs[0],\n [x, j] = Array.from(\n until(\n v => w <= `${v[0]}`.length\n )(\n v => fi(1 + v[1])\n )(fi(i))\n );\n\n return [\n [1 + w, j, x],\n ...xs\n ];\n };\n\n return until(x => n < x[0][0])(\n nxtWidth\n )([\n [2, 0, 0]\n ]);\n };\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\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 // fanArrow (&&&) ::\n // (a -> b) -> (a -> c) -> (a -> (b, c))\n const fanArrow = f =>\n // A combined function, given f and g,\n // from x to a tuple of (f(x), g(x))\n // ((,) . f <*> g)\n g => x => [f(x), g(x)];\n\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p =>\n // The value resulting from successive applications\n // of f to f(x), starting with a seed value x,\n // and terminating when the result returns true\n // for the predicate p.\n f => {\n const go = x =>\n p(x) ? x : go(f(x));\n\n return go;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Gaussian elimination", "language": "JavaScript", "task": "Solve '''Ax=b''' using Gaussian elimination then backwards substitution. \n\n'''A''' being an '''n''' by '''n''' matrix. \n\nAlso, '''x''' and '''b''' are '''n''' by '''1''' vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* the Wikipedia entry: Gaussian elimination\n\n", "solution": "// Lower Upper Solver\nfunction lusolve(A, b, update) {\n\tvar lu = ludcmp(A, update)\n\tif (lu === undefined) return // Singular Matrix!\n\treturn lubksb(lu, b, update)\n}\n\n// Lower Upper Decomposition\nfunction ludcmp(A, update) {\n\t// A is a matrix that we want to decompose into Lower and Upper matrices.\n\tvar d = true\n\tvar n = A.length\n\tvar idx = new Array(n) // Output vector with row permutations from partial pivoting\n\tvar vv = new Array(n) // Scaling information\n\n\tfor (var i=0; i max) max = temp\n\t\t}\n\t\tif (max == 0) return // Singular Matrix!\n\t\tvv[i] = 1 / max // Scaling\n\t}\n\t\n\tif (!update) { // make a copy of A \n\t\tvar Acpy = new Array(n)\n\t\tfor (var i=0; i= max) {\n\t\t\t\tmax = temp\n\t\t\t\tjmax = j\n\t\t\t}\n\t\t}\n\t\tif (i <= jmax) {\n\t\t\tfor (var j=0; j -1)\n\t\t\tfor (var j=ii; j=0; i--) {\n\t\tvar sum = b[i]\n\t\tfor (var j=i+1; j 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [this[i], this[j]] = [this[j], this[i]];\n }\n}\n\nfunction randomFEN() {\n\n let board = [];\n for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' '));\n\n function getRandPos() {\n return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)];\n }\n\n function isOccupied(pos) {\n return board[pos[0]][pos[1]] != '.';\n }\n\n function isAdjacent(pos1, pos2) {\n if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1)\n if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1)\n return true;\n return false;\n }\n\n // place kings\n let wk, bk;\n do { wk = getRandPos(); bk = getRandPos(); }\n while (isAdjacent(wk, bk));\n board[wk[0]][wk[1]] = 'K';\n board[bk[0]][bk[1]] = 'k';\n\n // get peaces\n let peaces = [];\n let names = 'PRNBQ';\n function pick() {\n for (x = 1; x < Math.floor(Math.random() * 32); x++)\n peaces.push(names[Math.floor(Math.random() * names.length)]);\n }\n pick();\n names = names.toLowerCase();\n pick();\n peaces.shuffle();\n\n // place peaces\n while (peaces.length > 0) {\n let p = peaces.shift(), pos;\n // paws: cannot be placed in bottom or top row\n if (p == 'p' || p == 'P')\n do { pos = getRandPos() }\n while (isOccupied(pos) || pos[0] == 0 || pos[0] == 7);\n // everything else\n else do { pos = getRandPos(); } while (isOccupied(pos));\n board[pos[0]][pos[1]] = p;\n }\n\n // write FEN\n let fen = [];\n for (x = 0; x < board.length; x++) {\n let str ='', buf = 0;\n for (let y = 0; y < board[x].length; y++)\n if (board[x][y] == '.') buf++;\n else {\n if (buf > 0) { str += buf; buf = 0; }\n str += board[x][y];\n }\n if (buf > 0) str += buf;\n fen.push(str);\n }\n fen = fen.join('/') + ' w - - 0 1';\n console.table(board); // for demonstrating purpose\n return fen;\n}\n\n// example\nconsole.log(randomFEN());\n"} {"title": "Generator/Exponential", "language": "JavaScript from Python", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO()\n const main = () => {\n\n // powers :: Gen [Int]\n const powers = n =>\n fmapGen(\n x => Math.pow(x, n),\n enumFrom(0)\n );\n\n // xs :: [Int]\n const xs = take(10, drop(20,\n differenceGen(\n powers(2),\n powers(3)\n )\n ));\n\n console.log(xs);\n // -> [529,576,625,676,784,841,900,961,1024,1089]\n };\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // differenceGen :: Gen [a] -> Gen [a] -> Gen [a]\n function* differenceGen(ga, gb) {\n // All values of generator stream a except any\n // already seen in generator stream b.\n const\n stream = zipGen(ga, gb),\n sb = new Set([]);\n let xy = take(1, stream);\n while (0 < xy.length) {\n const [x, y] = Array.from(xy[0]);\n sb.add(y);\n if (!sb.has(x)) yield x;\n xy = take(1, stream);\n }\n };\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) =>\n Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n, xs), xs);\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n let v = take(1, gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1, gen)\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]\n const zipGen = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just\n yield(Tuple(fst(ta), fst(tb)));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n }\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Gotchas", "language": "Javascript", "task": "Definition\nIn programming, a '''gotcha''' is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome.\n\n;Task\nGive an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools.\n\n", "solution": "===Equality Comparisons===\nThe normal equality operator (==) is very infamous for its strange results when comparing two variables of different types. Javascript has a complicated set of type coercion rules, which was intended to simplify comparisons between integers and floating point, integers and their string representations (e.g. 2 == '2'), etc. However, this is often frustrating for the programmer when they want to know if two variables are equal and also have the same data type. The strict equality (===) operator will always return false if the variables are of two different types. Many new programmers are taught to always use === to avoid subtle bugs in their programs.\n\n"} {"title": "Gray code", "language": "Javascript", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "import printf from 'printf' // Module must be installed with npm first\nimport * as gray from './gray-code.js'\n\nconsole.log(\n 'Number\\t' +\n 'Binary\\t' +\n 'Gray Code\\t' +\n 'Decoded Gray Code'\n)\n\nfor (let number = 0; number < 32; number++) {\n const grayCode = gray.encode(number)\n const decodedGrayCode = gray.decode(grayCode)\n\n console.log(printf(\n '%2d\\t%05d\\t%05d\\t\\t%2d',\n number,\n number.toString(2),\n grayCode.toString(2),\n decodedGrayCode\n ))\n}"} {"title": "Greatest subsequential sum", "language": "JavaScript", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "function MaximumSubsequence(population) {\n var maxValue = 0;\n var subsequence = [];\n\n for (var i = 0, len = population.length; i < len; i++) {\n for (var j = i; j <= len; j++) {\n var subsequence = population.slice(i, j);\n var value = sumValues(subsequence);\n if (value > maxValue) {\n maxValue = value;\n greatest = subsequence;\n };\n }\n }\n\n return greatest;\n}\n\nfunction sumValues(arr) {\n var result = 0;\n for (var i = 0, len = arr.length; i < len; i++) {\n result += arr[i];\n }\n return result;\n}"} {"title": "Greatest subsequential sum", "language": "JavaScript from Haskell", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "(() => {\n\n // maxSubseq :: [Int] -> (Int, [Int])\n const maxSubseq = xs =>\n snd(xs.reduce((tpl, x) => {\n const [m1, m2] = Array.from(fst(tpl)),\n high = max(\n Tuple(0, []),\n Tuple(m1 + x, m2.concat(x))\n );\n return Tuple(high, max(snd(tpl), high));\n }, Tuple(Tuple(0, []), Tuple(0, []))));\n\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () => {\n const mx = maxSubseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]);\n showLog(snd(mx), fst(mx))\n }\n // [3,5,6,-2,-1,4] -> 15\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // gt :: Ord a => a -> a -> Bool\n const gt = (x, y) =>\n 'Tuple' === x.type ? (\n x[0] > y[0]\n ) : (x > y);\n\n // max :: Ord a => a -> a -> a\n const max = (a, b) => gt(b, a) ? b : a;\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // MAIN ---\n return main();\n})();"} {"title": "Greyscale bars/Display", "language": "JavaScript", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "\n\n\n"} {"title": "Hailstone sequence", "language": "JavaScript", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "function hailstone (n) {\n var seq = [n];\n while (n > 1) {\n n = n % 2 ? 3 * n + 1 : n / 2;\n seq.push(n);\n }\n return seq;\n}\n\n// task 2: verify the sequence for n = 27\nvar h = hailstone(27), hLen = h.length;\nprint(\"sequence 27 is (\" + h.slice(0, 4).join(\", \") + \" ... \"\n + h.slice(hLen - 4, hLen).join(\", \") + \"). length: \" + hLen);\n\n// task 3: find the longest sequence for n < 100000\nfor (var n, max = 0, i = 100000; --i;) {\n var seq = hailstone(i), sLen = seq.length;\n if (sLen > max) {\n n = i;\n max = sLen;\n }\n}\nprint(\"longest sequence: \" + max + \" numbers for starting point \" + n);"} {"title": "Harshad or Niven series", "language": "JavaScript", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "function isHarshad(n) {\n var s = 0;\n var n_str = new String(n);\n for (var i = 0; i < n_str.length; ++i) {\n s += parseInt(n_str.charAt(i));\n }\n return n % s === 0;\n}\n\nvar count = 0;\nvar harshads = [];\n\nfor (var n = 1; count < 20; ++n) {\n if (isHarshad(n)) {\n count++;\n harshads.push(n);\n }\n}\n\nconsole.log(harshads.join(\" \"));\n\nvar h = 1000;\nwhile (!isHarshad(++h));\nconsole.log(h);\n"} {"title": "Hash join", "language": "JavaScript", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "(() => {\n 'use strict';\n\n // hashJoin :: [Dict] -> [Dict] -> String -> [Dict]\n let hashJoin = (tblA, tblB, strJoin) => {\n\n let [jA, jB] = strJoin.split('='),\n M = tblB.reduce((a, x) => {\n let id = x[jB];\n return (\n a[id] ? a[id].push(x) : a[id] = [x],\n a\n );\n }, {});\n\n return tblA.reduce((a, x) => {\n let match = M[x[jA]];\n return match ? (\n a.concat(match.map(row => dictConcat(x, row)))\n ) : a;\n }, []);\n },\n\n // dictConcat :: Dict -> Dict -> Dict\n dictConcat = (dctA, dctB) => {\n let ok = Object.keys;\n return ok(dctB).reduce(\n (a, k) => (a['B_' + k] = dctB[k]) && a,\n ok(dctA).reduce(\n (a, k) => (a['A_' + k] = dctA[k]) && a, {}\n )\n );\n };\n\n\n // TEST\n let lstA = [\n { age: 27, name: 'Jonah' },\n { age: 18, name: 'Alan' },\n { age: 28, name: 'Glory' },\n { age: 18, name: 'Popeye' },\n { age: 28, name: 'Alan' }\n ],\n lstB = [\n { character: 'Jonah', nemesis: 'Whales' },\n { character: 'Jonah', nemesis: 'Spiders' },\n { character: 'Alan', nemesis: 'Ghosts' },\n { character:'Alan', nemesis: 'Zombies' },\n { character: 'Glory', nemesis: 'Buffy' },\n { character: 'Bob', nemesis: 'foo' }\n ];\n\n return hashJoin(lstA, lstB, 'name=character');\n \n})();\n"} {"title": "Haversine formula", "language": "JavaScript from Java", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "function haversine() {\n var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });\n var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];\n var R = 6372.8; // km\n var dLat = lat2 - lat1;\n var dLon = lon2 - lon1;\n var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2);\n var c = 2 * Math.asin(Math.sqrt(a));\n return R * c;\n}\nconsole.log(haversine(36.12, -86.67, 33.94, -118.40));"} {"title": "Here document", "language": "JavaScript", "task": "A ''here document'' (or \"heredoc\") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a ''here document'' is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of ''here documents'' within the language.\n\n;Related task:\n* [[Documentation]]\n\n", "solution": "const myVar = 123;\nconst tempLit = `Here is some\nmulti-line string. And here is\nthe value of \"myVar\": ${myVar}\nThat's all.`;\nconsole.log(tempLit)\n"} {"title": "Heronian triangles", "language": "JavaScript", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "window.onload = function(){\t\n var list = [];\n var j = 0;\t\n for(var c = 1; c <= 200; c++)\n for(var b = 1; b <= c; b++)\n for(var a = 1; a <= b; a++)\n\t if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c)))\t\t\t\t\t\t\t\n\t\t list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c));\n sort(list);\t\n document.write(\"

Primitive Heronian triangles with sides up to 200: \" + list.length + \"

First ten when ordered by increasing area, then perimeter:

\");\n for(var i = 0; i < 10; i++)\n\tdocument.write(\"\");\n document.write(\"
SidesPerimeterArea
\" + list[i][0] + \" x \" + list[i][1] + \" x \" + list[i][2] + \"\" + list[i][3] + \"\" + list[i][4] + \"

Area = 210

\");\n for(var i = 0; i < list.length; i++)\n\tif(list[i][4] == 210)\n\t document.write(\"\"); \t\t\n function heronArea(a, b, c){\n\tvar s = (a + b + c)/ 2;\n\treturn Math.sqrt(s *(s -a)*(s - b)*(s - c));\t\t\n }\t\n function isHeron(h){\n return h % 1 == 0 && h > 0;\n }\t\n function gcd(a, b){\n\tvar leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;\t\t\n\twhile(leftover != 0){\n\t leftover = dividend % divisor;\n\t if(leftover > 0){\n\t\tdividend = divisor;\n\t\tdivisor = leftover;\n\t }\n\t}\t\t\n\treturn divisor;\n }\t\n function sort(list){\n\tvar swapped = true;\n\tvar temp = [];\n\twhile(swapped){\n\t swapped = false;\n\t for(var i = 1; i < list.length; i++){\n\t\tif(list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){\n\t\t temp = list[i];\n\t\t list[i] = list[i - 1];\n\t\t list[i - 1] = temp;\n\t\t swapped = true;\n\t\t}\t\t\t\t\n\t }\t\t\t\n\t}\n }\n}\n"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "JavaScript", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "var hofst_10k = function(n) {\n\tvar memo = [1, 1];\n\n\tvar a = function(n) {\n\t\tvar result = memo[n-1];\n\t\tif (typeof result !== 'number') {\n\t\t\tresult = a(a(n-1))+a(n-a(n-1));\t\n\t\t\tmemo[n-1] = result;\n\t\t}\t\n\t\treturn result;\n\t}\n\treturn a;\n}();\n\nvar maxima_between_twos = function(exp) {\n\tvar current_max = 0;\n\tfor(var i = Math.pow(2,exp)+1; i < Math.pow(2,exp+1); i += 1) {\n\t\tcurrent_max = Math.max(current_max, hofst_10k(i)/i);\n\t}\n\treturn current_max;\n}\n\nfor(var i = 1; i <= 20; i += 1) {\n\tconsole.log(\"Maxima between 2^\"+i+\"-2^\"+(i+1)+\" is: \"+maxima_between_twos(i)+\"\\n\");\n}"} {"title": "Hofstadter Figure-Figure sequences", "language": "JavaScript from Ruby", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "var R = [null, 1];\nvar S = [null, 2];\n\nvar extend_sequences = function (n) {\n\tvar current = Math.max(R[R.length-1],S[S.length-1]);\n\tvar i;\n\twhile (R.length <= n || S.length <= n) {\n\t\ti = Math.min(R.length, S.length) - 1;\n\t\tcurrent += 1;\n\t\tif (current === R[i] + S[i]) {\n\t\t\tR.push(current);\n\t\t} else {\n\t\t\tS.push(current);\n\t\t}\n\t}\n}\n\nvar ffr = function(n) {\n\textend_sequences(n);\n\treturn R[n];\n};\n\nvar ffs = function(n) {\n\textend_sequences(n);\n\treturn S[n];\n};\n\nfor (var i = 1; i <=10; i += 1) {\n console.log('R('+ i +') = ' + ffr(i));\n}\n\nvar int_array = [];\n\nfor (var i = 1; i <= 40; i += 1) {\n\tint_array.push(ffr(i));\n}\nfor (var i = 1; i <= 960; i += 1) {\n\tint_array.push(ffs(i));\n}\n\nint_array.sort(function(a,b){return a-b;});\n\nfor (var i = 1; i <= 1000; i += 1) {\n\tif (int_array[i-1] !== i) { \n\t\tthrow \"Something's wrong!\" \n\t} else { console.log(\"1000 integer check ok.\"); }\n}"} {"title": "Hofstadter Q sequence", "language": "JavaScript", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "var hofstadterQ = function() {\n var memo = [1,1,1];\n var Q = function (n) {\n var result = memo[n];\n if (typeof result !== 'number') {\n result = Q(n - Q(n-1)) + Q(n - Q(n-2));\n memo[n] = result;\n }\n return result;\n };\n return Q;\n}();\n\nfor (var i = 1; i <=10; i += 1) {\n console.log('Q('+ i +') = ' + hofstadterQ(i));\n}\n\nconsole.log('Q(1000) = ' + hofstadterQ(1000));\n"} {"title": "Horner's rule for polynomial evaluation", "language": "JavaScript from Haskell", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.\n\nCf. [[Formal power series]]\n\n", "solution": "function horner(coeffs, x) {\n return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0);\n}\nconsole.log(horner([-19,7,-4,6],3)); // ==> 128\n"} {"title": "Identity matrix", "language": "JavaScript", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "(() => {\n\n // identityMatrix :: Int -> [[Int]]\n const identityMatrix = n =>\n Array.from({\n length: n\n }, (_, i) => Array.from({\n length: n\n }, (_, j) => i !== j ? 0 : 1));\n\n\n // ----------------------- TEST ------------------------\n return identityMatrix(5)\n .map(JSON.stringify)\n .join('\\n');\n})();"} {"title": "Include a file", "language": "JavaScript", "task": "Demonstrate the language's ability to include source code from other files.\n\n\n;See Also\n\n* [[Compiler/Simple file inclusion pre processor]]\n\n\n", "solution": "var s = document.createElement('script');\ns.type = 'application/javascript';\n\n// path to the desired file\ns.src = 'http://code.jquery.com/jquery-1.6.2.js';\ndocument.body.appendChild(s);"} {"title": "Intersecting number wheels", "language": "JavaScript", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "Map-accumulation of a recursive digit-search,\nover an array of given length and arbitrary contents.\n"} {"title": "Intersecting number wheels", "language": "JavaScript from Python", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n\n // clockWorkTick :: Dict -> (Dict, Char)\n const clockWorkTick = wheelMap => {\n // The new configuration of the wheels, tupled with\n // a digit found by recursive descent from a single\n // click of the first wheel.\n const click = wheels => wheelName => {\n const\n wheel = wheels[wheelName] || ['?'],\n v = wheel[0];\n return bool(click)(Tuple)(isDigit(v) || '?' === v)(\n insertDict(wheelName)(\n leftRotate(wheel)\n )(wheels)\n )(v);\n };\n return click(wheelMap)('A');\n };\n\n // leftRotate ::[a] -> [a]\n const leftRotate = xs =>\n // The head of the list appended\n // to the tail of of the list.\n 0 < xs.length ? (\n xs.slice(1).concat(xs[0])\n ) : [];\n\n\n // TEST -------------------------------------------\n // State of each wheel-set after 20 clicks,\n // paired with the resulting series of characters.\n\n const tuple = uncurry(Tuple);\n const wheelLists = [\n [tuple('A', '123')],\n [tuple('A', '1B2'), tuple('B', '34')],\n [tuple('A', '1DD'), tuple('D', '678')],\n [tuple('A', '1BC'), tuple('B', '34'), tuple('C', '5B')]\n ];\n\n console.log([\n 'Series and state of each wheel-set after 20 clicks:\\n',\n unlines(\n map(tuples => showWheels(\n mapAccumL(\n compose(constant, clockWorkTick)\n )(dictFromList(tuples))(replicate(20)(''))\n ))(wheelLists)\n ),\n '\\nInitial state of each wheel-set:\\n',\n map(map(compose(\n JSON.stringify,\n dictFromList,\n x => [Array.from(x)]\n )))(wheelLists).join('\\n')\n ].join('\\n'));\n };\n\n // DISPLAY FORMATTING ---------------------------------\n\n // showWheels :: (Dict, [Char]) -> String\n const showWheels = tpl =>\n JSON.stringify(\n Array.from(secondArrow(concat)(tpl))\n );\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // bool :: a -> a -> Bool -> a\n const bool = f => t => p =>\n p ? t : f;\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // constant :: a -> b -> a\n const constant = k => _ => k;\n\n // dictFromList :: [(k, v)] -> Dict\n const dictFromList = kvs =>\n Object.fromEntries(kvs);\n\n // secondArrow :: (a -> b) -> ((c, a) -> (c, b))\n const secondArrow = f => xy =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n Tuple(xy[0])(\n f(xy[1])\n );\n\n // insertDict :: String -> a -> Dict -> Dict\n const insertDict = k => v => dct =>\n Object.assign({}, dct, {\n [k]: v\n });\n\n // isDigit :: Char -> Bool\n const isDigit = c => {\n const n = c.codePointAt(0);\n return 48 <= n && 57 >= n;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // Map-accumulation is a combination of map and a catamorphism;\n // it applies a function to each element of a list, passing an\n // accumulating parameter from left to right, and returning a final\n // value of this accumulator together with the new list.\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = f => acc => xs =>\n xs.reduce((a, x) => {\n const pair = f(a[0])(x);\n return Tuple(pair[0])(a[1].concat(pair[1]));\n }, Tuple(acc)([]));\n\n // replicate :: Int -> a -> [a]\n const replicate = n => x =>\n Array.from({\n length: n\n }, () => x);\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n (x, y) => f(x)(y);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} {"title": "JSON", "language": "JavaScript", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "var data = JSON.parse('{ \"foo\": 1, \"bar\": [10, \"apples\"] }');\n\nvar sample = { \"blue\": [1,2], \"ocean\": \"water\" };\nvar json_string = JSON.stringify(sample);"} {"title": "Jewels and stones", "language": "Javascript", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "(() => {\n\n // jewelCount :: String -> String -> Int\n const jewelCount = (j, s) => {\n const js = j.split('');\n return s.split('')\n .reduce((a, c) => js.includes(c) ? a + 1 : a, 0)\n };\n\n // TEST -----------------------------------------------\n return [\n ['aA', 'aAAbbbb'],\n ['z', 'ZZ']\n ]\n .map(x => jewelCount(...x))\n})();"} {"title": "Julia set", "language": "JavaScript", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "var maxIterations = 450, minX = -.5, maxX = .5, \n minY = -.5, maxY = .5, wid, hei, ctx,\n jsX = 0.285, jsY = 0.01;\n\nfunction remap( x, t1, t2, s1, s2 ) {\n var f = ( x - t1 ) / ( t2 - t1 ),\n g = f * ( s2 - s1 ) + s1;\n return g;\n}\nfunction getColor( c ) {\n var r, g, b, p = c / 32,\n l = ~~( p * 6 ), o = p * 6 - l, \n q = 1 - o;\n\n switch( l % 6 ) {\n case 0: r = 1; g = o; b = 0; break;\n case 1: r = q; g = 1; b = 0; break;\n case 2: r = 0; g = 1; b = o; break;\n case 3: r = 0; g = q; b = 1; break;\n case 4: r = o; g = 0; b = 1; break;\n case 5: r = 1; g = 0; b = q; break;\n }\n var c = \"#\" + ( \"00\" + ( ~~( r * 255 ) ).toString( 16 ) ).slice( -2 ) + \n ( \"00\" + ( ~~( g * 255 ) ).toString( 16 ) ).slice( -2 ) + \n ( \"00\" + ( ~~( b * 255 ) ).toString( 16 ) ).slice( -2 );\n return (c);\n}\nfunction drawFractal() {\n var a, as, za, b, bs, zb, cnt, clr\n for( var j = 0; j < hei; j++ ) {\n for( var i = 0; i < wid; i++ ) {\n a = remap( i, 0, wid, minX, maxX )\n b = remap( j, 0, hei, minY, maxY )\n cnt = 0;\n while( ++cnt < maxIterations ) {\n za = a * a; zb = b * b;\n if( za + zb > 4 ) break;\n as = za - zb; bs = 2 * a * b;\n a = as + jsX; b = bs + jsY;\n }\n if( cnt < maxIterations ) {\n ctx.fillStyle = getColor( cnt );\n }\n ctx.fillRect( i, j, 1, 1 );\n }\n }\n}\nfunction init() {\n var canvas = document.createElement( \"canvas\" );\n wid = hei = 800;\n canvas.width = wid; canvas.height = hei;\n ctx = canvas.getContext( \"2d\" );\n ctx.fillStyle = \"black\"; ctx.fillRect( 0, 0, wid, hei );\n document.body.appendChild( canvas );\n drawFractal();\n}\n"} {"title": "Kaprekar numbers", "language": "JavaScript", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "function kaprekar( s, e, bs, pbs ) {\n\tbs = bs || 10; pbs = pbs || 10\n\tconst toString = n => n.toString(pbs).toUpperCase()\n\tdocument.write('start:',toString(s), ' end:',toString(e), ' base:',bs, ' printBase:',pbs, '
' )\n\tfor (var k=0, n=s; n<=e; n+=1) if (isKaprekar(n, bs)) k+=1, document.write(toString(n), ' ') \n\tdocument.write('
found ', k, ' numbers

')\n}\n\nkaprekar( 1, 99 )\nkaprekar( 1, 255, 16)\nkaprekar( 1, 255, 16, 16)\nkaprekar( 1, 288, 17, 17)"} {"title": "Kernighans large earthquake problem", "language": "JavaScript", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "const fs = require(\"fs\");\nconst readline = require(\"readline\");\n\nconst args = process.argv.slice(2);\nif (!args.length) {\n console.error(\"must supply file name\");\n process.exit(1);\n}\n\nconst fname = args[0];\n\nconst readInterface = readline.createInterface({\n input: fs.createReadStream(fname),\n console: false,\n});\n\nreadInterface.on(\"line\", (line) => {\n const fields = line.split(/\\s+/);\n if (+fields[fields.length - 1] > 6) {\n console.log(line);\n }\n});\n"} {"title": "Keyboard input/Obtain a Y or N response", "language": "JavaScript", "task": "Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. \n\nThe response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.\n\n", "solution": "const readline = require('readline');\nreadline.emitKeypressEvents(process.stdin);\nprocess.stdin.setRawMode(true);\n\nvar wait_key = async function() {\n return await new Promise(function(resolve,reject) {\n var key_listen = function(str,key) {\n process.stdin.removeListener('keypress', key_listen);\n resolve(str);\n }\n process.stdin.on('keypress', key_listen);\n });\n}\n\nvar done = function() {\n process.exit();\n}\n\nvar go = async function() {\n do {\n console.log('Press any key...');\n var key = await wait_key();\n console.log(\"Key pressed is\",key);\n await new Promise(function(resolve) { setTimeout(resolve,1000); });\n } while(key != 'y');\n done();\n}\n\ngo();\n"} {"title": "Knight's tour", "language": "Javascript", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "class KnightTour {\n constructor() {\n this.width = 856;\n this.height = 856;\n this.cellCount = 8;\n this.size = 0;\n this.knightPiece = \"\\u2658\";\n this.knightPos = {\n x: 0,\n y: 0\n };\n this.ctx = null;\n this.step = this.width / this.cellCount;\n this.lastTime = 0;\n this.wait;\n this.delay;\n this.success;\n this.jumps;\n this.directions = [];\n this.visited = [];\n this.path = [];\n document.getElementById(\"start\").addEventListener(\"click\", () => {\n this.startHtml();\n });\n this.init();\n this.drawBoard();\n }\n\n drawBoard() {\n let a = false, xx, yy;\n for (let y = 0; y < this.cellCount; y++) {\n for (let x = 0; x < this.cellCount; x++) {\n if (a) {\n this.ctx.fillStyle = \"#607db8\";\n } else {\n this.ctx.fillStyle = \"#aecaf0\";\n }\n a = !a;\n xx = x * this.step;\n yy = y * this.step;\n this.ctx.fillRect(xx, yy, xx + this.step, yy + this.step);\n }\n if (!(this.cellCount & 1)) a = !a;\n }\n if (this.path.length) {\n const s = this.step >> 1;\n this.ctx.lineWidth = 3;\n this.ctx.fillStyle = \"black\";\n this.ctx.beginPath();\n this.ctx.moveTo(this.step * this.knightPos.x + s, this.step * this.knightPos.y + s);\n let a, b, v = this.path.length - 1;\n for (; v > -1; v--) {\n a = this.path[v].pos.x * this.step + s;\n b = this.path[v].pos.y * this.step + s;\n this.ctx.lineTo(a, b);\n this.ctx.fillRect(a - 5, b - 5, 10, 10);\n }\n this.ctx.stroke();\n }\n }\n\n createMoves(pos) {\n const possibles = [];\n let x = 0,\n y = 0,\n m = 0,\n l = this.directions.length;\n for (; m < l; m++) {\n x = pos.x + this.directions[m].x;\n y = pos.y + this.directions[m].y;\n if (x > -1 && x < this.cellCount && y > -1 && y < this.cellCount && !this.visited[x + y * this.cellCount]) {\n possibles.push({\n x,\n y\n })\n }\n }\n return possibles;\n }\n\n warnsdorff(pos) {\n const possibles = this.createMoves(pos);\n if (possibles.length < 1) return [];\n const moves = [];\n for (let p = 0, l = possibles.length; p < l; p++) {\n let ps = this.createMoves(possibles[p]);\n moves.push({\n len: ps.length,\n pos: possibles[p]\n });\n }\n moves.sort((a, b) => {\n return b.len - a.len;\n });\n return moves;\n }\n\n startHtml() {\n this.cellCount = parseInt(document.getElementById(\"cellCount\").value);\n this.size = Math.floor(this.width / this.cellCount)\n this.wait = this.delay = parseInt(document.getElementById(\"delay\").value);\n this.step = this.width / this.cellCount;\n this.ctx.font = this.size + \"px Arial\";\n document.getElementById(\"log\").innerText = \"\";\n document.getElementById(\"path\").innerText = \"\";\n this.path = [];\n this.jumps = 1;\n this.success = true;\n this.visited = [];\n const cnt = this.cellCount * this.cellCount;\n for (let a = 0; a < cnt; a++) {\n this.visited.push(false);\n }\n const kx = parseInt(document.getElementById(\"knightx\").value),\n ky = parseInt(document.getElementById(\"knighty\").value);\n this.knightPos = {\n x: (kx > this.cellCount || kx < 0) ? Math.floor(Math.random() * this.cellCount) : kx,\n y: (ky > this.cellCount || ky < 0) ? Math.floor(Math.random() * this.cellCount) : ky\n };\n this.mainLoop = (time = 0) => {\n const dif = time - this.lastTime;\n this.lastTime = time;\n this.wait -= dif;\n if (this.wait > 0) {\n requestAnimationFrame(this.mainLoop);\n return;\n }\n this.wait = this.delay;\n let moves;\n if (this.success) {\n moves = this.warnsdorff(this.knightPos);\n } else {\n if (this.path.length > 0) {\n const path = this.path[this.path.length - 1];\n moves = path.m;\n if (moves.length < 1) this.path.pop();\n this.knightPos = path.pos\n this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = false;\n this.jumps--;\n this.wait = this.delay;\n } else {\n document.getElementById(\"log\").innerText = \"Can't find a solution!\";\n return;\n }\n }\n this.drawBoard();\n const ft = this.step - (this.step >> 3);\n this.ctx.fillStyle = \"#000\";\n this.ctx.fillText(this.knightPiece, this.knightPos.x * this.step, this.knightPos.y * this.step + ft);\n if (moves.length < 1) {\n if (this.jumps === this.cellCount * this.cellCount) {\n document.getElementById(\"log\").innerText = \"Tour finished!\";\n let str = \"\";\n for (let z of this.path) {\n str += `${1 + z.pos.x + z.pos.y * this.cellCount}, `;\n }\n str += `${1 + this.knightPos.x + this.knightPos.y * this.cellCount}`;\n document.getElementById(\"path\").innerText = str;\n return;\n } else {\n this.success = false;\n }\n } else {\n this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = true;\n const move = moves.pop();\n this.path.push({\n pos: this.knightPos,\n m: moves\n });\n this.knightPos = move.pos\n this.success = true;\n this.jumps++;\n }\n requestAnimationFrame(this.mainLoop);\n };\n this.mainLoop();\n }\n\n init() {\n const canvas = document.createElement(\"canvas\");\n canvas.id = \"cv\";\n canvas.width = this.width;\n canvas.height = this.height;\n this.ctx = canvas.getContext(\"2d\");\n document.getElementById(\"out\").appendChild(canvas);\n this.directions = [{\n x: -1,\n y: -2\n }, {\n x: -2,\n y: -1\n }, {\n x: 1,\n y: -2\n }, {\n x: 2,\n y: -1\n },\n {\n x: -1,\n y: 2\n }, {\n x: -2,\n y: 1\n }, {\n x: 1,\n y: 2\n }, {\n x: 2,\n y: 1\n }\n ];\n }\n}\nnew KnightTour();\n"} {"title": "Knight's tour", "language": "Javascript from Haskell", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "(() => {\n 'use strict';\n\n // knightsTour :: Int -> [(Int, Int)] -> [(Int, Int)]\n const knightsTour = rowLength => moves => {\n const go = path => {\n const\n findMoves = xy => difference(knightMoves(xy), path),\n warnsdorff = minimumBy(\n comparing(compose(length, findMoves))\n ),\n options = findMoves(path[0]);\n return 0 < options.length ? (\n go([warnsdorff(options)].concat(path))\n ) : reverse(path);\n };\n\n // board :: [[(Int, Int)]]\n const board = concatMap(\n col => concatMap(\n row => [\n [col, row]\n ],\n enumFromTo(1, rowLength)),\n enumFromTo(1, rowLength)\n );\n\n // knightMoves :: (Int, Int) -> [(Int, Int)]\n const knightMoves = ([x, y]) =>\n concatMap(\n ([dx, dy]) => {\n const ab = [x + dx, y + dy];\n return elem(ab, board) ? (\n [ab]\n ) : [];\n }, [\n [-2, -1],\n [-2, 1],\n [-1, -2],\n [-1, 2],\n [1, -2],\n [1, 2],\n [2, -1],\n [2, 1]\n ]\n );\n return go(moves);\n };\n\n // TEST -----------------------------------------------\n // main :: IO()\n const main = () => {\n\n // boardSize :: Int\n const boardSize = 8;\n\n // tour :: [(Int, Int)]\n const tour = knightsTour(boardSize)(\n [fromAlgebraic('e5')]\n );\n\n // report :: String\n const report = '(Board size ' +\n boardSize + '*' + boardSize + ')\\n\\n' +\n 'Route: \\n\\n' +\n showRoute(boardSize)(tour) + '\\n\\n' +\n 'Coverage and order: \\n\\n' +\n showCoverage(boardSize)(tour) + '\\n\\n';\n return (\n console.log(report),\n report\n );\n }\n\n // DISPLAY --------------------------------------------\n\n // algebraic :: (Int, Int) -> String\n const algebraic = ([x, y]) =>\n chr(x + 96) + y.toString();\n\n // fromAlgebraic :: String -> (Int, Int)\n const fromAlgebraic = s =>\n 2 <= s.length ? (\n [ord(s[0]) - 96, parseInt(s.slice(1))]\n ) : undefined;\n\n // showCoverage :: Int -> [(Int, Int)] -> String\n const showCoverage = rowLength => xys => {\n const\n intMax = xys.length,\n w = 1 + intMax.toString().length\n return unlines(map(concat,\n chunksOf(\n rowLength,\n map(composeList([justifyRight(w, ' '), str, fst]),\n sortBy(\n mappendComparing([\n compose(fst, snd),\n compose(snd, snd)\n ]),\n zip(enumFromTo(1, intMax), xys)\n )\n )\n )\n ));\n };\n\n // showRoute :: Int -> [(Int, Int)] -> String\n const showRoute = rowLength => xys => {\n const w = 1 + rowLength.toString().length;\n return unlines(map(\n xs => xs.join(' -> '),\n chunksOf(\n rowLength,\n map(compose(justifyRight(w, ' '), algebraic), xys)\n )\n ));\n };\n\n\n // GENERIC FUNCTIONS ----------------------------------\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 // chr :: Int -> Char\n const chr = x => String.fromCodePoint(x);\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = (n, xs) =>\n enumFromThenTo(0, n, xs.length - 1)\n .reduce(\n (a, i) => a.concat([xs.slice(i, (n + i))]),\n []\n );\n\n // compare :: a -> a -> Ordering\n const compare = (a, b) =>\n a < b ? -1 : (a > b ? 1 : 0);\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // composeList :: [(a -> a)] -> (a -> a)\n const composeList = fs =>\n x => fs.reduceRight((a, f) => f(a), x, fs);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) =>\n xs.reduce((a, x) => a.concat(f(x)), []);\n\n\n // difference :: Eq a => [a] -> [a] -> [a]\n const difference = (xs, ys) => {\n const s = new Set(ys.map(str));\n return xs.filter(x => !s.has(str(x)));\n };\n\n // elem :: Eq a => a -> [a] -> Bool\n const elem = (x, xs) => xs.some(eq(x))\n\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a => b => {\n const t = typeof a;\n return t !== typeof b ? (\n false\n ) : 'object' !== t ? (\n 'function' !== t ? (\n a === b\n ) : a.toString() === b.toString()\n ) : (() => {\n const kvs = Object.entries(a);\n return kvs.length !== Object.keys(b).length ? (\n false\n ) : kvs.every(([k, v]) => eq(v)(b[k]));\n })();\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller) => s =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n\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 // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering)\n const mappendComparing = fs =>\n (x, y) => fs.reduce(\n (ordr, f) => (ordr || compare(f(x), f(y))),\n 0\n );\n\n // minimumBy :: (a -> a -> Ordering) -> [a] -> a\n const minimumBy = f => xs =>\n xs.reduce((a, x) => undefined === a ? x : (\n 0 > f(x, a) ? x : a\n ), undefined);\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // str :: a -> String\n const str = x => x.toString();\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.slice(0, n);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\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 const bs = take(lng, ys);\n return take(lng, xs).map((x, i) => Tuple(x, bs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Koch curve", "language": "JavaScript", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "Generates SVG. To view, save to a file with the extension '.svg', and open in a browser.\n\n"} {"title": "Koch curve", "language": "JavaScript from Haskell", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "(() => {\n 'use strict';\n\n // kochSnowflake :: Int -> (Float, Float) -> (Float, Float)\n // -> [(Float, Float)]\n const kochSnowflake = n => a => b => {\n // List of points on a Koch snowflake of order n, derived\n // from an equilateral triangle with base a b.\n const points = [a, equilateralApex(a)(b), b];\n return concat(\n zipWith(kochCurve(n))(points)(\n points.slice(1).concat([points[0]])\n )\n );\n };\n\n\n // koch :: Int -> (Float, Float) -> (Float, Float)\n // -> [(Float, Float)]\n const kochCurve = n => ab => xy => {\n // A Koch curve of order N, starting at the point\n // (a, b), and ending at the point (x, y).\n const go = n => ([ab, xy]) =>\n 0 !== n ? (() => {\n const [mp, mq] = midThirdOfLine(ab)(xy);\n const points = [\n ab,\n mp,\n equilateralApex(mp)(mq),\n mq,\n xy\n ];\n return zip(points)(points.slice(1))\n .flatMap(go(n - 1))\n })() : [xy];\n return [ab].concat(go(n)([ab, xy]));\n };\n\n\n // equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)\n const equilateralApex = p => q =>\n rotatedPoint(Math.PI / 3)(p)(q);\n\n\n // rotatedPoint :: Float -> (Float, Float) ->\n // (Float, Float) -> (Float, Float)\n const rotatedPoint = theta => ([ox, oy]) => ([a, b]) => {\n // The point ab rotated theta radians\n // around the origin xy.\n const [dx, dy] = rotatedVector(theta)(\n [a - ox, oy - b]\n );\n return [ox + dx, oy - dy];\n };\n\n\n // rotatedVector :: Float -> (Float, Float) -> (Float, Float)\n const rotatedVector = theta => ([x, y]) =>\n // The vector xy rotated by theta radians.\n [\n x * Math.cos(theta) - y * Math.sin(theta),\n x * Math.sin(theta) + y * Math.cos(theta)\n ];\n\n\n // midThirdOfLine :: (Float, Float) -> (Float, Float)\n // -> ((Float, Float), (Float, Float))\n const midThirdOfLine = ab => xy => {\n // Second of three equal segments of\n // the line between ab and xy.\n const\n vector = zipWith(dx => x => (dx - x) / 3)(xy)(ab),\n f = zipWith(add)(vector),\n p = f(ab);\n return [p, f(p)];\n };\n\n\n // TEST -----------------------------------------------\n // main :: IO ()\n const main = () =>\n // SVG showing a Koch snowflake of order 4.\n console.log(\n svgFromPoints(1024)(\n kochSnowflake(5)(\n [200, 600]\n )([800, 600])\n )\n );\n\n // SVG ----------------------------------------------\n\n // svgFromPoints :: Int -> [(Int, Int)] -> String\n const svgFromPoints = w => ps => [\n '`,\n ` p.map(n => n.toFixed(2))).join(' ')\n }\" `,\n 'stroke-width=\"2\" stroke=\"red\" fill=\"transparent\"/>',\n ''\n ].join('\\n');\n\n\n // GENERIC --------------------------------------------\n\n // add :: Num -> Num -> Num\n const add = a => b => a + b;\n\n // concat :: [[a]] -> [a]\n const concat = xs => [].concat.apply([], xs);\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => [x, ys[i]]);\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // MAIN ---\n return main();\n})();"} {"title": "Largest int from concatenated ints", "language": "JavaScript", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "(function () {\n 'use strict';\n\n // maxCombine :: [Int] -> Int\n function maxCombine(xs) {\n return parseInt(\n xs.sort(\n function (x, y) {\n var a = x.toString(),\n b = y.toString(),\n ab = parseInt(a + b),\n ba = parseInt(b + a);\n\n return ab > ba ? -1 : (ab < ba ? 1 : 0);\n }\n )\n .join(''), 10\n );\n }\n\n return [\n [1, 34, 3, 98, 9, 76, 45, 4],\n [54, 546, 548, 60]\n ].map(maxCombine);\n\n })();\n"} {"title": "Law of cosines - triples", "language": "JavaScript", "task": "The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n\n const\n f90 = dct => x2 => dct[x2],\n f60 = dct => (x2, ab) => dct[x2 - ab],\n f120 = dct => (x2, ab) => dct[x2 + ab],\n f60unequal = dct => (x2, ab, a, b) =>\n (a !== b) ? (\n dct[x2 - ab]\n ) : undefined;\n\n\n // triangles :: Dict -> (Int -> Int -> Int -> Int -> Maybe Int)\n // -> [String]\n const triangles = (f, n) => {\n const\n xs = enumFromTo(1, n),\n fr = f(xs.reduce((a, x) => (a[x * x] = x, a), {})),\n gc = xs.reduce((a, _) => a, {}),\n setSoln = new Set();\n return (\n xs.forEach(\n a => {\n const a2 = a * a;\n enumFromTo(1, 1 + a).forEach(\n b => {\n const\n suma2b2 = a2 + b * b,\n c = fr(suma2b2, a * b, a, b);\n if (undefined !== c) {\n setSoln.add([a, b, c].sort())\n };\n }\n );\n }\n ),\n Array.from(setSoln.keys())\n );\n };\n\n const\n result = 'Triangles of maximum side 13:\\n\\n' +\n unlines(\n zipWith(\n (s, f) => {\n const ks = triangles(f, 13);\n return ks.length.toString() + ' solutions for ' + s +\n ' degrees:\\n' + unlines(ks) + '\\n';\n },\n ['120', '90', '60'],\n [f120, f90, f60]\n )\n ) + '\\nUneven triangles of maximum side 10000. Total:\\n' +\n triangles(f60unequal, 10000).length\n\n return (\n //console.log(result),\n result\n );\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) =>\n xs.reduce((a, x) => a.concat(f(x)), []);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one non-finite like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Least common multiple", "language": "JavaScript", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "function LCM(A) // A is an integer array (e.g. [-50,25,-45,-18,90,447])\n{ \n var n = A.length, a = Math.abs(A[0]);\n for (var i = 1; i < n; i++)\n { var b = Math.abs(A[i]), c = a;\n while (a && b){ a > b ? a %= b : b %= a; } \n a = Math.abs(c*A[i])/(a+b);\n }\n return a;\n}\n\n/* For example:\n LCM([-50,25,-45,-18,90,447]) -> 67050\n*/"} {"title": "Least common multiple", "language": "JavaScript from Haskell", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "(() => {\n 'use strict';\n\n // gcd :: Integral a => a -> a -> a\n let gcd = (x, y) => {\n let _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n }\n\n // lcm :: Integral a => a -> a -> a\n let lcm = (x, y) =>\n x === 0 || y === 0 ? 0 : Math.abs(Math.floor(x / gcd(x, y)) * y);\n\n // TEST\n return lcm(12, 18);\n\n})();"} {"title": "Levenshtein distance", "language": "JavaScript", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "function levenshtein(a, b) {\n var t = [], u, i, j, m = a.length, n = b.length;\n if (!m) { return n; }\n if (!n) { return m; }\n for (j = 0; j <= n; j++) { t[j] = j; }\n for (i = 1; i <= m; i++) {\n for (u = [i], j = 1; j <= n; j++) {\n u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1]) + 1;\n } t = u;\n } return u[n];\n}\n\n// tests\n[ ['', '', 0],\n ['yo', '', 2],\n ['', 'yo', 2],\n ['yo', 'yo', 0],\n ['tier', 'tor', 2],\n ['saturday', 'sunday', 3],\n ['mist', 'dist', 1],\n ['tier', 'tor', 2],\n ['kitten', 'sitting', 3],\n ['stop', 'tops', 2],\n ['rosettacode', 'raisethysword', 8],\n ['mississippi', 'swiss miss', 8]\n].forEach(function(v) {\n var a = v[0], b = v[1], t = v[2], d = levenshtein(a, b);\n if (d !== t) {\n console.log('levenstein(\"' + a + '\",\"' + b + '\") was ' + d + ' should be ' + t);\n }\n});"} {"title": "Levenshtein distance", "language": "JavaScript from Haskell", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "(() => {\n 'use strict';\n\n // levenshtein :: String -> String -> Int\n const levenshtein = sa => sb => {\n const cs = chars(sa);\n const go = (ns, c) => {\n const calc = z => tpl => {\n const [c1, x, y] = Array.from(tpl);\n return minimum([\n succ(y),\n succ(z),\n x + (c !== c1 ? 1 : 0)\n ]);\n };\n const [n, ns1] = [ns[0], ns.slice(1)];\n return scanl(calc)(succ(n))(\n zip3(cs)(ns)(ns1)\n );\n };\n return last(\n chars(sb).reduce(\n go,\n enumFromTo(0)(cs.length)\n )\n );\n };\n\n // ----------------------- TEST ------------------------\n const main = () => [\n [\"kitten\", \"sitting\"],\n [\"sitting\", \"kitten\"],\n [\"rosettacode\", \"raisethysword\"],\n [\"raisethysword\", \"rosettacode\"]\n ].map(uncurry(levenshtein));\n\n\n // ----------------- GENERIC FUNCTIONS -----------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n\n // TupleN :: a -> b ... -> (a, b ... )\n function TupleN() {\n const\n args = Array.from(arguments),\n n = args.length;\n return 2 < n ? Object.assign(\n args.reduce((a, x, i) => Object.assign(a, {\n [i]: x\n }), {\n type: 'Tuple' + n.toString(),\n length: n\n })\n ) : args.reduce((f, x) => f(x), Tuple);\n };\n\n\n // chars :: String -> [Char]\n const chars = s =>\n s.split('');\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // last :: [a] -> a\n const last = xs => (\n // The last item of a list.\n ys => 0 < ys.length ? (\n ys.slice(-1)[0]\n ) : undefined\n )(xs);\n\n\n // minimum :: Ord a => [a] -> a\n const minimum = xs => (\n // The least value of xs.\n ys => 0 < ys.length ? (\n ys.slice(1)\n .reduce((a, y) => y < a ? y : a, ys[0])\n ) : undefined\n )(xs);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n // A function over a pair, derived\n // from a curried function.\n function () {\n const\n args = arguments,\n xy = Boolean(args.length % 2) ? (\n args[0]\n ) : args;\n return f(xy[0])(xy[1]);\n };\n\n\n // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]\n const zip3 = xs =>\n ys => zs => xs\n .slice(0, Math.min(...[xs, ys, zs].map(length)))\n .map((x, i) => TupleN(x, ys[i], zs[i]));\n\n // MAIN ---\n return JSON.stringify(main())\n})();"} {"title": "List rooted trees", "language": "Javascript", "task": "You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.\n\nIf we use a matching pair of parentheses to represent a bag, the ways are:\n\nFor 1 bag, there's one way:\n ()\t<- a bag\n\nfor 2 bags, there's one way:\n (())\t<- one bag in another\n\nfor 3 bags, there are two:\n ((())) <- 3 bags nested Russian doll style\n (()()) <- 2 bags side by side, inside the third\n\nfor 4 bags, four:\n (()()())\n ((())())\n ((()()))\n (((())))\n\nNote that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.\n\nIt's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.\n\nThis task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.\n\nAs an example output, run 5 bags. There should be 9 ways.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n bagPatterns(5)\n .join('\\n');\n\n // BAG PATTERNS ---------------------------------------\n\n // bagPatterns :: Int -> [String]\n const bagPatterns = n =>\n nub(map(\n composeList([\n commasFromTree,\n depthSortedTree,\n treeFromParentIndices\n ]),\n parentIndexPermutations(n)\n ));\n\n // parentIndexPermutations :: Int -> [[Int]]\n const parentIndexPermutations = n =>\n sequenceA(\n map(curry(enumFromToInt)(0),\n enumFromToInt(0, n - 2)\n )\n );\n\n // treeFromParentIndices :: [Int] -> Tree Int\n const treeFromParentIndices = pxs => {\n const go = (tree, tplIP) =>\n Node(\n tree.root,\n tree.root === snd(tplIP) ? (\n tree.nest.concat(Node(fst(tplIP)), [])\n ) : map(t => go(t, tplIP), tree.nest)\n );\n return foldl(\n go, Node(0, []),\n zip(enumFromToInt(1, pxs.length), pxs)\n );\n };\n\n // Siblings sorted by descendant count\n\n // depthSortedTree :: Tree a -> Tree Int\n const depthSortedTree = t => {\n const go = tree =>\n isNull(tree.nest) ? (\n Node(0, [])\n ) : (() => {\n const xs = map(go, tree.nest);\n return Node(\n 1 + foldl((a, x) => a + x.root, 0, xs),\n sortBy(flip(comparing(x => x.root)), xs)\n );\n })();\n return go(t);\n };\n\n // Serialisation of the tree structure\n\n // commasFromTree :: Tree a -> String\n const commasFromTree = tree => {\n const go = t => `(${concat(map(go, t.nest))})`\n return go(tree);\n };\n\n\n // GENERIC FUNCTIONS --------------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v, // any type of value (but must be consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // composeList :: [(a -> a)] -> (a -> a)\n const composeList = fs =>\n x => fs.reduceRight((a, f) => f(a), x, fs);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n xs.length > 0 ? (() => {\n const unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) => []\n .concat.apply(\n [],\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f)\n );\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) => [x].concat(xs);\n\n // Flexibly handles two or more arguments, applying\n // the function directly if the argument array is complete,\n // or recursing with a concatenation of any existing and\n // newly supplied arguments, if gaps remain.\n // curry :: ((a, b) -> c) -> a -> b -> c\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (\n f.apply(null, xs)\n ) : function() {\n return go(xs.concat(Array.from(arguments)));\n };\n return go(args);\n };\n\n // enumFromToInt :: Int -> Int -> [Int]\n const enumFromToInt = (m, n) =>\n n >= m ? (\n iterateUntil(x => x >= n, x => 1 + x, m)\n ) : [];\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f => (a, b) => f.apply(null, [b, a]);\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 // isNull :: [a] -> Bool\n // isNull :: String -> Bool\n const isNull = xs =>\n Array.isArray(xs) || typeof xs === 'string' ? (\n xs.length < 1\n ) : undefined;\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n let vs = [x],\n h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]\n const liftA2List = (f, xs, ys) =>\n concatMap(x => concatMap(y => [f(x, y)], ys), xs);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // nub :: [a] -> [a]\n const nub = xs => nubBy((a, b) => a === b, xs);\n\n // nubBy :: (a -> a -> Bool) -> [a] -> [a]\n const nubBy = (p, xs) => {\n const go = xs => xs.length > 0 ? (() => {\n const x = xs[0];\n return [x].concat(\n go(xs.slice(1)\n .filter(y => !p(x, y))\n )\n )\n })() : [];\n return go(xs);\n };\n\n // sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a)\n const sequenceA = tfa =>\n traverseList(x => x, tfa);\n\n // traverseList :: (Applicative f) => (a -> f b) -> [a] -> f [b]\n const traverseList = (f, xs) => {\n const lng = xs.length;\n return 0 < lng ? (() => {\n const\n vLast = f(xs[lng - 1]),\n t = vLast.type || 'List';\n return xs.slice(0, -1).reduceRight(\n (ys, x) => liftA2List(cons, f(x), ys),\n liftA2List(cons, vLast, [[]])\n );\n })() : [\n []\n ];\n };\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => Tuple(x, ys[i]));\n\n // MAIN ---\n return main()\n})();"} {"title": "Long year", "language": "JavaScript from TypeScript", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "const isLongYear = (year) => {\n const jan1 = new Date(year, 0, 1);\n const dec31 = new Date(year, 11, 31);\n return (4 == jan1.getDay() || 4 == dec31.getDay())\n}\n\nfor (let y = 1995; y <= 2045; y++) {\n if (isLongYear(y)) {\n console.log(y)\n }\n}"} {"title": "Longest common subsequence", "language": "JavaScript from Java", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "function lcs_greedy(x,y){\n var p1, i, idx,\n symbols = {},\n r = 0,\n p = 0,\n l = 0,\n m = x.length,\n n = y.length,\n s = new Buffer((m < n) ? n : m);\n\n p1 = popsym(0);\n\n for (i = 0; i < m; i++) {\n p = (r === p) ? p1 : popsym(i);\n p1 = popsym(i + 1);\n if (p > p1) {\n i += 1;\n idx = p1;\n } else {\n idx = p;\n }\n\n if (idx === n) {\n p = popsym(i);\n } else {\n r = idx;\n s[l] = x.charCodeAt(i);\n l += 1;\n }\n }\n return s.toString('utf8', 0, l);\n\t\n function popsym(index) {\n var s = x[index],\n pos = symbols[s] + 1;\n\n pos = y.indexOf(s, ((pos > r) ? pos : r));\n if (pos === -1) { pos = n; }\n symbols[s] = pos;\n return pos;\n }\n}"} {"title": "Longest common substring", "language": "JavaScript from Haskell", "task": "Write a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*Generalize Suffix Tree\n*[[Ukkonen's Suffix Tree Construction]]\n\n", "solution": "(() => {\n 'use strict';\n\n // longestCommon :: String -> String -> String\n const longestCommon = (s1, s2) => maximumBy(\n comparing(length),\n intersect(...apList(\n [s => map(\n concat,\n concatMap(tails, compose(tail, inits)(s))\n )],\n [s1, s2]\n ))\n );\n\n // main :: IO ()\n const main = () =>\n console.log(\n longestCommon(\n \"testing123testing\",\n \"thisisatest\"\n )\n );\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Each member of a list of functions applied to each\n // of a list of arguments, deriving a list of new values.\n\n // apList (<*>) :: [(a -> b)] -> [a] -> [b]\n const apList = (fs, xs) => //\n fs.reduce((a, f) => a.concat(\n xs.reduce((a, x) => a.concat([f(x)]), [])\n ), []);\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = (f, xs) =>\n xs.reduce((a, x) => a.concat(f(x)), []);\n\n // inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3]\n // inits('abc') -> [\"\", \"a\", \"ab\", \"abc\"]\n\n // inits :: [a] -> [[a]]\n // inits :: String -> [String]\n const inits = xs => [\n []\n ]\n .concat(('string' === typeof xs ? xs.split('') : xs)\n .map((_, i, lst) => lst.slice(0, i + 1)));\n\n // intersect :: (Eq a) => [a] -> [a] -> [a]\n const intersect = (xs, ys) =>\n xs.filter(x => -1 !== ys.indexOf(x));\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n 0 < xs.length ? (\n xs.slice(1)\n .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])\n ) : undefined;\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // tails :: [a] -> [[a]]\n const tails = xs => {\n const\n es = ('string' === typeof xs) ? (\n xs.split('')\n ) : xs;\n return es.map((_, i) => es.slice(i))\n .concat([\n []\n ]);\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Longest increasing subsequence", "language": "JavaScript", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "function getLis(input) {\n if (input.length === 0) {\n return [];\n }\n\n var lisLenPerIndex = [];\n let max = { index: 0, length: 1 };\n\n for (var i = 0; i < input.length; i++) {\n lisLenPerIndex[i] = 1;\n for (var j = i - 1; j >= 0; j--) {\n if (input[i] > input[j] && lisLenPerIndex[j] >= lisLenPerIndex[i]) {\n var length = lisLenPerIndex[i] = lisLenPerIndex[j] + 1;\n if (length > max.length) {\n max = { index: i, length };\n }\n }\n }\n }\n\n var lis = [input[max.index]];\n for (var i = max.index; i >= 0 && max.length !== 0; i--) {\n if (input[max.index] > input[i] && lisLenPerIndex[i] === max.length - 1) {\n lis.unshift(input[i]);\n max.length--;\n }\n }\n\n return lis;\n}\n\nconsole.log(getLongestIncreasingSubsequence([0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]));\nconsole.log(getLongestIncreasingSubsequence([3, 2, 6, 4, 5, 1]));\n"} {"title": "Lucky and even lucky numbers", "language": "JavaScript", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n +-------------------+----------------------------------------------------+\n | j | Jth lucky number |\n | j , lucky | Jth lucky number |\n | j , evenLucky | Jth even lucky number |\n | | |\n | j k | Jth through Kth (inclusive) lucky numbers |\n | j k lucky | Jth through Kth (inclusive) lucky numbers |\n | j k evenLucky | Jth through Kth (inclusive) even lucky numbers |\n | | |\n | j -k | all lucky numbers in the range j --> |k| |\n | j -k lucky | all lucky numbers in the range j --> |k| |\n | j -k evenLucky | all even lucky numbers in the range j --> |k| |\n +-------------------+----------------------------------------------------+\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki Lucky numbers.\n* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.\n* Entry lucky numbers on The Eric Weisstein's World of Mathematics.\n", "solution": "function luckyNumbers(opts={}) {\n /**************************************************************************\\\n | OPTIONS |\n |**************************************************************************|\n | even ...... boolean ............. return even/uneven numbers |\n | (default: false) |\n | |\n | nth ....... number ............... return nth number |\n | |\n | through ... number ............... return numbers from #1 to number |\n | OR array[from, to] ... return numbers on index |\n | from array[from] to array[to] |\n | |\n | range ..... array[from, to] ...... return numbers between from and to |\n \\**************************************************************************/\n\n opts.even = opts.even || false;\n if (typeof opts.through == 'number') opts.through = [0, opts.through];\n let out = [],\n x = opts.even ? 2 : 1,\n max = opts.range ? opts.range[1] * 3\n : opts.through ? opts.through[1] * 12\n : opts.nth ? opts.nth * 15\n : 2000;\n\n for (x; x <= max; x = x+2) out.push(x); // fill\n for (x = 1; x < Math.floor(out.length / 2); x++) { // sieve\n let i = out.length;\n while (i--)\n (i+1) % out[x] == 0 && out.splice(i, 1);\n }\n\n if (opts.nth) return out[opts.nth-1];\n if (opts.through) return out.slice(opts.through[0], opts.through[1]);\n if (opts.range) return out.filter(function(val) {\n return val >= opts.range[0] && val <= opts.range[1];\n });\n return out;\n}\n\n/* TESTING */\n// blank\nconsole.log( luckyNumbers() );\n// showing the first twenty lucky numbers\nconsole.log( luckyNumbers({through: 20}) );\n// showing the first twenty even lucky numbers\nconsole.log( luckyNumbers({even: true, through: 20}) );\n// showing all lucky numbers between 6,000 and 6,100 (inclusive)\nconsole.log( luckyNumbers({range: [6000, 6100]}) );\n// showing all even lucky numbers in the same range as above\nconsole.log( luckyNumbers({even: true, range: [6000, 6100]}) );\n// showing the 10,000th lucky number (extra credit)\nconsole.log( luckyNumbers({nth: 10000}) );\n// showing the 10,000th even lucky number (extra credit)\nconsole.log( luckyNumbers({even: true, nth: 10000}) );\n"} {"title": "MAC vendor lookup", "language": "Javascript", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA MAC address that does not return a valid result should return the String \"N/A\". An error related to the network connectivity or the API should return a null result.\n\nMany implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "var mac = \"88:53:2E:67:07:BE\";\nfunction findmac(){\n\twindow.open(\"http://api.macvendors.com/\" + mac);\n}\n\nfindmac();\n"} {"title": "MD4", "language": "JavaScript", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \"Rosetta Code\" (without quotes). \nYou may either call an MD4 library, or implement MD4 in your language.\n\n'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.\n\nRFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.\n\n", "solution": "const md4func = () => {\n\n const hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */\n const b64pad = \"\"; /* base-64 pad character. \"=\" for strict RFC compliance */\n const chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n const tab = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\n /**\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n const safe_add = (x, y) => {\n const lsw = (x & 0xFFFF) + (y & 0xFFFF);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xFFFF);\n };\n\n /**\n * Bitwise rotate a 32-bit number to the left.\n */\n const rol = (num, cnt) => (num << cnt) | (num >>> (32 - cnt));\n\n /**\n * Convert a string to an array of little-endian words\n * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.\n */\n const str2binl = str => {\n const bin = Array();\n const mask = (1 << chrsz) - 1;\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);\n return bin;\n };\n\n /**\n * Convert an array of little-endian words to a string\n */\n const binl2str = bin => {\n let str = \"\";\n const mask = (1 << chrsz) - 1;\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);\n return str;\n };\n\n /**\n * Convert an array of little-endian words to a hex string.\n */\n const binl2hex = binarray => {\n let str = \"\";\n for (let i = 0; i < binarray.length * 4; i++) {\n str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +\n hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);\n }\n return str;\n };\n\n /**\n * Convert an array of little-endian words to a base-64 string\n */\n const binl2b64 = binarray => {\n let str = \"\";\n for (let i = 0; i < binarray.length * 4; i += 3) {\n const triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16)\n | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8)\n | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;\n else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);\n }\n }\n return str;\n };\n\n\n /**\n * Calculate the MD4 of an array of little-endian words, and a bit length\n */\n const core_md4 = (x, len) => {\n\n x[len >> 5] |= 0x80 << (len % 32);\n x[(((len + 64) >>> 9) << 4) + 14] = len;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n\n for (let i = 0; i < x.length; i += 16) {\n\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n\n a = md4_ff(a, b, c, d, x[i], 3);\n d = md4_ff(d, a, b, c, x[i + 1], 7);\n c = md4_ff(c, d, a, b, x[i + 2], 11);\n b = md4_ff(b, c, d, a, x[i + 3], 19);\n a = md4_ff(a, b, c, d, x[i + 4], 3);\n d = md4_ff(d, a, b, c, x[i + 5], 7);\n c = md4_ff(c, d, a, b, x[i + 6], 11);\n b = md4_ff(b, c, d, a, x[i + 7], 19);\n a = md4_ff(a, b, c, d, x[i + 8], 3);\n d = md4_ff(d, a, b, c, x[i + 9], 7);\n c = md4_ff(c, d, a, b, x[i + 10], 11);\n b = md4_ff(b, c, d, a, x[i + 11], 19);\n a = md4_ff(a, b, c, d, x[i + 12], 3);\n d = md4_ff(d, a, b, c, x[i + 13], 7);\n c = md4_ff(c, d, a, b, x[i + 14], 11);\n b = md4_ff(b, c, d, a, x[i + 15], 19);\n\n a = md4_gg(a, b, c, d, x[i], 3);\n d = md4_gg(d, a, b, c, x[i + 4], 5);\n c = md4_gg(c, d, a, b, x[i + 8], 9);\n b = md4_gg(b, c, d, a, x[i + 12], 13);\n a = md4_gg(a, b, c, d, x[i + 1], 3);\n d = md4_gg(d, a, b, c, x[i + 5], 5);\n c = md4_gg(c, d, a, b, x[i + 9], 9);\n b = md4_gg(b, c, d, a, x[i + 13], 13);\n a = md4_gg(a, b, c, d, x[i + 2], 3);\n d = md4_gg(d, a, b, c, x[i + 6], 5);\n c = md4_gg(c, d, a, b, x[i + 10], 9);\n b = md4_gg(b, c, d, a, x[i + 14], 13);\n a = md4_gg(a, b, c, d, x[i + 3], 3);\n d = md4_gg(d, a, b, c, x[i + 7], 5);\n c = md4_gg(c, d, a, b, x[i + 11], 9);\n b = md4_gg(b, c, d, a, x[i + 15], 13);\n\n a = md4_hh(a, b, c, d, x[i], 3);\n d = md4_hh(d, a, b, c, x[i + 8], 9);\n c = md4_hh(c, d, a, b, x[i + 4], 11);\n b = md4_hh(b, c, d, a, x[i + 12], 15);\n a = md4_hh(a, b, c, d, x[i + 2], 3);\n d = md4_hh(d, a, b, c, x[i + 10], 9);\n c = md4_hh(c, d, a, b, x[i + 6], 11);\n b = md4_hh(b, c, d, a, x[i + 14], 15);\n a = md4_hh(a, b, c, d, x[i + 1], 3);\n d = md4_hh(d, a, b, c, x[i + 9], 9);\n c = md4_hh(c, d, a, b, x[i + 5], 11);\n b = md4_hh(b, c, d, a, x[i + 13], 15);\n a = md4_hh(a, b, c, d, x[i + 3], 3);\n d = md4_hh(d, a, b, c, x[i + 11], 9);\n c = md4_hh(c, d, a, b, x[i + 7], 11);\n b = md4_hh(b, c, d, a, x[i + 15], 15);\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n }\n\n return Array(a, b, c, d);\n\n };\n\n /**\n * These functions implement the basic operation for each round of the\n * algorithm.\n */\n const md4_cmn = (q, a, b, x, s, t) => safe_add(\n rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);\n\n const md4_ff = (a, b, c, d, x, s) => md4_cmn(\n (b & c) | ((~b) & d), a, 0, x, s, 0);\n\n const md4_gg = (a, b, c, d, x, s) => md4_cmn(\n (b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249);\n\n const md4_hh = (a, b, c, d, x, s) => md4_cmn(\n b ^ c ^ d, a, 0, x, s, 1859775393);\n\n /**\n * Calculate the HMAC-MD4, of a key and some data\n */\n const core_hmac_md4 = (key, data) => {\n\n let bkey = str2binl(key);\n if (bkey.length > 16) {\n bkey = core_md4(bkey, key.length * chrsz)\n }\n\n const ipad = Array(16);\n const opad = Array(16);\n\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636;\n opad[i] = bkey[i] ^ 0x5C5C5C5C;\n }\n const hash = core_md4(\n ipad.concat(str2binl(data)), 512 + data.length * chrsz);\n\n return core_md4(opad.concat(hash), 512 + 128);\n };\n\n /**\n * These are the functions you'll usually want to call\n */\n return {\n hex_md4: s => binl2hex(core_md4(str2binl(s), s.length * chrsz)),\n b64_md4: s => binl2b64(core_md4(str2binl(s), s.length * chrsz)),\n str_md4: s => binl2str(core_md4(str2binl(s), s.length * chrsz)),\n hex_hmac_md4: (key, data) => binl2hex(core_hmac_md4(key, data)),\n b64_hmac_md4: (key, data) => binl2b64(core_hmac_md4(key, data)),\n str_hmac_md4: (key, data) => binl2str(core_hmac_md4(key, data)),\n };\n\n};\n\nconst md4 = md4func();\nconsole.log(md4.hex_md4('Rosetta Code'));"} {"title": "Magic 8-ball", "language": "JavaScript", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "//console\nvar answers = [ \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n \"Very doubtful\"])\n\nconsole.log(\"ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!\")\n\nfor(;;){\n var answer = prompt(\"question:\")\n console.log(answer)\nconsole.log(answers[Math.floor(Math.random()*answers.length)]);\n}\n"} {"title": "Magic squares of doubly even order", "language": "JavaScript from Haskell", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "(() => {\n 'use strict';\n\n // doublyEvenMagicSquare :: Int -> [[Int]]\n const doublyEvenMagicSquare = n =>\n 0 === n % 4 ? (() => {\n const\n sqr = n * n,\n power = Math.log2(sqr),\n scale = replicate(n / 4);\n return chunksOf(n)(\n map((x, i) => x ? 1 + i : sqr - i)(\n isInt(power) ? truthSeries(power) : (\n compose(\n flatten,\n scale,\n map(scale),\n chunksOf(4)\n )(truthSeries(4))\n )\n )\n );\n })() : undefined;\n\n // truthSeries :: Int -> [Bool]\n const truthSeries = n =>\n 0 >= n ? (\n [true]\n ) : (() => {\n const xs = truthSeries(n - 1);\n return xs.concat(xs.map(x => !x));\n })();\n\n\n\n // TEST -----------------------------------------------\n const main = () =>\n // Magic squares of orders 4, 8 and 12, with\n // checks of row, column and diagonal sums.\n intercalate('\\n\\n')(\n map(n => {\n const\n lines = doublyEvenMagicSquare(n),\n sums = map(sum)(\n lines.concat(\n transpose(lines)\n .concat(diagonals(lines))\n )\n ),\n total = sums[0];\n return unlines([\n \"Order: \" + str(n),\n \"Summing to: \" + str(total),\n \"Row, column and diagonal sums checked: \" +\n str(all(eq(total))(sums)) + '\\n',\n unlines(map(compose(\n intercalate(' '),\n map(compose(justifyRight(3)(' '), str))\n ))(lines))\n ]);\n })([4, 8, 12])\n );\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // all :: (a -> Bool) -> [a] -> Bool\n const all = p =>\n // True if p(x) holds for every x in xs.\n xs => xs.every(p);\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n => xs =>\n enumFromThenTo(0)(n)(\n xs.length - 1\n ).reduce(\n (a, i) => a.concat([xs.slice(i, (n + i))]),\n []\n );\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // diagonals :: [[a]] -> [[a], [a]]\n const diagonals = rows =>\n // Two diagonal sequences,\n // from top left and bottom left\n // respectively, of a given matrix.\n map(flip(zipWith(index))(\n enumFromTo(0)(pred(\n 0 < rows.length ? (\n rows[0].length\n ) : 0\n ))\n ))([rows, reverse(rows)]);\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = x1 => x2 => y => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a => b => a === b;\n\n // flatten :: NestedList a -> [a]\n const flatten = nest => nest.flat(Infinity);\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n x => y => f(y)(x);\n\n // index (!!) :: [a] -> Int -> a\n const index = xs => i => xs[i];\n\n // intercalate :: String -> [String] -> String\n const intercalate = s =>\n xs => xs.join(s);\n\n // isInt :: Int -> Bool\n const isInt = x => x === Math.floor(x);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n => cFiller => s =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f => xs =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // pred :: Enum a => a -> a\n const pred = x => x - 1;\n\n // replicate :: Int -> a -> [a]\n const replicate = n => x =>\n Array.from({\n length: n\n }, () => x);\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // show :: a -> String\n const show = x => JSON.stringify(x);\n\n // str :: a -> String\n const str = x => x.toString();\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map((row) => row[iCol]));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // MAIN ------------------------------------------------\n return main();\n})();"} {"title": "Magic squares of odd order", "language": "JavaScript from Mathematica", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "(function () {\n\n // n -> [[n]]\n function magic(n) {\n return n % 2 ? rotation(\n transposed(\n rotation(\n table(n)\n )\n )\n ) : null;\n }\n\n // [[a]] -> [[a]]\n function rotation(lst) {\n return lst.map(function (row, i) {\n return rotated(\n row, ((row.length + 1) / 2) - (i + 1)\n );\n })\n }\n\n // [[a]] -> [[a]]\n function transposed(lst) {\n return lst[0].map(function (col, i) {\n return lst.map(function (row) {\n return row[i];\n })\n });\n }\n\n // [a] -> n -> [a]\n function rotated(lst, n) {\n var lng = lst.length,\n m = (typeof n === 'undefined') ? 1 : (\n n < 0 ? lng + n : (n > lng ? n % lng : n)\n );\n\n return m ? (\n lst.slice(-m).concat(lst.slice(0, lng - m))\n ) : lst;\n }\n\n // n -> [[n]]\n function table(n) {\n var rngTop = rng(1, n);\n\n return rng(0, n - 1).map(function (row) {\n return rngTop.map(function (x) {\n return row * n + x;\n });\n });\n }\n\n // [m..n]\n function rng(m, n) {\n return Array.apply(null, Array(n - m + 1)).map(\n function (x, i) {\n return m + i;\n });\n }\n\n /******************** TEST WITH 3, 5, 11 ***************************/\n\n // Results as right-aligned wiki tables\n function wikiTable(lstRows, blnHeaderRow, strStyle) {\n var css = strStyle ? 'style=\"' + strStyle + '\"' : '';\n\n return '{| class=\"wikitable\" ' + css + lstRows.map(\n function (lstRow, iRow) {\n var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|'),\n strDbl = strDelim + strDelim;\n\n return '\\n|-\\n' + strDelim + ' ' + lstRow.join(' ' + strDbl + ' ');\n }).join('') + '\\n|}';\n }\n\n return [3, 5, 11].map(\n function (n) {\n var w = 2.5 * n;\n return 'magic(' + n + ')\\n\\n' + wikiTable(\n magic(n), false, 'text-align:center;width:' + w + 'em;height:' + w + 'em;table-layout:fixed;'\n )\n }\n ).join('\\n\\n')\n})();"} {"title": "Magic squares of odd order", "language": "JavaScript from Haskell", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "(() => {\n\n // Number of rows -> n rows of integers\n // oddMagicTable :: Int -> [[Int]]\n const oddMagicTable = n =>\n mapAsTable(n, siamMap(quot(n, 2)));\n\n // Highest index of square -> Siam xys so far -> xy -> next xy coordinate\n // nextSiam :: Int -> M.Map (Int, Int) Int -> (Int, Int) -> (Int, Int)\n const nextSiam = (uBound, sMap, [x, y]) => {\n const [a, b] = [x + 1, y - 1];\n return (a > uBound && b < 0) ? (\n [uBound, 1] // Move down if obstructed by corner\n ) : a > uBound ? (\n [0, b] // Wrap at right edge\n ) : b < 0 ? (\n [a, uBound] // Wrap at upper edge\n ) : mapLookup(sMap, [a, b])\n .nothing ? ( // Unimpeded default: one up one right\n [a, b]\n ) : [a - 1, b + 2]; // Position occupied: move down\n };\n\n // Order of table -> Siamese indices keyed by coordinates\n // siamMap :: Int -> M.Map (Int, Int) Int\n const siamMap = n => {\n const\n uBound = 2 * n,\n sPath = (uBound, sMap, xy, n) => {\n const [x, y] = xy,\n newMap = mapInsert(sMap, xy, n);\n return (y == uBound && x == quot(uBound, 2) ? (\n newMap\n ) : sPath(\n uBound, newMap, nextSiam(uBound, newMap, [x, y]), n + 1));\n };\n return sPath(uBound, {}, [n, 0], 1);\n };\n\n // Size of square -> integers keyed by coordinates -> rows of integers\n // mapAsTable :: Int -> M.Map (Int, Int) Int -> [[Int]]\n const mapAsTable = (nCols, dct) => {\n const axis = enumFromTo(0, nCols - 1);\n return map(row => map(k => fromJust(mapLookup(dct, k)), row),\n bind(axis, y => [bind(axis, x => [\n [x, y]\n ])]));\n };\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // bind :: [a] -> (a -> [b]) -> [b]\n const bind = (xs, f) => [].concat.apply([], xs.map(f));\n\n // curry :: Function -> Function\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :\n function () {\n return go(xs.concat(Array.from(arguments)));\n };\n return go([].slice.call(args, 1));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // fromJust :: M a -> a\n const fromJust = m => m.nothing ? {} : m.just;\n\n // fst :: [a, b] -> a\n const fst = pair => pair.length === 2 ? pair[0] : undefined;\n\n // intercalate :: String -> [a] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (cFiller.repeat(n) + strText)\n .slice(-n)\n ) : strText;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // log :: a -> IO ()\n const log = (...args) =>\n console.log(\n args\n .map(show)\n .join(' -> ')\n );\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // mapInsert :: Dictionary -> k -> v -> Dictionary\n const mapInsert = (dct, k, v) =>\n (dct[(typeof k === 'string' && k) || show(k)] = v, dct);\n\n // mapKeys :: Map k a -> [k]\n const mapKeys = dct =>\n sortBy(mappendComparing([snd, fst]),\n map(JSON.parse, Object.keys(dct)));\n\n // mapLookup :: Dictionary -> k -> Maybe v\n const mapLookup = (dct, k) => {\n const\n v = dct[(typeof k === 'string' && k) || show(k)],\n blnJust = (typeof v !== 'undefined');\n return {\n nothing: !blnJust,\n just: v\n };\n };\n\n // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering)\n const mappendComparing = fs => (x, y) =>\n fs.reduce((ord, f) => {\n if (ord !== 0) return ord;\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n }, 0);\n\n // maximum :: [a] -> a\n const maximum = xs =>\n xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined);\n\n // Integral a => a -> a -> a\n const quot = (n, m) => Math.floor(n / m);\n\n // show :: a -> String\n const show = x => JSON.stringify(x);\n //\n // snd :: (a, b) -> b\n const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined;\n //\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) => xs.slice()\n .sort(f);\n\n // table :: String -> [[String]] -> [String]\n const table = (delim, rows) =>\n map(curry(intercalate)(delim),\n transpose(map(col =>\n map(curry(justifyRight)(maximum(map(length, col)))(' '), col),\n transpose(rows))));\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, col) => xs.map(row => row[col]));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // TEST -------------------------------------------------------------------\n\n return intercalate('\\n\\n',\n bind([3, 5, 7],\n n => unlines(table(\" \",\n map(xs => map(show, xs), oddMagicTable(n))))));\n})();"} {"title": "Map range", "language": "JavaScript", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "// Javascript doesn't have built-in support for ranges\n// Insted we use arrays of two elements to represent ranges\nvar mapRange = function(from, to, s) {\n return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]);\n};\n\nvar range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nfor (var i = 0; i < range.length; i++) {\n range[i] = mapRange([0, 10], [-1, 0], range[i]);\n}\n\nconsole.log(range);"} {"title": "Matrix digital rain", "language": "Javascript", "task": "Implement the Matrix Digital Rain visual effect from the movie \"The Matrix\" as described in Wikipedia.\n\nProvided is a reference implementation in Common Lisp to be run in a terminal.\n\n", "solution": "var tileSize = 20;\n// a higher fade factor will make the characters fade quicker\nvar fadeFactor = 0.05;\n\nvar canvas;\nvar ctx;\n\nvar columns = [];\nvar maxStackHeight;\n\nfunction init() {\n\tcanvas = document.getElementById('canvas');\n\tctx = canvas.getContext('2d');\n\n // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver\n const resizeObserver = new ResizeObserver(entries =>\n {\n for (let entry of entries)\n {\n if (entry.contentBoxSize)\n {\n // Firefox implements `contentBoxSize` as a single content rect, rather than an array\n const contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;\n\n canvas.width = contentBoxSize.inlineSize;\n canvas.height = window.innerHeight;\n\n initMatrix();\n }\n }\n });\n\n // observe the size of the document\n resizeObserver.observe(document.documentElement);\n\n\t// start the main loop\n\ttick();\n}\n\nfunction initMatrix() {\n columns = [];\n\n maxStackHeight = Math.ceil(canvas.height/tileSize);\n\n // divide the canvas into columns\n for (let i = 0 ; i < canvas.width/tileSize ; ++i) {\n var column = {};\n // save the x position of the column\n column.x = i*tileSize;\n // create a random stack height for the column\n column.stackHeight = 10+Math.random()*maxStackHeight;\n // add a counter to count the stack height\n column.stackCounter = 0;\n // add the column to the list\n columns.push(column);\n }\n}\n\nfunction draw() {\n // draw a semi transparent black rectangle on top of the scene to slowly fade older characters\n ctx.fillStyle = \"rgba(0 , 0 , 0 , \"+fadeFactor+\")\";\n ctx.fillRect(0 , 0 , canvas.width , canvas.height);\n\n ctx.font = (tileSize-2)+\"px monospace\";\n ctx.fillStyle = \"rgb(0 , 255 , 0)\";\n for (let i = 0 ; i < columns.length ; ++i) {\n // pick a random ascii character (change the 94 to a higher number to include more characters)\n var randomCharacter = String.fromCharCode(33+Math.floor(Math.random()*94));\n ctx.fillText(randomCharacter , columns[i].x , columns[i].stackCounter*tileSize+tileSize);\n\n // if the stack is at its height limit, pick a new random height and reset the counter\n if (++columns[i].stackCounter >= columns[i].stackHeight)\n {\n columns[i].stackHeight = 10+Math.random()*maxStackHeight;\n columns[i].stackCounter = 0;\n }\n }\n}\n\n// MAIN LOOP\nfunction tick() {\t\n draw();\n setTimeout(tick , 50);\n}\n\nvar b_isFullscreen = false;\n\nfunction fullscreen() {\n var elem = document.documentElement;\n if (elem.requestFullscreen) {\n elem.requestFullscreen();\n }\n else if (elem.webkitRequestFullscreen) { \n elem.webkitRequestFullscreen(); // Safari\n }\n else if (elem.msRequestFullscreen) { \n elem.msRequestFullscreen(); // IE11\n }\n}\n\nfunction exitFullscreen() {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n }\n else if (document.webkitExitFullscreen) {\n document.webkitExitFullscreen(); // Safari\n }\n else if (document.msExitFullscreen) {\n document.msExitFullscreen(); // IE11\n }\n}\n\nfunction toggleFullscreen() {\n if (!b_isFullscreen) {\n fullscreen();\n b_isFullscreen = true;\n }\n else {\n exitFullscreen();\n b_isFullscreen = false;\n }\n}\n\nfunction updateTileSize() {\n tileSize = Math.min(Math.max(document.getElementById(\"tileSize\").value , 10) , 100);\n initMatrix();\n}\n\nfunction updateFadeFactor() {\n fadeFactor = Math.min(Math.max(document.getElementById(\"fadeFactor\").value , 0.0) , 1.0);\n initMatrix();\n}"} {"title": "Maximum triangle path sum", "language": "Javascript", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "var arr = [\n[55],\n[94, 48],\n[95, 30, 96],\n[77, 71, 26, 67],\n[97, 13, 76, 38, 45],\n[07, 36, 79, 16, 37, 68],\n[48, 07, 09, 18, 70, 26, 06],\n[18, 72, 79, 46, 59, 79, 29, 90],\n[20, 76, 87, 11, 32, 07, 07, 49, 18],\n[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],\n[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],\n[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],\n[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n];\n\nwhile (arr.length !== 1) {\n var len = arr.length;\n var row = [];\n var current = arr[len-2];\n var currentLen = current.length - 1;\n var end = arr[len-1];\n\n for ( var i = 0; i <= currentLen; i++ ) {\n row.push(Math.max(current[i] + end[i] || 0, current[i] + end[i+1] || 0) )\n }\n\n arr.pop();\n arr.pop();\n\n arr.push(row);\n}\n\nconsole.log(arr);\n"} {"title": "Maximum triangle path sum", "language": "Javascript from Haskell", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "(() => {\n \"use strict\";\n\n // ------------------ MAX PATH SUM -------------------\n\n // Working from the bottom of the triangle upwards,\n // summing each number with the larger of the two below\n // until the maximum emerges at the top.\n\n // maxPathSum ::[[Int]] -> Int\n const maxPathSum = xss =>\n // A list of lists folded down to a list of just one\n // remaining integer.\n foldr1(\n // The accumulator, zipped with the tail of the\n // accumulator, yields pairs of adjacent sums.\n (ys, xs) => zipWith3(\n\n // Plus greater of two below\n (a, b, c) => a + Math.max(b, c)\n )(xs)(ys)(ys.slice(1))\n )(xss)[0];\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // foldr1 :: (a -> a -> a) -> [a] -> a\n const foldr1 = f =>\n xs => 0 < xs.length ? (\n xs.slice(0, -1).reduceRight(\n f, xs.slice(-1)[0]\n )\n ) : [];\n\n\n // zipWith3 :: (a -> b -> c -> d) ->\n // [a] -> [b] -> [c] -> [d]\n const zipWith3 = f =>\n xs => ys => zs => Array.from({\n length: Math.min(\n ...[xs, ys, zs].map(x => x.length)\n )\n }, (_, i) => f(xs[i], ys[i], zs[i]));\n\n\n // ---------------------- TEST -----------------------\n return maxPathSum([\n [55],\n [94, 48],\n [95, 30, 96],\n [77, 71, 26, 67],\n [97, 13, 76, 38, 45],\n [7, 36, 79, 16, 37, 68],\n [48, 7, 9, 18, 70, 26, 6],\n [18, 72, 79, 46, 59, 79, 29, 90],\n [20, 76, 87, 11, 32, 7, 7, 49, 18],\n [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],\n [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],\n [2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23],\n [92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42],\n [56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72],\n [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],\n [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52],\n [6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15],\n [27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]\n ]);\n})();"} {"title": "McNuggets problem", "language": "JavaScript", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const\n size = n => enumFromTo(0)(\n quot(100, n)\n ),\n nuggets = new Set(\n size(6).flatMap(\n x => size(9).flatMap(\n y => size(20).flatMap(\n z => {\n const v = sum([6 * x, 9 * y, 20 * z]);\n return 101 > v ? (\n [v]\n ) : [];\n }\n ),\n )\n )\n ),\n xs = dropWhile(\n x => nuggets.has(x),\n enumFromThenTo(100, 99, 1)\n );\n\n return 0 < xs.length ? (\n xs[0]\n ) : 'No unreachable quantities found in this range';\n };\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n const dropWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // ft :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return console.log(\n main()\n );\n})();"} {"title": "Mian-Chowla sequence", "language": "JavaScript from Python", "task": "The Mian-Chowla sequence is an integer sequence defined recursively.\n\n\nMian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const genMianChowla = mianChowlas();\n console.log([\n 'Mian-Chowla terms 1-30:',\n take(30)(\n genMianChowla\n ),\n\n '\\nMian-Chowla terms 91-100:',\n (\n drop(60)(genMianChowla),\n take(10)(\n genMianChowla\n )\n )\n ].join('\\n') + '\\n');\n };\n\n // mianChowlas :: Gen [Int]\n function* mianChowlas() {\n let\n mcs = [1],\n sumSet = new Set([2]),\n x = 1;\n while (true) {\n yield x;\n [sumSet, mcs, x] = nextMC(sumSet, mcs, x);\n }\n }\n\n // nextMC :: Set Int -> [Int] -> Int -> (Set Int, [Int], Int)\n const nextMC = (setSums, mcs, n) => {\n // Set of sums -> Series up to n -> Next term in series\n const valid = x => {\n for (const m of mcs) {\n if (setSums.has(x + m)) return false;\n }\n return true;\n };\n const x = until(valid)(x => 1 + x)(n);\n return [\n sumList(mcs)(x)\n .reduce(\n (a, n) => (a.add(n), a),\n setSums\n ),\n mcs.concat(x),\n x\n ];\n };\n\n // sumList :: [Int] -> Int -> [Int]\n const sumList = xs =>\n // Series so far -> additional term -> new sums\n n => [2 * n].concat(xs.map(x => n + x));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = n =>\n xs => Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n)(xs), xs);\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n 'GeneratorFunction' !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p =>\n f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Middle three digits", "language": "JavaScript", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "function middleThree(x){\n var n=''+Math.abs(x); var l=n.length-1;\n if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1));\n return n.slice(l/2-1,l/2+2);\n}\n\n[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,\n1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){\n try{console.log(n,middleThree(n))}catch(e){console.error(e.message)}\n});"} {"title": "Middle three digits", "language": "JavaScript from Python", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "(() => {\n 'use strict';\n\n // mid3digits :: Int -> Either String String\n const mid3digits = n => {\n const\n m = abs(n),\n s = m.toString();\n return 100 > m ? (\n Left('Less than 3 digits')\n ) : even(length(s)) ? (\n Left('Even digit count')\n ) : Right(take(3, drop(quot(length(s) - 3, 2), s)));\n };\n\n // TEST -----------------------------------------------\n const main = () => {\n const\n xs = [\n 123, 12345, 1234567, 987654321, 10001, -10001, -123,\n -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0\n ],\n w = maximum(map(x => x.toString().length, xs));\n return (\n unlines(map(\n n => justifyRight(w, ' ', n.toString()) + ' -> ' +\n either(\n s => '(' + s + ')',\n id,\n mid3digits(n)\n ),\n xs\n ))\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: 'Either',\n Left: x\n });\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: 'Either',\n Right: x\n });\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> Generator [a] -> Generator [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) =>\n Infinity > length(xs) ? (\n xs.slice(n)\n ) : (take(n, xs), xs);\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = (fl, fr, e) =>\n 'Either' === e.type ? (\n undefined !== e.Left ? (\n fl(e.Left)\n ) : fr(e.Right)\n ) : undefined;\n\n // even :: Int -> Bool\n const even = n => 0 === n % 2;\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n const foldl1 = (f, xs) =>\n 1 < xs.length ? xs.slice(1)\n .reduce(f, xs[0]) : xs[0];\n\n // id :: a -> a\n const id = x => x;\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n 0 < xs.length ? (\n foldl1((a, x) => x > a ? x : a, xs)\n ) : undefined;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} {"title": "Mind boggling card trick", "language": "Javascript from Haskell", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (The above two steps complete the swap of '''X''' cards of the \"red\" and \"black\" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n const\n // DEALT\n [rs_, bs_, discards] = threeStacks(\n map(n =>\n even(n) ? (\n 'R'\n ) : 'B', knuthShuffle(\n enumFromTo(1, 52)\n )\n )\n ),\n\n // SWAPPED\n nSwap = randomRInt(1, min(rs_.length, bs_.length)),\n [rs, bs] = exchange(nSwap, rs_, bs_),\n\n // CHECKED\n rrs = filter(c => 'R' === c, rs).join(''),\n bbs = filter(c => 'B' === c, bs).join('');\n return unlines([\n 'Discarded: ' + discards.join(''),\n 'Swapped: ' + nSwap,\n 'Red pile: ' + rs.join(''),\n 'Black pile: ' + bs.join(''),\n rrs + ' = Red cards in the red pile',\n bbs + ' = Black cards in the black pile',\n (rrs.length === bbs.length).toString()\n ]);\n };\n\n // THREE STACKS ---------------------------------------\n\n // threeStacks :: [Chars] -> ([Chars], [Chars], [Chars])\n const threeStacks = cards => {\n const go = ([rs, bs, ds]) => xs => {\n const lng = xs.length;\n return 0 < lng ? (\n 1 < lng ? (() => {\n const [x, y] = take(2, xs),\n ds_ = cons(x, ds);\n return (\n 'R' === x ? (\n go([cons(y, rs), bs, ds_])\n ) : go([rs, cons(y, bs), ds_])\n )(drop(2, xs));\n })() : [rs, bs, ds_]\n ) : [rs, bs, ds];\n };\n return go([\n [],\n [],\n []\n ])(cards);\n };\n\n // exchange :: Int -> [a] -> [a] -> ([a], [a])\n const exchange = (n, xs, ys) => {\n const [xs_, ys_] = map(splitAt(n), [xs, ys]);\n return [\n fst(ys_).concat(snd(xs_)),\n fst(xs_).concat(snd(ys_))\n ];\n };\n\n // SHUFFLE --------------------------------------------\n\n // knuthShuffle :: [a] -> [a]\n const knuthShuffle = xs =>\n enumFromTo(0, xs.length - 1)\n .reduceRight((a, i) => {\n const iRand = randomRInt(0, i);\n return i !== iRand ? (\n swapped(i, iRand, a)\n ) : a;\n }, xs);\n\n // swapped :: Int -> Int -> [a] -> [a]\n const swapped = (iFrom, iTo, xs) =>\n xs.map(\n (x, i) => iFrom !== i ? (\n iTo !== i ? (\n x\n ) : xs[iFrom]\n ) : xs[iTo]\n );\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) =>\n Array.isArray(xs) ? (\n [x].concat(xs)\n ) : (x + xs);\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) => xs.slice(n);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // even :: Int -> Bool\n const even = n => 0 === n % 2;\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 // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // min :: Ord a => a -> a -> a\n const min = (a, b) => b < a ? b : a;\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 // splitAt :: Int -> [a] -> ([a],[a])\n const splitAt = n => xs => Tuple(xs.slice(0, n), xs.slice(n));\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, 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 // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} {"title": "Modular inverse", "language": "JavaScript", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "var modInverse = function(a, b) {\n a %= b;\n for (var x = 1; x < b; x++) {\n if ((a*x)%b == 1) {\n return x;\n }\n }\n}"} {"title": "Monads/List monad", "language": "Javascript", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.\n\nThe bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.\n\n\nDemonstrate in your programming language the following:\n\n#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "(function (n) {\n\n // ENCODING A SET COMPREHENSION IN TERMS OF A LIST MONAD\n\n // Pythagorean triples drawn from integers in the range [1..25]\n\n\n // Each range of integers here represents the set of possible values for the variable.\n // Where the test returns true for a particular [x, y, z] triple, we return that triple\n // to the expected data type, wrapping it using the unit or return function;\n\n // Where the test returns false, we return the empty list, which vanishes from the \n // results set under concatenation, giving us a convenient encoding of filtering.\n\n // {(x, y, z) | x <- [1..n], y <- [x+1..n], z <- [y+1..n], (x^2 + y^2 = z^2)} \n\n return bind(rng(1, n), function (x) {\n return bind(rng(1 + x, n), function (y) {\n return bind(rng(1 + y, n), function (z) {\n\n return (x * x + y * y === z * z) ? unit([x, y, z]) : [];\n\n })})});\n\n\n // Monadic return/unit/inject for lists just wraps a value in a list\n // a -> [a]\n function unit(a) {\n return [a];\n }\n\n // Bind for lists is simply ConcatMap\n // which applies a function f directly to each value in the list,\n // and returns the set of results as a concat-flattened list\n // [a] -> (a -> [b]) -> [b]\n function bind(xs, f) {\n return [].concat.apply([], xs.map(f));\n }\n\n\n\n // we will need some ranges of integers, each expressing a range of possible values\n // [m..n]\n function rng(m, n) {\n return Array.apply(null, Array(n - m + 1))\n .map(function (x, i) {\n return m + i;\n });\n }\n\n})(25);"} {"title": "Monads/Maybe monad", "language": "JavaScript", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "(function () {\n 'use strict';\n\n // START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:\n\n // Returns Infinity if n === 0\n function reciprocal(n) {\n return 1 / n;\n }\n\n // Returns NaN if n < 0\n function root(n) {\n return Math.sqrt(n);\n }\n\n // Returns -Infinity if n === 0\n // Returns NaN if n < 0\n function log(n) {\n return Math.log(n);\n }\n\n\n // NOW DERIVE SAFE VERSIONS OF THESE SIMPLE FUNCTIONS:\n // These versions use a validity test, and return a wrapped value\n // with a boolean .isValid property as well as a .value property\n\n function safeVersion(f, fnSafetyCheck) {\n return function (v) {\n return maybe(fnSafetyCheck(v) ? f(v) : undefined);\n }\n }\n\n var safe_reciprocal = safeVersion(reciprocal, function (n) {\n return n !== 0;\n });\n\n var safe_root = safeVersion(root, function (n) {\n return n >= 0;\n });\n\n\n var safe_log = safeVersion(log, function (n) {\n return n > 0;\n });\n\n\n // THE DERIVATION OF THE SAFE VERSIONS USED THE 'UNIT' OR 'RETURN' \n // FUNCTION OF THE MAYBE MONAD\n\n // Named maybe() here, the unit function of the Maybe monad wraps a raw value \n // in a datatype with two elements: .isValid (Bool) and .value (Number)\n\n // a -> Ma\n function maybe(n) {\n return {\n isValid: (typeof n !== 'undefined'),\n value: n\n };\n }\n\n // THE PROBLEM FOR FUNCTION NESTING (COMPOSITION) OF THE SAFE FUNCTIONS\n // IS THAT THEIR INPUT AND OUTPUT TYPES ARE DIFFERENT\n\n // Our safe versions of the functions take simple numeric arguments, but return\n // wrapped results. If we feed a wrapped result as an input to another safe function,\n // it will choke on the unexpected type. The solution is to write a higher order\n // function (sometimes called 'bind' or 'chain') which handles composition, taking a \n // a safe function and a wrapped value as arguments,\n\n // The 'bind' function of the Maybe monad:\n // 1. Applies a 'safe' function directly to the raw unwrapped value, and\n // 2. returns the wrapped result.\n\n // Ma -> (a -> Mb) -> Mb\n function bind(maybeN, mf) {\n return (maybeN.isValid ? mf(maybeN.value) : maybeN);\n }\n\n // Using the bind function, we can nest applications of safe_ functions,\n // without their choking on unexpectedly wrapped values returned from\n // other functions of the same kind.\n var rootOneOverFour = bind(\n bind(maybe(4), safe_reciprocal), safe_root\n ).value;\n\n // -> 0.5\n\n\n // We can compose a chain of safe functions (of any length) with a simple foldr/reduceRight\n // which starts by 'lifting' the numeric argument into a Maybe wrapping,\n // and then nests function applications (working from right to left)\n function safeCompose(lstFunctions, value) {\n return lstFunctions\n .reduceRight(function (a, f) {\n return bind(a, f);\n }, maybe(value));\n }\n\n // TEST INPUT VALUES WITH A SAFELY COMPOSED VERSION OF LOG(SQRT(1/X))\n\n var safe_log_root_reciprocal = function (n) {\n return safeCompose([safe_log, safe_root, safe_reciprocal], n).value;\n }\n\n return [-2, -1, -0.5, 0, 1 / Math.E, 1, 2, Math.E, 3, 4, 5].map(\n safe_log_root_reciprocal\n );\n\n})();"} {"title": "Monads/Writer monad", "language": "JavaScript", "task": "The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "(function () {\n 'use strict';\n\n // START WITH THREE SIMPLE FUNCTIONS\n\n // Square root of a number more than 0\n function root(x) {\n return Math.sqrt(x);\n }\n\n // Add 1\n function addOne(x) {\n return x + 1;\n }\n\n // Divide by 2\n function half(x) {\n return x / 2;\n }\n\n\n // DERIVE LOGGING VERSIONS OF EACH FUNCTION\n\n function loggingVersion(f, strLog) {\n return function (v) {\n return {\n value: f(v),\n log: strLog\n };\n }\n }\n\n var log_root = loggingVersion(root, \"obtained square root\"),\n\n log_addOne = loggingVersion(addOne, \"added 1\"),\n\n log_half = loggingVersion(half, \"divided by 2\");\n\n\n // UNIT/RETURN and BIND for the the WRITER MONAD\n\n // The Unit / Return function for the Writer monad:\n // 'Lifts' a raw value into the wrapped form\n // a -> Writer a\n function writerUnit(a) {\n return {\n value: a,\n log: \"Initial value: \" + JSON.stringify(a)\n };\n }\n\n // The Bind function for the Writer monad:\n // applies a logging version of a function\n // to the contents of a wrapped value\n // and return a wrapped result (with extended log)\n\n // Writer a -> (a -> Writer b) -> Writer b\n function writerBind(w, f) {\n var writerB = f(w.value),\n v = writerB.value;\n\n return {\n value: v,\n log: w.log + '\\n' + writerB.log + ' -> ' + JSON.stringify(v)\n };\n }\n\n // USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS\n\n // We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight\n // which starts by 'lifting' the initial value into a Writer wrapping,\n // and then nests function applications (working from right to left)\n function logCompose(lstFunctions, value) {\n return lstFunctions.reduceRight(\n writerBind,\n writerUnit(value)\n );\n }\n\n var half_of_addOne_of_root = function (v) {\n return logCompose(\n [log_half, log_addOne, log_root], v\n );\n };\n\n return half_of_addOne_of_root(5);\n})();"} {"title": "Move-to-front algorithm", "language": "JavaScript", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "var encodeMTF = function (word) {\n var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};\n\n return word.split('').reduce(function (acc, char) {\n var charNum = acc.charList.indexOf(char); //get index of char\n acc.wordAsNumbers.push(charNum); //add original index to acc\n acc.charList.unshift(acc.charList.splice(charNum, 1)[0]); //put at beginning of list\n return acc;\n }, init).wordAsNumbers; //return number list\n};\n\nvar decodeMTF = function (numList) {\n var init = {word: '', charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};\n\n return numList.reduce(function (acc, num) {\n acc.word += acc.charList[num];\n acc.charList.unshift(acc.charList.splice(num, 1)[0]); //put at beginning of list\n return acc;\n }, init).word;\n};\n\n//test our algorithms\nvar words = ['broood', 'bananaaa', 'hiphophiphop'];\nvar encoded = words.map(encodeMTF);\nvar decoded = encoded.map(decodeMTF);\n\n//print results\nconsole.log(\"from encoded:\");\nconsole.log(encoded);\nconsole.log(\"from decoded:\");\nconsole.log(decoded);"} {"title": "Multifactorial", "language": "JavaScript from C", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "function test (n, deg) {\n for (var i = 1; i <= deg; i ++) {\n var results = '';\n for (var j = 1; j <= n; j ++) {\n results += multifact(j, i) + ' ';\n }\n console.log('Degree ' + i + ': ' + results);\n }\n}"} {"title": "Multiple distinct objects", "language": "JavaScript", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.\n\nBy ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to \"zero\" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of \"zero\" for that type.\n\nThis task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "(n => {\n\n let nObjects = n => Array.from({\n length: n + 1\n }, (_, i) => {\n // optionally indexed object constructor\n return {\n index: i\n };\n });\n\n return nObjects(6);\n\n})(6);"} {"title": "Multisplit", "language": "JavaScript from Haskell", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "(() => {\n\n /// Delimiter list -> String -> list of parts, delimiters, offsets\n\n // multiSplit :: [String] -> String ->\n // [{part::String, delim::String, offset::Int}]\n const multiSplit = (ds, s) => {\n const\n dcs = map(chars, ds),\n xs = chars(s),\n dct = foldl(\n (a, c, i, s) => {\n const\n inDelim = a.offset > i,\n mb = inDelim ? (\n nothing('')\n ) : find(d => isPrefixOf(d, drop(i, xs)), dcs);\n return mb.nothing ? {\n tokens: a.tokens.concat(inDelim ? (\n []\n ) : [c]),\n parts: a.parts,\n offset: a.offset\n } : {\n tokens: [],\n parts: append(a.parts, [{\n part: intercalate('', a.tokens),\n delim: intercalate('', mb.just),\n offset: i\n }]),\n offset: i + length(mb.just)\n };\n }, {\n tokens: [],\n parts: [],\n offset: 0\n }, xs\n );\n return append(dct.parts, [{\n part: intercalate('', dct.tokens),\n delim: \"\",\n offset: length(s)\n }]);\n };\n\n // GENERIC FUNCTIONS -----------------------------------------------------\n\n // append (++) :: [a] -> [a] -> [a]\n const append = (xs, ys) => xs.concat(ys);\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> String -> String\n const drop = (n, xs) => xs.slice(n);\n\n // find :: (a -> Bool) -> [a] -> Maybe a\n const find = (p, xs) => {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n var x = xs[i];\n if (p(x)) return just(x);\n }\n return nothing('Not found');\n };\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // intercalate :: String -> [String] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // isPrefixOf takes two lists or strings and returns\n // true iff the first is a prefix of the second.\n // isPrefixOf :: [a] -> [a] -> Bool\n // isPrefixOf :: String -> String -> Bool\n const isPrefixOf = (xs, ys) => {\n const pfx = (xs, ys) => xs.length ? (\n ys.length ? xs[0] === ys[0] && pfx(\n xs.slice(1), ys.slice(1)\n ) : false\n ) : true;\n return typeof xs !== 'string' ? pfx(xs, ys) : ys.startsWith(xs);\n };\n\n // just :: a -> Just a\n const just = x => ({\n nothing: false,\n just: x\n });\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // nothing :: () -> Nothing\n const nothing = (optionalMsg) => ({\n nothing: true,\n msg: optionalMsg\n });\n\n // show :: Int -> a -> Indented String\n // show :: a -> String\n const show = (...x) =>\n JSON.stringify.apply(\n null, x.length > 1 ? [x[1], null, x[0]] : x\n );\n\n // TEST ------------------------------------------------------------------\n const\n strTest = 'a!===b=!=c',\n delims = ['==', '!=', '='];\n\n return show(2,\n multiSplit(delims, strTest)\n );\n})();"} {"title": "Munchausen numbers", "language": "JavaScript", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "for (let i of [...Array(5000).keys()]\n\t.filter(n => n == n.toString().split('')\n\t.reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0)))\n console.log(i);"} {"title": "Musical scale", "language": "JavaScript", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "\n\n\n\nSample Page\n\n\n\n\n\n"} {"title": "N-queens problem", "language": "Javascript", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "(() => {\n \"use strict\";\n\n // ---------------- N QUEENS PROBLEM -----------------\n\n // queenPuzzle :: Int -> Int -> [[Int]]\n const queenPuzzle = intCols => {\n // All solutions for a given number\n // of columns and rows.\n const go = nRows =>\n nRows <= 0 ? [\n []\n ] : go(nRows - 1).reduce(\n (a, solution) => [\n ...a, ...(\n enumFromTo(0)(intCols - 1)\n .reduce((b, iCol) =>\n safe(\n nRows - 1, iCol, solution\n ) ? (\n [...b, [...solution, iCol]]\n ) : b, [])\n )\n ], []\n );\n\n\n return go;\n };\n\n // safe : Int -> Int -> [Int] -> Bool\n const safe = (iRow, iCol, solution) =>\n !zip(solution)(\n enumFromTo(0)(iRow - 1)\n )\n .some(\n ([sc, sr]) => (iCol === sc) || (\n sc + sr === iCol + iRow\n ) || (sc - sr === iCol - iRow)\n );\n\n // ---------------------- TEST -----------------------\n // Ten columns of solutions to the 7*7 board\n\n // main :: IO ()\n const main = () =>\n // eslint-disable-next-line no-console\n console.log(\n showSolutions(10)(7)\n );\n\n // --------------------- DISPLAY ---------------------\n\n // showSolutions :: Int -> Int -> String\n const showSolutions = nCols =>\n // Display of solutions, in nCols columns\n // for a board of size N * N.\n n => chunksOf(nCols)(\n queenPuzzle(n)(n)\n )\n .map(xs => transpose(\n xs.map(\n rows => rows.map(\n r => enumFromTo(1)(rows.length)\n .flatMap(\n x => r === x ? (\n \"\u265b\"\n ) : \".\"\n )\n .join(\"\")\n )\n )\n )\n .map(cells => cells.join(\" \"))\n )\n .map(x => x.join(\"\\n\"))\n .join(\"\\n\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\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 Boolean(chunk.length) ? [\n chunk, ...go(xs.slice(n))\n ] : [];\n };\n\n return go;\n };\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // transpose_ :: [[a]] -> [[a]]\n const transpose = rows =>\n // The columns of the input transposed\n // into new rows.\n // Simpler version of transpose, assuming input\n // rows of even length.\n Boolean(rows.length) ? rows[0].map(\n (_, i) => rows.flatMap(\n v => v[i]\n )\n ) : [];\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 // MAIN ---\n return main();\n})();"} {"title": "Narcissistic decimal number", "language": "JavaScript from Java", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "function isNarc(x) {\n var str = x.toString(),\n i,\n sum = 0,\n l = str.length;\n if (x < 0) {\n return false;\n } else {\n for (i = 0; i < l; i++) {\n sum += Math.pow(str.charAt(i), l);\n }\n }\n return sum == x;\n}\nfunction main(){\n var n = []; \n for (var x = 0, count = 0; count < 25; x++){\n if (isNarc(x)){\n n.push(x);\n count++;\n }\n }\n return n.join(' '); \n}"} {"title": "Narcissistic decimal number", "language": "JavaScript from Haskell", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n console.log(\n fTable(\n 'Narcissistic decimal numbers of lengths [1..7]:\\n'\n )(show)(show)(\n narcissiOfLength\n )(enumFromTo(1)(7))\n );\n\n // narcissiOfLength :: Int -> [Int]\n const narcissiOfLength = n =>\n 0 < n ? filter(isDaffodil(n))(\n digitPowerSums(n)\n ) : [0];\n\n\n // powerSum :: Int -> [Int] -> Int\n const powerSum = n =>\n xs => xs.reduce(\n (a, x) => a + pow(x, n), 0\n );\n\n\n // isDaffodil :: Int -> Int -> Bool\n const isDaffodil = e => n => {\n // True if the decimal digits of N,\n // each raised to the power E, sum to N.\n const ds = digitList(n);\n return e === ds.length && n === powerSum(e)(ds);\n };\n\n // The subset of integers of n digits that actually need daffodil checking:\n\n // (Flattened leaves of a tree of unique digit combinations, in which\n // order is not significant. Digit sequence doesn't affect power summing)\n\n // digitPowerSums :: Int -> [Int]\n const digitPowerSums = nDigits => {\n const\n digitPowers = map(x => [x, pow(x, nDigits)])(\n enumFromTo(0)(9)\n ),\n treeGrowth = (n, parentPairs) => 0 < n ? (\n treeGrowth(n - 1,\n isNull(parentPairs) ? (\n digitPowers\n ) : concatMap(\n ([parentDigit, parentSum]) =>\n map(([leafDigit, leafSum]) => //\n [leafDigit, parentSum + leafSum])(\n take(parentDigit + 1)(digitPowers)\n )\n )(parentPairs)\n )\n ) : parentPairs;\n return map(snd)(treeGrowth(nDigits, []));\n };\n\n\n // ---------------------GENERIC FUNCTIONS---------------------\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 // concatMap :: (a -> [b]) -> [a] -> [b]\n const concatMap = f =>\n xs => xs.flatMap(f);\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => [x].concat(xs);\n\n // digitList :: Int -> [Int]\n const digitList = n => {\n const go = x => 0 < x ? (\n cons(x % 10)(\n go(Math.floor(x / 10))\n )\n ) : [];\n return 0 < n ? go(n) : [0];\n }\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = f => xs => xs.filter(f);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n xs => xs.map(f);\n\n // isNull :: [a] -> Bool\n // isNull :: String -> Bool\n const isNull = xs =>\n 1 > xs.length;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // pow :: Int -> Int -> Int\n const pow = Math.pow;\n\n // take :: Int -> [a] -> [a]\n const take = n =>\n xs => xs.slice(0, n);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // show :: a -> String\n const show = x => JSON.stringify(x)\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f => xs => ys =>\n xs.slice(\n 0, Math.min(xs.length, ys.length)\n ).map((x, i) => f(x)(ys[i]));\n\n // ------------------------FORMATTING-------------------------\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 // MAIN ---\n return main();\n})();"} {"title": "Nested function", "language": "JavaScript", "task": "In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator \". \" as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.\n\nThe inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.\n\n\n;References:\n:* Nested function\n\n", "solution": "function makeList(separator) {\n var counter = 1;\n\n function makeItem(item) {\n return counter++ + separator + item + \"\\n\";\n }\n\n return makeItem(\"first\") + makeItem(\"second\") + makeItem(\"third\");\n}\n\nconsole.log(makeList(\". \"));"} {"title": "Next highest int from digits", "language": "JavaScript", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* Numbers will not be padded to the left with zeroes.\n* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).\n* If there is no next highest integer return zero.\n\n\n:*1 Alternatively phrased as: \"Find the smallest integer larger than the (positive or zero) integer '''N''' \n:: which can be obtained by reordering the (base ten) digits of '''N'''\".\n\n\n;Algorithm 1:\n# Generate all the permutations of the digits and sort into numeric order.\n# Find the number in the list.\n# Return the next highest number from the list.\n\n\nThe above could prove slow and memory hungry for numbers with large numbers of\ndigits, but should be easy to reason about its correctness.\n\n\n;Algorithm 2:\n# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.\n# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)\n\n\n'''E.g.:'''\n\n n = 12453\n\n 12_4_53\n\n 12_5_43\n\n 12_5_34\n\n return: 12534\n\n\nThis second algorithm is faster and more memory efficient, but implementations\nmay be harder to test. \n\nOne method of testing, (as used in developing the task), is to compare results from both\nalgorithms for random numbers generated from a range that the first algorithm can handle.\n\n\n;Task requirements:\nCalculate the next highest int from the digits of the following numbers:\n:* 0\n:* 9\n:* 12\n:* 21\n:* 12453\n:* 738440\n:* 45072010\n:* 95322020\n\n\n;Optional stretch goal:\n:* 9589776899767587796600\n\n", "solution": "const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);\nconst toString = x => x + '';\nconst reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);\nconst minBiggerThanN = (arr, n) => arr.filter(e => e > n).sort()[0];\nconst remEl = (arr, e) => {\n const r = arr.indexOf(e);\n return arr.filter((e,i) => i !== r);\n}\n\nconst nextHighest = itr => {\n const seen = [];\n let result = 0;\n for (const [i,v] of itr.entries()) {\n const n = +v;\n if (Math.max(n, ...seen) !== n) {\n const right = itr.slice(i + 1);\n const swap = minBiggerThanN(seen, n);\n const rem = remEl(seen, swap);\n const rest = [n, ...rem].sort();\n result = [...reverse(right), swap, ...rest].join('');\n break;\n } else {\n seen.push(n);\n }\n }\n return result;\n};\n\nconst check = compose(nextHighest, reverse, toString);\n\nconst test = v => {\n console.log(v, '=>', check(v));\n}\n\ntest(0);\ntest(9);\ntest(12);\ntest(21);\ntest(12453);\ntest(738440);\ntest(45072010);\ntest(95322020);\ntest('9589776899767587796600');\n"} {"title": "Nim game", "language": "Javascript", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "class Nim {\n\tconstructor(tokens, printFun) {\n\t\tthis.startTokens = tokens;\n\t\tthis.tokens = tokens;\n\t\tthis.printFun = printFun;\n\t}\n\n\tplayerTurn(take) {\n\t\ttake = Math.round(take);\n\n\t\tif (take < 1 || take > 3) {\n\t\t\tthis.printFun(\"take must be between 1 and 3.\\n\")\n\t\t\treturn false;\n\t\t}\n\t\tthis.tokens -= take;\n\t\tthis.printFun(\"Player takes \" + take + \" tokens.\");\n\t\tthis.printRemaining()\n\n\t\tif (this.tokens === 0) {\n\t\t\tthis.printFun(\"Player wins!\\n\");\n\t\t}\n\t\treturn true;\n\t}\n\n\tcomputerTurn() {\n\t\tlet take = this.tokens % 4;\n\t\tthis.tokens -= take;\n\t\tthis.printFun(\"Computer takes \" + take + \" tokens.\");\n\t\tthis.printRemaining();\n\n\t\tif (this.tokens === 0) {\n\t\t\tthis.printFun(\"Computer wins.\\n\");\n\t\t}\n\n\t}\n\n\tprintRemaining() {\n\t\tthis.printFun(this.tokens + \" tokens remaining.\\n\");\n\t}\n}\n\n\nlet game = new Nim(12, console.log);\nwhile (true) {\n\tif (game.playerTurn(parseInt(prompt(\"How many tokens would you like to take?\")))){\n\t\tgame.computerTurn();\n\t}\n\tif (game.tokens == 0) {\n\t\tbreak;\n\t}\n}\n"} {"title": "Nonoblock", "language": "JavaScript", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).\n* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.\n* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);\nconst inv = b => !b;\nconst arrJoin = str => arr => arr.join(str);\nconst mkArr = (l, f) => Array(l).fill(f);\nconst sumArr = arr => arr.reduce((a, b) => a + b, 0);\nconst sumsTo = val => arr => sumArr(arr) === val;\nconst zipper = arr => (p, c, i) => arr[i] ? [...p, c, arr[i]] : [...p, c];\nconst zip = (a, b) => a.reduce(zipper(b), []);\nconst zipArr = arr => a => zip(a, arr);\nconst hasInner = v => arr => arr.slice(1, -1).indexOf(v) >= 0;\nconst choose = (even, odd) => n => n % 2 === 0 ? even : odd;\nconst toBin = f => arr => arr.reduce(\n (p, c, i) => [...p, ...mkArr(c, f(i))], []);\n\n\nconst looper = (arr, max, acc = [[...arr]], idx = 0) => {\n if (idx !== arr.length) {\n const b = looper([...arr], max, acc, idx + 1)[0];\n if (b[idx] !== max) {\n b[idx] = b[idx] + 1;\n acc.push(looper([...b], max, acc, idx)[0]);\n }\n }\n return [arr, acc];\n};\n\nconst gapPerms = (grpSize, numGaps, minVal = 0) => {\n const maxVal = numGaps - grpSize * minVal + minVal;\n return maxVal <= 0\n ? (grpSize === 2 ? [[0]] : [])\n : looper(mkArr(grpSize, minVal), maxVal)[1];\n}\n\nconst test = (cells, ...blocks) => {\n const grpSize = blocks.length + 1;\n const numGaps = cells - sumArr(blocks);\n\n // Filter functions\n const sumsToTrg = sumsTo(numGaps);\n const noInnerZero = compose(inv, hasInner(0));\n\n // Output formatting\n const combine = zipArr([...blocks]);\n const choices = toBin(choose(0, 1));\n const output = compose(console.log, arrJoin(''), choices, combine);\n\n console.log(`\\n${cells} cells. Blocks: ${blocks}`);\n gapPerms(grpSize, numGaps)\n .filter(noInnerZero)\n .filter(sumsToTrg)\n .map(output);\n};\n\ntest(5, 2, 1);\ntest(5);\ntest(5, 5);\ntest(5, 1, 1, 1);\ntest(10, 8);\ntest(15, 2, 3, 2, 3);\ntest(10, 4, 3);\ntest(5, 2, 3);\n"} {"title": "OpenWebNet password", "language": "JavaScript", "task": "Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist\n\n'''Note:''' Factory default password is '12345'. Changing it is highly recommended !\n\nconversation goes as follows\n\n- *#*1##\n- *99*0##\n- *#603356072##\n\nat which point a password should be sent back, calculated from the \"password open\" that is set in the gateway, and the nonce that was just sent\n\n- *#25280520##\n- *#*1##\n", "solution": "function calcPass (pass, nonce) {\n\tvar flag = true;\n\tvar num1 = 0x0;\n\tvar num2 = 0x0;\n\tvar password = parseInt(pass, 10);\n\t\n\tfor (var c in nonce) {\n\t\tc = nonce[c];\n\t\tif (c!='0') {\n\t\t\tif (flag) num2 = password;\n\t\t\tflag = false;\n\t\t}\n\t\tswitch (c) {\n\t\t\tcase '1':\n\t\t\t\tnum1 = num2 & 0xFFFFFF80;\n\t\t\t\tnum1 = num1 >>> 7;\n\t\t\t\tnum2 = num2 << 25;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '2':\n\t\t\t\tnum1 = num2 & 0xFFFFFFF0;\n\t\t\t\tnum1 = num1 >>> 4;\n\t\t\t\tnum2 = num2 << 28;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '3':\n\t\t\t\tnum1 = num2 & 0xFFFFFFF8;\n\t\t\t\tnum1 = num1 >>> 3;\n\t\t\t\tnum2 = num2 << 29;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '4':\n\t\t\t\tnum1 = num2 << 1;\n\t\t\t\tnum2 = num2 >>> 31;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '5':\n\t\t\t\tnum1 = num2 << 5;\n\t\t\t\tnum2 = num2 >>> 27;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '6':\n\t\t\t\tnum1 = num2 << 12;\n\t\t\t\tnum2 = num2 >>> 20;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '7':\n\t\t\t\tnum1 = num2 & 0x0000FF00;\n\t\t\t\tnum1 = num1 + (( num2 & 0x000000FF ) << 24 );\n\t\t\t\tnum1 = num1 + (( num2 & 0x00FF0000 ) >>> 16 );\n\t\t\t\tnum2 = ( num2 & 0xFF000000 ) >>> 8;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '8':\n\t\t\t\tnum1 = num2 & 0x0000FFFF;\n\t\t\t\tnum1 = num1 << 16;\n\t\t\t\tnum1 = num1 + ( num2 >>> 24 );\n\t\t\t\tnum2 = num2 & 0x00FF0000;\n\t\t\t\tnum2 = num2 >>> 8;\n\t\t\t\tnum1 = num1 + num2;\n\t\t\t\tbreak;\n\t\t\tcase '9':\n\t\t\t\tnum1 = ~num2;\n\t\t\t\tbreak;\n\t\t\tcase '0':\n\t\t\t\tnum1 = num2;\n\t\t\t\tbreak;\n\t\t}\n\t\tnum2 = num1;\n\t}\n\treturn (num1 >>> 0).toString();\n}\n\nexports.calcPass = calcPass;\n\nconsole.log ('openpass initialization');\nfunction testCalcPass (pass, nonce, expected) {\n\tvar res = calcPass (pass, nonce);\n\tvar m = pass + ' ' + nonce + ' ' + res + ' ' + expected;\n\tif (res == parseInt(expected, 10))\n\t\tconsole.log ('PASS '+m);\n\telse\n\t\tconsole.log ('FAIL '+m);\n}\n\ntestCalcPass ('12345', '603356072', '25280520');\ntestCalcPass ('12345', '410501656', '119537670');\ntestCalcPass ('12345', '630292165', '4269684735');\ntestCalcPass ('12345', '523781130', '537331200');\n"} {"title": "Operator precedence", "language": "JavaScript", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "Mozilla Developer Network have a nice list of this at [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence JavaScript Reference:Expressions and operators:Operator Precedence]\n\n"} {"title": "Padovan n-step number sequences", "language": "JavaScript", "task": "As the [[Fibonacci sequence]] expands to the [[Fibonacci n-step number sequences]]; We similarly expand the [[Padovan sequence]] to form these Padovan n-step number sequences.\n\nThe Fibonacci-like sequences can be defined like this:\n\n For n == 2:\n start: 1, 1\n Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2\n For n == N:\n start: First N terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))\n\nFor this task we similarly define terms of the first 2..n-step Padovan sequences as:\n\n For n == 2:\n start: 1, 1, 1\n Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2\n For n == N:\n start: First N + 1 terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))\n\nThe initial values of the sequences are:\n:: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Padovan n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Values !! OEIS Entry\n|-\n| 2 || 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... || A134816: 'Padovan's spiral numbers'\n|-\n| 3 || 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... || A000930: 'Narayana's cows sequence'\n|-\n| 4 || 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... || A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'\n|-\n| 5 || 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... || A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'\n|-\n| 6 || 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... || \n|-\n| 7 || 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... || A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'\n|-\n| 8 || 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... || \n|-\n|}\n\n\n;Task:\n# Write a function to generate the first t terms, of the first 2..max_n Padovan n-step number sequences as defined above.\n# Use this to print and show here at least the first t=15 values of the first 2..8 n-step sequences. (The OEIS column in the table above should be omitted).\n\n", "solution": "(() => {\n \"use strict\";\n\n // ---------- PADOVAN N-STEP NUMBER SERIES -----------\n\n // padovans :: Int -> [Int]\n const padovans = n => {\n // Padovan number series of step N\n const recurrence = ns => [\n ns[0],\n ns.slice(1).concat(\n sum(take(n)(ns))\n )\n ];\n\n\n return 0 > n ? (\n []\n ) : unfoldr(recurrence)(\n take(1 + n)(\n 3 > n ? (\n repeat(1)\n ) : padovans(n - 1)\n )\n );\n };\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n fTable(\"Padovan N-step series:\")(str)(\n xs => xs.map(\n compose(justifyRight(4)(\" \"), str)\n )\n .join(\"\")\n )(\n compose(take(15), padovans)\n )(\n enumFromTo(2)(8)\n );\n\n\n // --------------------- GENERIC ---------------------\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // repeat :: a -> Generator [a]\n const repeat = function* (x) {\n while (true) {\n yield x;\n }\n };\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]\n const unfoldr = f =>\n // A lazy (generator) list unfolded from a seed value\n // by repeated application of f to a value until no\n // residue remains. Dual to fold/reduce.\n // f returns either Nothing or Just (value, residue).\n // For a strict output list,\n // wrap with `list` or Array.from\n x => (\n function* () {\n let valueResidue = f(x);\n\n while (null !== valueResidue) {\n yield valueResidue[0];\n valueResidue = f(valueResidue[1]);\n }\n }()\n );\n\n // ------------------- FORMATTING --------------------\n\n // fTable :: String -> (a -> String) ->\n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = s =>\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n xShow => fxShow => f => xs => {\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(y => [...y].length)),\n table = zipWith(\n a => b => `${a.padStart(w, \" \")} ->${b}`\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join(\"\\n\");\n\n return `${s}\\n${table}`;\n };\n\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n\n // str :: a -> String\n const str = x => `${x}`;\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => take(\n Math.min(xs.length, ys.length)\n )(\n xs.map((x, i) => f(x)(ys[i]))\n );\n\n // MAIN ---\n return main();\n})();"} {"title": "Padovan sequence", "language": "JavaScript", "task": "The Fibonacci sequence in several ways.\nSome are given in the table below, and the referenced video shows some of the geometric\nsimilarities.\n\n::{| class=\"wikitable\"\n! Comment !! Padovan !! Fibonacci\n|-\n| || || \n|-\n| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci\n|-\n| || || \n|-\n| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1\n|-\n| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)\n|-\n| || || \n|-\n| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34\n|-\n| || || \n|-\n| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g\n|-\n| || 1.324717957244746025960908854... || 1.6180339887498948482...\n|-\n| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2\n|-\n| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1\n|-\n| || || \n|-\n| Spirally tiling the plane using. || Equilateral triangles || Squares\n|-\n| || || \n|-\n| Constants for ... || s= 1.0453567932525329623 || a=5**0.5\n|-\n| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)\n|-\n| || || \n|-\n| L-System Variables. || A,B,C || A,B\n|-\n| L-System Start/Axiom. || A || A\n|-\n| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB\n|}\n\n;Task:\n* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.\n* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.\n* Show the first twenty terms of the sequence.\n* Confirm that the recurrence and floor based functions give the same results for 64 terms,\n* Write a function/method/... using the L-system to generate successive strings.\n* Show the first 10 strings produced from the L-system\n* Confirm that the length of the first 32 strings produced is the Padovan sequence.\n\nShow output here, on this page.\n\n;Ref:\n* The Plastic Ratio - Numberphile video.\n\n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------------- PADOVAN NUMBERS -----------------\n\n // padovans :: [Int]\n const padovans = () => {\n // Non-finite series of Padovan numbers,\n // defined in terms of recurrence relations.\n const f = ([a, b, c]) => [\n a,\n [b, c, a + b]\n ];\n\n return unfoldr(f)([1, 1, 1]);\n };\n\n\n // padovanFloor :: [Int]\n const padovanFloor = () => {\n // The Padovan series, defined in terms\n // of a floor function.\n const\n // NB JavaScript loses some of this\n // precision at run-time.\n p = 1.324717957244746025960908854,\n s = 1.0453567932525329623;\n\n const f = n => [\n Math.floor(((p ** (n - 1)) / s) + 0.5),\n 1 + n\n ];\n\n return unfoldr(f)(0);\n };\n\n\n // padovanLSystem : [Int]\n const padovanLSystem = () => {\n // An L-system generating terms whose lengths\n // are the values of the Padovan integer series.\n const rule = c =>\n \"A\" === c ? (\n \"B\"\n ) : \"B\" === c ? (\n \"C\"\n ) : \"AB\";\n\n const f = s => [\n s,\n chars(s).flatMap(rule)\n .join(\"\")\n ];\n\n return unfoldr(f)(\"A\");\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => {\n // prefixesMatch :: [a] -> [a] -> Bool\n const prefixesMatch = xs =>\n ys => n => and(\n zipWith(a => b => a === b)(\n take(n)(xs)\n )(\n take(n)(ys)\n )\n );\n\n return [\n \"First 20 padovans:\",\n take(20)(padovans()),\n\n \"\\nThe recurrence and floor-based functions\",\n \"match over the first 64 terms:\\n\",\n prefixesMatch(\n padovans()\n )(\n padovanFloor()\n )(64),\n\n \"\\nFirst 10 L-System strings:\",\n take(10)(padovanLSystem()),\n\n \"\\nThe lengths of the first 32 L-System\",\n \"strings match the Padovan sequence:\\n\",\n prefixesMatch(\n padovans()\n )(\n fmap(length)(padovanLSystem())\n )(32)\n ]\n .map(str)\n .join(\"\\n\");\n };\n\n // --------------------- GENERIC ---------------------\n\n // and :: [Bool] -> Bool\n const and = xs =>\n // True unless any value in xs is false.\n [...xs].every(Boolean);\n\n\n // chars :: String -> [Char]\n const chars = s =>\n s.split(\"\");\n\n\n // fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmap = f =>\n function* (gen) {\n let v = take(1)(gen);\n\n while (0 < v.length) {\n yield f(v[0]);\n v = take(1)(gen);\n }\n };\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat(...Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }));\n\n\n // str :: a -> String\n const str = x =>\n \"string\" !== typeof x ? (\n JSON.stringify(x)\n ) : x;\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]\n const unfoldr = f =>\n // A lazy (generator) list unfolded from a seed value\n // by repeated application of f to a value until no\n // residue remains. Dual to fold/reduce.\n // f returns either Null or just (value, residue).\n // For a strict output list,\n // wrap with `list` or Array.from\n x => (\n function* () {\n let valueResidue = f(x);\n\n while (null !== valueResidue) {\n yield valueResidue[0];\n valueResidue = f(valueResidue[1]);\n }\n }()\n );\n\n\n // zipWithList :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => ((xs_, ys_) => {\n const lng = Math.min(length(xs_), length(ys_));\n\n return take(lng)(xs_).map(\n (x, i) => f(x)(ys_[i])\n );\n })([...xs], [...ys]);\n\n // MAIN ---\n return main();\n})();"} {"title": "Palindrome dates", "language": "Javascript", "task": "Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format.\n\n\n;Task\nWrite a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.\n\n", "solution": "/**\n * Adds zeros for 1 digit days/months\n * @param date: string\n */\nconst addMissingZeros = date => (/^\\d$/.test(date) ? `0${date}` : date);\n\n/**\n * Formats a Date to a string. If readable is false,\n * string is only numbers (used for comparison), else\n * is a human readable date.\n * @param date: Date\n * @param readable: boolean\n */\nconst formatter = (date, readable) => {\n const year = date.getFullYear();\n const month = addMissingZeros(date.getMonth() + 1);\n const day = addMissingZeros(date.getDate());\n\n return readable ? `${year}-${month}-${day}` : `${year}${month}${day}`;\n};\n\n/**\n * Returns n (palindromesToShow) palindrome dates\n * since start (or 2020-02-02)\n * @param start: Date\n * @param palindromesToShow: number\n */\nfunction getPalindromeDates(start, palindromesToShow = 15) {\n let date = start || new Date(2020, 3, 2);\n\n for (\n let i = 0;\n i < palindromesToShow;\n date = new Date(date.setDate(date.getDate() + 1))\n ) {\n const formattedDate = formatter(date);\n if (formattedDate === formattedDate.split(\"\").reverse().join(\"\")) {\n i++;\n console.log(formatter(date, true));\n }\n }\n}\n\ngetPalindromeDates();"} {"title": "Pangram checker", "language": "JavaScript", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------------- PANGRAM CHECKER -----------------\n\n // isPangram :: String -> Bool\n const isPangram = s =>\n 0 === \"abcdefghijklmnopqrstuvwxyz\"\n .split(\"\")\n .filter(c => -1 === s.toLowerCase().indexOf(c))\n .length;\n\n // ---------------------- TEST -----------------------\n return [\n \"is this a pangram\",\n \"The quick brown fox jumps over the lazy dog\"\n ].map(isPangram);\n})();"} {"title": "Parsing/RPN calculator algorithm", "language": "JavaScript", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +';\nconst s = [], tokens = e.split(' ');\nfor (const t of tokens) {\n const n = Number(t);\n if (!isNaN(n)) {\n s.push(n);\n } else {\n if (s.length < 2) {\n throw new Error(`${t}: ${s}: insufficient operands.`);\n }\n const o2 = s.pop(), o1 = s.pop();\n switch (t) {\n case '+': s.push(o1 + o2); break;\n case '-': s.push(o1 - o2); break;\n case '*': s.push(o1 * o2); break;\n case '/': s.push(o1 / o2); break;\n case '^': s.push(Math.pow(o1, o2)); break;\n default: throw new Error(`Unrecognized operator: [${t}]`);\n }\n }\n console.log(`${t}: ${s}`);\n}\n\nif (s.length > 1) {\n throw new Error(`${s}: insufficient operators.`);\n}\n"} {"title": "Parsing/RPN to infix conversion", "language": "JavaScript", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "const Associativity = {\n /** a / b / c = (a / b) / c */\n left: 0,\n /** a ^ b ^ c = a ^ (b ^ c) */\n right: 1,\n /** a + b + c = (a + b) + c = a + (b + c) */\n both: 2,\n};\nconst operators = {\n '+': { precedence: 2, associativity: Associativity.both },\n '-': { precedence: 2, associativity: Associativity.left },\n '*': { precedence: 3, associativity: Associativity.both },\n '/': { precedence: 3, associativity: Associativity.left },\n '^': { precedence: 4, associativity: Associativity.right },\n};\nclass NumberNode {\n constructor(text) { this.text = text; }\n toString() { return this.text; }\n}\nclass InfixNode {\n constructor(fnname, operands) {\n this.fnname = fnname;\n this.operands = operands;\n }\n toString(parentPrecedence = 0) {\n const op = operators[this.fnname];\n const leftAdd = op.associativity === Associativity.right ? 0.01 : 0;\n const rightAdd = op.associativity === Associativity.left ? 0.01 : 0;\n if (this.operands.length !== 2) throw Error(\"invalid operand count\");\n const result = this.operands[0].toString(op.precedence + leftAdd)\n +` ${this.fnname} ${this.operands[1].toString(op.precedence + rightAdd)}`;\n if (parentPrecedence > op.precedence) return `( ${result} )`;\n else return result;\n }\n}\nfunction rpnToTree(tokens) {\n const stack = [];\n console.log(`input = ${tokens}`);\n for (const token of tokens.split(\" \")) {\n if (token in operators) {\n const op = operators[token], arity = 2; // all of these operators take 2 arguments\n if (stack.length < arity) throw Error(\"stack error\");\n stack.push(new InfixNode(token, stack.splice(stack.length - arity)));\n }\n else stack.push(new NumberNode(token));\n console.log(`read ${token}, stack = [${stack.join(\", \")}]`);\n }\n if (stack.length !== 1) throw Error(\"stack error \" + stack);\n return stack[0];\n}\nconst tests = [\n [\"3 4 2 * 1 5 - 2 3 ^ ^ / +\", \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"],\n [\"1 2 + 3 4 + ^ 5 6 + ^\", \"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\"],\n [\"1 2 3 + +\", \"1 + 2 + 3\"] // test associativity (1+(2+3)) == (1+2+3)\n];\nfor (const [inp, oup] of tests) {\n const realOup = rpnToTree(inp).toString();\n console.log(realOup === oup ? \"Correct!\" : \"Incorrect!\");\n}"} {"title": "Parsing/Shunting-yard algorithm", "language": "JavaScript", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "function Stack() {\n this.dataStore = [];\n this.top = 0;\n this.push = push;\n this.pop = pop;\n this.peek = peek;\n this.length = length;\n}\n \nfunction push(element) {\n this.dataStore[this.top++] = element;\n}\n \nfunction pop() {\n return this.dataStore[--this.top];\n}\n \nfunction peek() {\n return this.dataStore[this.top-1];\n}\n \nfunction length() {\n return this.top;\n}\n \nvar infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\ninfix = infix.replace(/\\s+/g, ''); // remove spaces, so infix[i]!=\" \"\n\nvar s = new Stack();\nvar ops = \"-+/*^\";\nvar precedence = {\"^\":4, \"*\":3, \"/\":3, \"+\":2, \"-\":2};\nvar associativity = {\"^\":\"Right\", \"*\":\"Left\", \"/\":\"Left\", \"+\":\"Left\", \"-\":\"Left\"};\nvar token;\nvar postfix = \"\";\nvar o1, o2;\n\nfor (var i = 0; i < infix.length; i++) {\n token = infix[i];\n if (token >= \"0\" && token <= \"9\") { // if token is operand (here limited to 0 <= x <= 9)\n postfix += token + \" \";\n }\n else if (ops.indexOf(token) != -1) { // if token is an operator\n o1 = token;\n o2 = s.peek();\n while (ops.indexOf(o2)!=-1 && ( // while operator token, o2, on top of the stack\n // and o1 is left-associative and its precedence is less than or equal to that of o2\n (associativity[o1] == \"Left\" && (precedence[o1] <= precedence[o2]) ) || \n // the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be\n // or o1 is right-associative and its precedence is less than that of o2\n (associativity[o1] == \"Right\" && (precedence[o1] < precedence[o2])) \n )){\n postfix += o2 + \" \"; // add o2 to output queue\n s.pop(); // pop o2 of the stack\n o2 = s.peek(); // next round\n }\n s.push(o1); // push o1 onto the stack\n }\n else if (token == \"(\") { // if token is left parenthesis\n s.push(token); // then push it onto the stack\n }\n else if (token == \")\") { // if token is right parenthesis \n while (s.peek() != \"(\"){ // until token at top is (\n postfix += s.pop() + \" \";\n }\n s.pop(); // pop (, but not onto the output queue\n }\n}\npostfix += s.dataStore.reverse().join(\" \");\nprint(postfix);"} {"title": "Pascal matrix generation", "language": "JavaScript", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "In terms of a binomial coefficient, and a function on a coordinate pair.\n"} {"title": "Pascal matrix generation", "language": "JavaScript from Haskell", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "(() => {\n 'use strict';\n\n // -------------------PASCAL MATRIX--------------------\n\n // pascalMatrix :: ((Int, Int) -> (Int, Int)) ->\n // Int -> [Int]\n const pascalMatrix = f =>\n n => map(compose(binomialCoefficient, f))(\n range([0, 0], [n - 1, n - 1])\n );\n\n // binomialCoefficient :: (Int, Int) -> Int\n const binomialCoefficient = nk => {\n const [n, k] = Array.from(nk);\n return enumFromThenTo(k)(\n pred(k)\n )(1).reduceRight((a, x) => quot(\n a * succ(n - x)\n )(x), 1);\n };\n\n // ------------------------TEST------------------------\n // main :: IO ()\n const main = () => {\n const matrixSize = 5;\n console.log(intercalate('\\n\\n')(\n zipWith(\n k => xs => k + ':\\n' + showMatrix(matrixSize)(xs)\n )(['Lower', 'Upper', 'Symmetric'])(\n apList(\n map(pascalMatrix)([\n identity, // Lower\n swap, // Upper\n ([a, b]) => [a + b, b] // Symmetric\n ])\n )([matrixSize])\n )\n ));\n };\n\n // ----------------------DISPLAY-----------------------\n\n // showMatrix :: Int -> [Int] -> String\n const showMatrix = n =>\n xs => {\n const\n ks = map(str)(xs),\n w = maximum(map(length)(ks));\n return unlines(\n map(unwords)(chunksOf(n)(\n map(justifyRight(w)(' '))(ks)\n ))\n );\n };\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // apList (<*>) :: [(a -> b)] -> [a] -> [b]\n const apList = fs =>\n // The sequential application of each of a list\n // of functions to each of a list of values.\n xs => fs.flatMap(\n f => xs.map(f)\n );\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n =>\n xs => enumFromThenTo(0)(n)(\n xs.length - 1\n ).reduce(\n (a, i) => a.concat([xs.slice(i, (n + i))]),\n []\n );\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n x => fs.reduceRight((a, f) => f(a), x);\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (\n xs.every(x => 'string' === typeof x) ? (\n ''\n ) : []\n ).concat(...xs) : xs;\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => [x].concat(xs);\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = x1 =>\n x2 => y => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // fst :: (a, b) -> a\n const fst = tpl =>\n // First member of a pair.\n tpl[0];\n\n // identity :: a -> a\n const identity = x =>\n // The identity function. (`id`, in Haskell)\n x;\n\n // intercalate :: String -> [String] -> String\n const intercalate = s =>\n // The concatenation of xs\n // interspersed with copies of s.\n xs => xs.join(s);\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padStart(n, c)\n ) : s;\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n\n // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]\n const liftA2List = f => xs => ys =>\n // The binary operator f lifted to a function over two\n // lists. f applied to each pair of arguments in the\n // cartesian product of xs and ys.\n xs.flatMap(\n x => ys.map(f(x))\n );\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f to each element of xs.\n // (The image of xs under f).\n xs => (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n // The largest value in a non-empty list.\n 0 < xs.length ? (\n xs.slice(1).reduce(\n (a, x) => x > a ? (\n x\n ) : a, xs[0]\n )\n ) : undefined;\n\n // pred :: Enum a => a -> a\n const pred = x =>\n x - 1;\n\n // quot :: Int -> Int -> Int\n const quot = n => m => Math.floor(n / m);\n\n // The list of values in the subrange defined by a bounding pair.\n\n // range([0, 2]) -> [0,1,2]\n // range([[0,0], [2,2]])\n // -> [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]\n // range([[0,0,0],[1,1,1]])\n // -> [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]\n\n // range :: Ix a => (a, a) -> [a]\n function range() {\n const\n args = Array.from(arguments),\n ab = 1 !== args.length ? (\n args\n ) : args[0],\n [as, bs] = [ab[0], ab[1]].map(\n x => Array.isArray(x) ? (\n x\n ) : (undefined !== x.type) &&\n (x.type.startsWith('Tuple')) ? (\n Array.from(x)\n ) : [x]\n ),\n an = as.length;\n return (an === bs.length) ? (\n 1 < an ? (\n traverseList(x => x)(\n as.map((_, i) => enumFromTo(as[i])(bs[i]))\n )\n ) : enumFromTo(as[0])(bs[0])\n ) : [];\n };\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // str :: a -> String\n const str = x => x.toString();\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // swap :: (a, b) -> (b, a)\n const swap = ab =>\n // The pair ab with its order reversed.\n Tuple(ab[1])(\n ab[0]\n );\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => xs.slice(0, n);\n\n // traverseList :: (Applicative f) => (a -> f b) -> [a] -> f [b]\n const traverseList = f =>\n // Collected results of mapping each element\n // of a structure to an action, and evaluating\n // these actions from left to right.\n xs => 0 < xs.length ? (() => {\n const\n vLast = f(xs.slice(-1)[0]),\n t = vLast.type || 'List';\n return xs.slice(0, -1).reduceRight(\n (ys, x) => liftA2List(cons)(f(x))(ys),\n liftA2List(cons)(vLast)([\n []\n ])\n );\n })() : [\n []\n ];\n\n // unlines :: [String] -> String\n const unlines = xs =>\n // A single string formed by the intercalation\n // of a list of strings with the newline character.\n xs.join('\\n');\n\n // unwords :: [String] -> String\n const unwords = xs =>\n // A space-separated string derived\n // from a list of words.\n xs.join(' ');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => {\n const\n lng = Math.min(length(xs), length(ys)),\n vs = take(lng)(ys);\n return take(lng)(xs)\n .map((x, i) => f(x)(vs[i]));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Password generator", "language": "JavaScript", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "String.prototype.shuffle = function() {\n return this.split('').sort(() => Math.random() - .5).join('');\n}\n\nfunction createPwd(opts = {}) {\n let len = opts.len || 5, // password length\n num = opts.num || 1, // number of outputs\n noSims = opts.noSims == false ? false : true, // exclude similar?\n out = [],\n cur, i;\n\n let chars = [\n 'abcdefghijkmnopqrstuvwxyz'.split(''),\n 'ABCDEFGHJKLMNPQRTUVWXY'.split(''),\n '346789'.split(''),\n '!\"#$%&()*+,-./:;<=>?@[]^_{|}'.split('')\n ];\n\n if (!noSims) {\n chars[0].push('l');\n chars[1] = chars[1].concat('IOSZ'.split(''));\n chars[2] = chars[2].concat('1250'.split(''));\n }\n\n if (len < 4) {\n console.log('Password length changed to 4 (minimum)');\n len = 4;\n }\n\n while (out.length < num) {\n cur = '';\n // basic requirement\n for (i = 0; i < 4; i++)\n cur += chars[i][Math.floor(Math.random() * chars[i].length)];\n\n while (cur.length < len) {\n let rnd = Math.floor(Math.random() * chars.length);\n cur += chars[rnd][Math.floor(Math.random() * chars[rnd].length)];\n }\n out.push(cur);\n }\n\n for (i = 0; i < out.length; i++) out[i] = out[i].shuffle();\n\n if (out.length == 1) return out[0];\n return out;\n}\n\n// testing\nconsole.log( createPwd() );\nconsole.log( createPwd( {len: 20}) );\nconsole.log( createPwd( {len: 20, num: 2}) );\nconsole.log( createPwd( {len: 20, num: 2, noSims: false}) );\n"} {"title": "Perfect shuffle", "language": "JavaScript", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "(() => {\n 'use strict';\n\n // shuffleCycleLength :: Int -> Int\n const shuffleCycleLength = deckSize =>\n firstCycle(shuffle, range(1, deckSize))\n .all.length;\n\n // shuffle :: [a] -> [a]\n const shuffle = xs =>\n concat(zip.apply(null, splitAt(div(length(xs), 2), xs)));\n\n // firstycle :: Eq a => (a -> a) -> a -> [a]\n const firstCycle = (f, x) =>\n until(\n m => EqArray(x, m.current),\n m => {\n const fx = f(m.current);\n return {\n current: fx,\n all: m.all.concat([fx])\n };\n }, {\n current: f(x),\n all: [x]\n }\n );\n\n // Two arrays equal ?\n // EqArray :: [a] -> [b] -> Bool\n const EqArray = (xs, ys) => {\n const [nx, ny] = [xs.length, ys.length];\n return nx === ny ? (\n nx > 0 ? (\n xs[0] === ys[0] && EqArray(xs.slice(1), ys.slice(1))\n ) : true\n ) : false;\n };\n\n // GENERIC FUNCTIONS\n\n // zip :: [a] -> [b] -> [(a,b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => [x, ys[i]]);\n\n // concat :: [[a]] -> [a]\n const concat = xs => [].concat.apply([], xs);\n\n // splitAt :: Int -> [a] -> ([a],[a])\n const splitAt = (n, xs) => [xs.slice(0, n), xs.slice(n)];\n\n // div :: Num -> Num -> Int\n const div = (x, y) => Math.floor(x / y);\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n const go = x => p(x) ? x : go(f(x));\n return go(x);\n }\n\n // range :: Int -> Int -> [Int]\n const range = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // length :: [a] -> Int\n // length :: Text -> Int\n const length = xs => xs.length;\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) > 0 ? x : a\n ), undefined);\n\n // transpose :: [[a]] -> [[a]]\n const transpose = xs =>\n xs[0].map((_, iCol) => xs.map((row) => row[iCol]));\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // replicateS :: Int -> String -> String\n const replicateS = (n, s) => {\n let v = s,\n o = '';\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (replicateS(n, cFiller) + strText)\n .slice(-n)\n ) : strText;\n\n // TEST\n return transpose(transpose([\n ['Deck', 'Shuffles']\n ].concat(\n [8, 24, 52, 100, 1020, 1024, 10000]\n .map(n => [n.toString(), shuffleCycleLength(n)\n .toString()\n ])))\n .map(col => { // Right-justified number columns\n const width = length(\n maximumBy((a, b) => length(a) - length(b), col)\n ) + 2;\n\n return col.map(x => justifyRight(width, ' ', x));\n }))\n .map(row => row.join(''))\n .join('\\n');\n})();"} {"title": "Perfect totient numbers", "language": "JavaScript", "task": "Generate and show here, the first twenty Perfect totient numbers.\n\n\n;Related task:\n::* [[Totient function]]\n\n\n;Also see:\n::* the OEIS entry for perfect totient numbers.\n::* mrob list of the first 54\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n showLog(\n take(20, perfectTotients())\n );\n\n // perfectTotients :: Generator [Int]\n function* perfectTotients() {\n const\n phi = memoized(\n n => length(\n filter(\n k => 1 === gcd(n, k),\n enumFromTo(1, n)\n )\n )\n ),\n imperfect = n => n !== sum(\n tail(iterateUntil(\n x => 1 === x,\n phi,\n n\n ))\n );\n let ys = dropWhileGen(imperfect, enumFrom(1))\n while (true) {\n yield ys.next().value - 1;\n ys = dropWhileGen(imperfect, ys)\n }\n }\n\n // GENERIC FUNCTIONS ----------------------------\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // dropWhileGen :: (a -> Bool) -> Gen [a] -> [a]\n const dropWhileGen = (p, xs) => {\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n nxt = xs.next();\n v = nxt.value;\n }\n return xs;\n };\n\n // enumFrom :: Int -> [Int]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // gcd :: Int -> Int -> Int\n const gcd = (x, y) => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // memoized :: (a -> b) -> (a -> b)\n const memoized = f => {\n const dctMemo = {};\n return x => {\n const v = dctMemo[x];\n return undefined !== v ? v : (dctMemo[x] = f(x));\n };\n };\n\n // showLog :: a -> IO ()\n const showLog = (...args) =>\n console.log(\n args\n .map(JSON.stringify)\n .join(' -> ')\n );\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n main();\n})();"} {"title": "Phrase reversals", "language": "JavaScript", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "(function (p) {\n return [\n p.split('').reverse().join(''),\n\n p.split(' ').map(function (x) {\n return x.split('').reverse().join('');\n }).join(' '),\n\n p.split(' ').reverse().join(' ')\n\n ].join('\\n');\n\n})('rosetta code phrase reversal');"} {"title": "Pig the dice game", "language": "JavaScript", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "let players = [\n { name: '', score: 0 },\n { name: '', score: 0 }\n];\nlet curPlayer = 1,\n gameOver = false;\n\nplayers[0].name = prompt('Your name, player #1:').toUpperCase();\nplayers[1].name = prompt('Your name, player #2:').toUpperCase();\n\nfunction roll() { return 1 + Math.floor(Math.random()*6) }\n\nfunction round(player) {\n let curSum = 0,\n quit = false,\n dice;\n alert(`It's ${player.name}'s turn (${player.score}).`);\n while (!quit) {\n dice = roll();\n if (dice == 1) {\n alert('You roll a 1. What a pity!');\n quit = true;\n } else {\n curSum += dice;\n quit = !confirm(`\n You roll a ${dice} (sum: ${curSum}).\\n\n Roll again?\n `);\n if (quit) {\n player.score += curSum;\n if (player.score >= 100) gameOver = true;\n }\n }\n }\n}\n// main\nwhile (!gameOver) {\n if (curPlayer == 0) curPlayer = 1; else curPlayer = 0;\n round(players[curPlayer]);\n if (gameOver) alert(`\n ${players[curPlayer].name} wins (${players[curPlayer].score}).\n `);\n}\n"} {"title": "Plasma effect", "language": "JavaScript from Java", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "\n\n\n \n \n\n\n \n \n\n\n"} {"title": "Poker hand analyser", "language": "JavaScript ECMAScript 6", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];\nconst SUITS = ['\u2665', '\u2666', '\u2663', '\u2660'];\n\nfunction analyzeHand(hand){\n\tlet cards = hand.split(' ').filter(x => x !== 'joker');\n\tlet jokers = hand.split(' ').length - cards.length;\n\t\n\tlet faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) );\n\tlet suits = cards.map( card => SUITS.indexOf(card.slice(-1)) );\n\t\n\tif( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) \n\t\treturn 'invalid';\n\t\n\tlet flush = suits.every(suit => suit === suits[0]);\n\tlet groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x );\n\tlet shifted = faces.map(x => (x + 1) % 13);\n\tlet distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted));\n\tlet straight = groups[0] === 1 && distance < 5;\n\tgroups[0] += jokers;\n\t\n\tif (groups[0] === 5) return 'five-of-a-kind'\n\telse if (straight && flush) return 'straight-flush'\n\telse if (groups[0] === 4) return 'four-of-a-kind'\n\telse if (groups[0] === 3 && groups[1] === 2) return 'full-house'\n\telse if (flush) return 'flush'\n\telse if (straight) return 'straight'\n\telse if (groups[0] === 3) return 'three-of-a-kind'\n\telse if (groups[0] === 2 && groups[1] === 2) return 'two-pair'\n\telse if (groups[0] === 2) return 'one-pair'\n\telse return 'high-card';\n}"} {"title": "Polyspiral", "language": "JavaScript", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "===Version #1 - Plain===\nThis Polyspiral Generator page alows user to enjoy hundreds of polyspirals in different colors.
\nThis is inspired by a discovery made while using the gnuplot. \n(See [[Talk:Polyspiral| Discussion ]] for Polyspiral task.)
\n'''Note:'''\n* Some polyspirals would be degenerated to a single branch of it or even to a single line.
\n* An image uploading is still blocked. But you have a browser!? So, copy/paste/save this page and double click it.\n"} {"title": "Polyspiral", "language": "JavaScript from Java", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "\n\n\n \n \n\n\n \n \n\n\n"} {"title": "Population count", "language": "Javascript", "task": "The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.\n\n''Population count'' is also known as:\n::::* ''pop count''\n::::* ''popcount'' \n::::* ''sideways sum''\n::::* ''bit summation'' \n::::* ''Hamming weight'' \n\n\nFor example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.\n\n\n''Evil numbers'' are non-negative integers that have an ''even'' population count.\n\n''Odious numbers'' are positive integers that have an ''odd'' population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with '''0''' (zero indexed).\n:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').\n:* display the 1st thirty ''evil'' numbers.\n:* display the 1st thirty ''odious'' numbers.\n* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.\n\n", "solution": "(() => {\n 'use strict';\n\n // populationCount :: Int -> Int\n const populationCount = n =>\n // The number of non-zero bits in the binary\n // representation of the integer n.\n sum(unfoldr(\n x => 0 < x ? (\n Just(Tuple(x % 2)(Math.floor(x / 2)))\n ) : Nothing()\n )(n));\n\n // ----------------------- TEST ------------------------\n // main :: IO ()\n const main = () => {\n const [evens, odds] = Array.from(\n partition(compose(even, populationCount))(\n enumFromTo(0)(59)\n )\n );\n return [\n 'Population counts of the first 30 powers of three:',\n ` [${enumFromTo(0)(29).map(\n compose(populationCount, raise(3))\n ).join(',')}]`,\n \"\\nFirst thirty 'evil' numbers:\",\n ` [${[evens.join(',')]}]`,\n \"\\nFirst thirty 'odious' numbers:\",\n ` [${odds.join(',')}]`\n ].join('\\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\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 // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => !isNaN(m) ? (\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i)\n ) : enumFromTo_(m)(n);\n\n\n // even :: Int -> Bool\n const even = n =>\n // True if n is an even number.\n 0 === n % 2;\n\n\n // partition :: (a -> Bool) -> [a] -> ([a], [a])\n const partition = p =>\n // A tuple of two lists - those elements in\n // xs which match p, and those which don't.\n xs => ([...xs]).reduce(\n (a, x) =>\n p(x) ? (\n Tuple(a[0].concat(x))(a[1])\n ) : Tuple(a[0])(a[1].concat(x)),\n Tuple([])([])\n );\n\n\n // raise :: Num -> Int -> Num\n const raise = x =>\n // X to the power of n.\n n => Math.pow(x, n);\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n\n // unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\n const unfoldr = f =>\n v => {\n const xs = [];\n let xr = [v, v];\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 // ---\n return main();\n})();"} {"title": "Pythagoras tree", "language": "JavaScript from Java", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "\n\n\n\n \n \n\n\n\n \n \n\n\n\n"} {"title": "Pythagorean quadruples", "language": "JavaScript from Haskell", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () => {\n const xs = takeWhileGen(\n x => 2200 >= x,\n mergeInOrder(\n powersOfTwo(),\n fmapGen(x => 5 * x, powersOfTwo())\n )\n );\n\n return (\n console.log(JSON.stringify(xs)),\n xs\n );\n }\n\n // powersOfTwo :: Gen [Int]\n const powersOfTwo = () =>\n iterate(x => 2 * x, 1);\n\n // mergeInOrder :: Gen [Int] -> Gen [Int] -> Gen [Int]\n const mergeInOrder = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just;\n if (fst(ta) < fst(tb)) {\n yield(fst(ta));\n a = uncons(snd(ta))\n } else {\n yield(fst(tb));\n b = uncons(snd(tb))\n }\n }\n }\n return go(uncons(ga), uncons(gb))\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n const g = gen;\n let v = take(1, g);\n while (0 < v.length) {\n yield(f(v))\n v = take(1, g)\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // iterate :: (a -> a) -> a -> Generator [a]\n function* iterate(f, x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n }\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // takeWhileGen :: (a -> Bool) -> Generator [a] -> [a]\n const takeWhileGen = (p, xs) => {\n const ys = [];\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n ys.push(v);\n nxt = xs.next();\n v = nxt.value\n }\n return ys;\n };\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Pythagorean triples", "language": "JavaScript", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "(() => {\n \"use strict\";\n\n // Arguments: predicate, maximum perimeter\n // pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int\n const pythTripleCount = p =>\n maxPerim => {\n const\n xs = enumFromTo(1)(\n Math.floor(maxPerim / 2)\n );\n\n return xs.flatMap(\n x => xs.slice(x).flatMap(\n y => xs.slice(y).flatMap(\n z => ((x + y + z <= maxPerim) &&\n ((x * x) + (y * y) === z * z) &&\n p(x, y, z)) ? [\n [x, y, z]\n ] : []\n )\n )\n ).length;\n };\n\n // ---------------------- TEST -----------------------\n const main = () => [10, 100, 1000]\n .map(n => ({\n maxPerimeter: n,\n triples: pythTripleCount(() => true)(n),\n primitives: pythTripleCount(\n (x, y) => gcd(x)(y) === 1\n )(n)\n }));\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // abs :: Num -> Num\n const abs =\n // Absolute value of a given number\n // without the sign.\n x => 0 > x ? (\n -x\n ) : x;\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // gcd :: Integral a => a -> a -> a\n const gcd = x =>\n y => {\n const zero = x.constructor(0);\n const go = (a, b) =>\n zero === b ? (\n a\n ) : go(b, a % b);\n\n return go(abs(x), abs(y));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Quaternion type", "language": "JavaScript", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "var Quaternion = (function() {\n // The Q() function takes an array argument and changes it\n // prototype so that it becomes a Quaternion instance. This is\n // scoped only for prototype member access.\n function Q(a) {\n\ta.__proto__ = proto;\n\treturn a;\n }\n\n // Actual constructor. This constructor converts its arguments to\n // an array, then that array to a Quaternion instance, then\n // returns that instance. (using \"new\" with this constructor is\n // optional)\n function Quaternion() {\n\treturn Q(Array.prototype.slice.call(arguments, 0, 4));\n }\n\n // Prototype for all Quaternions\n const proto = {\n\t// Inherits from a 4-element Array\n\t__proto__ : [0,0,0,0],\n\n\t// Properties -- In addition to Array[0..3] access, we\n\t// also define matching a, b, c, and d properties\n\tget a() this[0],\n\tget b() this[1],\n\tget c() this[2],\n\tget d() this[3],\n\n\t// Methods\n\tnorm : function() Math.sqrt(this.map(function(x) x*x).reduce(function(x,y) x+y)),\n\tnegate : function() Q(this.map(function(x) -x)),\n\tconjugate : function() Q([ this[0] ].concat(this.slice(1).map(function(x) -x))),\n\tadd : function(x) {\n\t if (\"number\" === typeof x) {\n\t\treturn Q([ this[0] + x ].concat(this.slice(1)));\n\t } else {\n\t\treturn Q(this.map(function(v,i) v+x[i]));\n\t }\n\t},\n\tmul : function(r) {\n\t var q = this;\n\t if (\"number\" === typeof r) {\n\t\treturn Q(q.map(function(e) e*r));\n\t } else {\n\t\treturn Q([ q[0] * r[0] - q[1] * r[1] - q[2] * r[2] - q[3] * r[3],\n\t\t\t q[0] * r[1] + q[1] * r[0] + q[2] * r[3] - q[3] * r[2],\n\t\t\t q[0] * r[2] - q[1] * r[3] + q[2] * r[0] + q[3] * r[1],\n\t\t\t q[0] * r[3] + q[1] * r[2] - q[2] * r[1] + q[3] * r[0] ]);\n\t }\n\t},\n\tequals : function(q) this.every(function(v,i) v === q[i]),\n\ttoString : function() (this[0] + \" + \" + this[1] + \"i + \"+this[2] + \"j + \" + this[3] + \"k\").replace(/\\+ -/g, '- ')\n };\n\n Quaternion.prototype = proto;\n return Quaternion;\n})();"} {"title": "RPG attributes generator", "language": "Javascript", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "function roll() {\n const stats = {\n total: 0,\n rolls: []\n }\n let count = 0;\n\n for(let i=0;i<=5;i++) {\n let d6s = [];\n\n for(let j=0;j<=3;j++) {\n d6s.push(Math.ceil(Math.random() * 6))\n } \n\n d6s.sort().splice(0, 1);\n rollTotal = d6s.reduce((a, b) => a+b, 0);\n\n stats.rolls.push(rollTotal);\n stats.total += rollTotal; \n }\n \n return stats;\n}\n\nlet rolledCharacter = roll();\n \nwhile(rolledCharacter.total < 75 || rolledCharacter.rolls.filter(a => a >= 15).length < 2){\n rolledCharacter = roll();\n}\n\nconsole.log(`The 6 random numbers generated are:\n${rolledCharacter.rolls.join(', ')}\n\nTheir sum is ${rolledCharacter.total} and ${rolledCharacter.rolls.filter(a => a >= 15).length} of them are >= 15`);"} {"title": "RPG attributes generator", "language": "Javascript from Python", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n // 10 random heroes drawn from\n // a non-finite series.\n unlines(map(\n xs => show(sum(xs)) +\n ' -> [' + show(xs) + ']',\n\n take(10, heroes(\n seventyFivePlusWithTwo15s\n ))\n ));\n\n // seventyFivePlusWithTwo15s :: [Int] -> Bool\n const seventyFivePlusWithTwo15s = xs =>\n // Total score over 75,\n // with two or more qualities scoring 15.\n 75 < sum(xs) && 1 < length(filter(\n x => 15 === x, xs\n ));\n\n // heroes :: Gen IO [(Int, Int, Int, Int, Int, Int)]\n function* heroes(p) {\n // Non-finite list of heroes matching\n // the requirements of predicate p.\n while (true) {\n yield hero(p)\n }\n }\n\n // hero :: (Int -> Bool) -> IO (Int, Int, Int, Int, Int, Int)\n const hero = p =>\n // A random character matching the\n // requirements of predicate p.\n until(p, character, []);\n\n // character :: () -> IO [Int]\n const character = () =>\n // A random character with six\n // integral attributes.\n map(() => sum(tail(sort(map(\n randomRInt(1, 6),\n enumFromTo(1, 4)\n )))),\n enumFromTo(1, 6)\n );\n\n\n // GENERIC FUNCTIONS ----------------------------------\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 // e.g. map(randomRInt(1, 10), enumFromTo(1, 20))\n\n // randomRInt :: Int -> Int -> IO () -> Int\n const randomRInt = (low, high) => () =>\n low + Math.floor(\n (Math.random() * ((high - low) + 1))\n );\n\n // show :: a -> String\n const show = x => x.toString()\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Ramer-Douglas-Peucker line simplification", "language": "JavaScript from Go", "task": "The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:\n (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) \n\nThe error threshold to be used is: '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.\n\n", "solution": "/**\n * @typedef {{\n * x: (!number),\n * y: (!number)\n * }}\n */\nlet pointType;\n\n/**\n * @param {!Array} l\n * @param {number} eps\n */\nconst RDP = (l, eps) => {\n const last = l.length - 1;\n const p1 = l[0];\n const p2 = l[last];\n const x21 = p2.x - p1.x;\n const y21 = p2.y - p1.y;\n\n const [dMax, x] = l.slice(1, last)\n .map(p => Math.abs(y21 * p.x - x21 * p.y + p2.x * p1.y - p2.y * p1.x))\n .reduce((p, c, i) => {\n const v = Math.max(p[0], c);\n return [v, v === p[0] ? p[1] : i + 1];\n }, [-1, 0]);\n\n if (dMax > eps) {\n return [...RDP(l.slice(0, x + 1), eps), ...RDP(l.slice(x), eps).slice(1)];\n }\n return [l[0], l[last]]\n};\n\nconst points = [\n {x: 0, y: 0},\n {x: 1, y: 0.1},\n {x: 2, y: -0.1},\n {x: 3, y: 5},\n {x: 4, y: 6},\n {x: 5, y: 7},\n {x: 6, y: 8.1},\n {x: 7, y: 9},\n {x: 8, y: 9},\n {x: 9, y: 9}];\n\nconsole.log(RDP(points, 1));"} {"title": "Random Latin squares", "language": "Javascript", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "class Latin {\n constructor(size = 3) {\n this.size = size;\n this.mst = [...Array(this.size)].map((v, i) => i + 1);\n this.square = Array(this.size).fill(0).map(() => Array(this.size).fill(0));\n\n if (this.create(0, 0)) {\n console.table(this.square);\n }\n }\n\n create(c, r) {\n const d = [...this.mst];\n let s;\n while (true) {\n do {\n s = d.splice(Math.floor(Math.random() * d.length), 1)[0];\n if (!s) return false;\n } while (this.check(s, c, r));\n\n this.square[c][r] = s;\n if (++c >= this.size) {\n c = 0;\n if (++r >= this.size) {\n return true;\n }\n }\n if (this.create(c, r)) return true;\n if (--c < 0) {\n c = this.size - 1;\n if (--r < 0) {\n return false;\n }\n }\n }\n }\n\n check(d, c, r) {\n for (let a = 0; a < this.size; a++) {\n if (c - a > -1) {\n if (this.square[c - a][r] === d)\n return true;\n }\n if (r - a > -1) {\n if (this.square[c][r - a] === d)\n return true;\n }\n }\n return false;\n }\n}\nnew Latin(5);\n"} {"title": "Random number generator (included)", "language": "JavaScript", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "The only built-in random number generation facility is Math.random(), which returns a floating-point number greater than or equal to 0 and less than 1, with approximately uniform distribution. The standard (ECMA-262) does not specify what algorithm is to be used.\n\n"} {"title": "Range consolidation", "language": "JavaScript from Python", "task": "Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* If one range covers all of the other then the result is that encompassing range.\n* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.\n* Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. \n\nIf '''N < 2''' then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then \n: there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then \n: there is : an overlap '''[2.5, 1.8]''' between the ranges and \n: the result is the single range '''[1, 4.7]'''. \n: Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then \n: they touch at '''7.2''' and \n: the result is the single range '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' \n: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' \n: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and \n: consolidate to produce the range '''[1, 5]'''. \n: This range, in turn, overlaps the other range '''[4, 8]''', and \n: so consolidates to the final output of the single range '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; and show the\nrange with the smaller lower bound to the left of other ranges when showing multiple ranges.\n\nOutput the ''normalized'' result of applying consolidation to these five sets of ranges: \n [1.1, 2.2]\n [6.1, 7.2], [7.2, 8.3]\n [4, 3], [2, 1]\n [4, 3], [2, 1], [-1, -2], [3.9, 10]\n [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] \nShow all output here.\n\n\n;See also:\n* [[Set consolidation]]\n* [[Set of real numbers]]\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n // consolidated :: [(Float, Float)] -> [(Float, Float)]\n const consolidated = xs =>\n foldl((abetc, xy) =>\n 0 < abetc.length ? (() => {\n const\n etc = abetc.slice(1),\n [a, b] = abetc[0],\n [x, y] = xy;\n\n return y >= b ? (\n cons(xy, etc)\n ) : y >= a ? (\n cons([x, b], etc)\n ) : cons(xy, abetc);\n })() : [xy],\n [],\n sortBy(flip(comparing(fst)),\n map(([a, b]) => a < b ? (\n [a, b]\n ) : [b, a],\n xs\n )\n )\n );\n\n // TEST -------------------------------------------\n console.log(\n tabulated(\n 'Range consolidations:',\n JSON.stringify,\n JSON.stringify,\n consolidated,\n [\n [\n [1.1, 2.2]\n ],\n [\n [6.1, 7.2],\n [7.2, 8.3]\n ],\n [\n [4, 3],\n [2, 1]\n ],\n [\n [4, 3],\n [2, 1],\n [-1, -2],\n [3.9, 10]\n ],\n [\n [1, 3],\n [-6, -1],\n [-4, -5],\n [8, 2],\n [-6, -6]\n ]\n ]\n )\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) => [x].concat(xs);\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // foldl :: (a -> b -> a) -> a -> [b] -> a\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = (n, cFiller, s) =>\n n > s.length ? (\n s.padStart(n, cFiller)\n ) : s;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n 0 < xs.length ? (\n xs.slice(1)\n .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0])\n ) : undefined;\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // tabulated :: String -> (a -> String) ->\n // (b -> String) ->\n // (a -> b) -> [a] -> String\n const tabulated = (s, xShow, fxShow, f, xs) => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = map(xShow, xs),\n w = maximumBy(comparing(x => x.length), ys).length,\n rows = zipWith(\n (a, b) => justifyRight(w, ' ', a) + ' -> ' + b,\n ys,\n map(compose(fxShow, f), xs)\n );\n return s + '\\n' + unlines(rows);\n };\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Range expansion", "language": "JavaScript", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "#!/usr/bin/env js\n\nfunction main() {\n print(rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20'));\n}\n\nfunction rangeExpand(rangeExpr) {\n \n function getFactors(term) {\n var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);\n if (!matches) return {first:Number(term)};\n return {first:Number(matches[1]), last:Number(matches[2])};\n }\n \n function expandTerm(term) {\n var factors = getFactors(term);\n if (factors.length < 2) return [factors.first];\n var range = [];\n for (var n = factors.first; n <= factors.last; n++) {\n range.push(n);\n }\n return range;\n }\n \n var result = [];\n var terms = rangeExpr.split(/,/);\n for (var t in terms) {\n result = result.concat(expandTerm(terms[t]));\n }\n \n return result;\n}\n\nmain();\n"} {"title": "Range extraction", "language": "JavaScript", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "function rangeExtraction(list) {\n var len = list.length;\n var out = [];\n var i, j;\n\n for (i = 0; i < len; i = j + 1) {\n // beginning of range or single\n out.push(list[i]);\n \n // find end of range\n for (var j = i + 1; j < len && list[j] == list[j-1] + 1; j++);\n j--;\n \n if (i == j) {\n // single number\n out.push(\",\");\n } else if (i + 1 == j) {\n // two numbers\n out.push(\",\", list[j], \",\");\n } else { \n // range\n out.push(\"-\", list[j], \",\");\n }\n }\n out.pop(); // remove trailing comma\n return out.join(\"\");\n}\n\n// using print function as supplied by Rhino standalone\nprint(rangeExtraction([\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n]));"} {"title": "Range extraction", "language": "JavaScript from Haskell", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "(() => {\n 'use strict';\n\n // ---------------- RANGE EXTRACTION -----------------\n\n // rangeFormat :: [Int] -> String\n const rangeFormat = xs =>\n splitBy((a, b) => b - a > 1, xs)\n .map(rangeString)\n .join(',');\n\n // rangeString :: [Int] -> String\n const rangeString = xs =>\n xs.length > 2 ? (\n [xs[0], last(xs)].map(show)\n .join('-')\n ) : xs.join(',')\n\n\n // ---------------------- TEST -----------------------\n const main = () =>\n rangeFormat([0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n ]);\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // Splitting not on a delimiter, but whenever the \n // relationship between two consecutive items matches \n // a supplied predicate function\n\n // splitBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const splitBy = (f, xs) => {\n if (xs.length < 2) return [xs];\n const\n h = xs[0],\n lstParts = xs.slice(1)\n .reduce(([acc, active, prev], x) =>\n f(prev, x) ? (\n [acc.concat([active]), [x], x]\n ) : [acc, active.concat(x), x], [\n [],\n [h],\n h\n ]);\n return lstParts[0].concat([lstParts[1]]);\n };\n\n // last :: [a] -> a\n const last = xs => (\n // The last item of a list.\n ys => 0 < ys.length ? (\n ys.slice(-1)[0]\n ) : undefined\n )(xs);\n\n // show :: a -> String\n const show = x =>\n JSON.stringify(x);\n\n // MAIN --\n return main();\n})();"} {"title": "Rate counter", "language": "JavaScript", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "function millis() { // Gets current time in milliseconds.\n return (new Date()).getTime();\n}\n\n/* Executes function 'func' n times, returns array of execution times. */\nfunction benchmark(n, func, args) {\n var times = [];\n for (var i=0; i0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "(() => {\n const main = () => {\n\n console.log(\n 'First 15 Recaman:\\n' +\n recamanUpto(i => 15 === i)\n );\n\n console.log(\n '\\n\\nFirst duplicated Recaman:\\n' +\n last(recamanUpto(\n (_, set, rs) => set.size !== rs.length\n ))\n );\n\n const setK = new Set(enumFromTo(0, 1000));\n console.log(\n '\\n\\nNumber of Recaman terms needed to generate' +\n '\\nall integers from [0..1000]:\\n' +\n (recamanUpto(\n (_, setR) => isSubSetOf(setK, setR)\n ).length - 1)\n );\n };\n\n // RECAMAN --------------------------------------------\n\n // recamanUpto :: (Int -> Set Int > [Int] -> Bool) -> [Int]\n const recamanUpto = p => {\n let\n i = 1,\n r = 0, // First term of series\n rs = [r];\n const seen = new Set(rs);\n while (!p(i, seen, rs)) {\n r = nextR(seen, i, r);\n seen.add(r);\n rs.push(r);\n i++;\n }\n return rs;\n }\n\n // Next Recaman number.\n\n // nextR :: Set Int -> Int -> Int\n const nextR = (seen, i, n) => {\n const back = n - i;\n return (0 > back || seen.has(back)) ? (\n n + i\n ) : back;\n };\n\n // GENERIC --------------------------------------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // isSubsetOf :: Ord a => Set a -> Set a -> Bool\n const isSubSetOf = (a, b) => {\n for (let x of a) {\n if (!b.has(x)) return false;\n }\n return true;\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // MAIN ------------------------------------------------\n return main();\n})();"} {"title": "Rep-string", "language": "JavaScript", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n // REP-CYCLES -------------------------------------\n\n // repCycles :: String -> [String]\n const repCycles = s => {\n const n = s.length;\n return filter(\n x => s === take(n, cycle(x)).join(''),\n tail(inits(take(quot(n, 2), s)))\n );\n };\n\n // TEST -------------------------------------------\n console.log(fTable(\n 'Longest cycles:\\n',\n str,\n xs => 0 < xs.length ? concat(last(xs)) : '(none)',\n repCycles,\n [\n '1001110011',\n '1110111011',\n '0010010010',\n '1010101010',\n '1111111111',\n '0100101101',\n '0100100',\n '101',\n '11',\n '00',\n '1'\n ]\n ));\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cycle :: [a] -> Generator [a]\n function* cycle(xs) {\n const lng = xs.length;\n let i = 0;\n while (true) {\n yield(xs[i])\n i = (1 + i) % lng;\n }\n }\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // fTable :: String -> (a -> String) -> \n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = (s, xShow, fxShow, f, xs) => {\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(length));\n return s + '\\n' + zipWith(\n (a, b) => a.padStart(w, ' ') + ' -> ' + b,\n ys,\n xs.map(x => fxShow(f(x)))\n ).join('\\n');\n };\n\n // inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3]\n // inits('abc') -> [\"\", \"a\", \"ab\", \"abc\"]\n\n // inits :: [a] -> [[a]]\n // inits :: String -> [String]\n const inits = xs => [\n []\n ]\n .concat(('string' === typeof xs ? xs.split('') : xs)\n .map((_, i, lst) => lst.slice(0, 1 + i)));\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // quot :: Int -> Int -> Int\n const quot = (n, m) => Math.floor(n / m);\n\n // str :: a -> String\n const str = x => x.toString();\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Resistor mesh", "language": "JavaScript", "task": "Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,\nfind the resistance between points '''A''' and '''B'''.\n\n\n;See also:\n* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)\n* An article on how to calculate this and an implementation in Mathematica\n\n", "solution": "// Vector addition, scalar multiplication & dot product:\nconst add = (u, v) => {let i = u.length; while(i--) u[i] += v[i]; return u;};\nconst sub = (u, v) => {let i = u.length; while(i--) u[i] -= v[i]; return u;};\nconst mul = (a, u) => {let i = u.length; while(i--) u[i] *= a; return u;};\nconst dot = (u, v) => {let s = 0, i = u.length; while(i--) s += u[i]*v[i]; return s;};\n\nconst W = 10, H = 10, A = 11, B = 67; \n\nfunction getAdjacent(node){ // Adjacency lists for square grid\n let list = [], x = node % W, y = Math.floor(node / W);\n if (x > 0) list.push(node - 1);\n if (y > 0) list.push(node - W);\n if (x < W - 1) list.push(node + 1);\n if (y < H - 1) list.push(node + W);\n return list;\n}\n\nfunction linOp(u){ // LHS of the linear equation\n let v = new Float64Array(W * H);\n for(let i = 0; i < v.length; i++){\n if ( i === A || i === B ) {\n v[i] = u[i];\n continue;\n }\n // For each node other then A, B calculate the net current flow:\n for(let j of getAdjacent(i)){\n v[i] += (j === A || j === B) ? u[i] : u[i] - u[j];\n }\n }\n return v;\n}\n\nfunction getRHS(phiA = 1, phiB = 0){ // RHS of the linear equation\n let b = new Float64Array(W * H);\n // Setting boundary conditions (electric potential at A and B):\n b[A] = phiA;\n b[B] = phiB;\n for(let j of getAdjacent(A)) b[j] = phiA;\n for(let j of getAdjacent(B)) b[j] = phiB;\n return b;\n}\n\nfunction init(phiA = 1, phiB = 0){ // initialize unknown vector\n let u = new Float64Array(W * H);\n u[A] = phiA;\n u[B] = phiB; \n return u;\n}\n\nfunction solveLinearSystem(err = 1e-20){ // conjugate gradient solver\n\n let b = getRHS();\n let u = init();\n let r = sub(linOp(u), b);\n let p = r;\n let e = dot(r,r);\n\n while(true){\n let Ap = linOp(p);\n let alpha = e / dot(p, Ap);\n u = sub(u, mul(alpha, p.slice()));\n r = sub(linOp(u), b); \n let e_new = dot(r,r);\n let beta = e_new / e;\n\n if(e_new < err) return u;\n\n e = e_new;\n p = add(r, mul(beta, p));\n }\n}\n\nfunction getResistance(u){\n let curr = 0;\n for(let j of getAdjacent(A)) curr += u[A] - u[j];\n return 1 / curr;\n}\n\nlet phi = solveLinearSystem();\nlet res = getResistance(phi);\nconsole.log(`R = ${res} Ohm`);\n"} {"title": "Reverse words in a string", "language": "JavaScript", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "var strReversed =\n\"---------- Ice and Fire ------------\\n\\\n\\n\\\nfire, in end will world the say Some\\n\\\nice. in say Some\\n\\\ndesire of tasted I've what From\\n\\\nfire. favor who those with hold I\\n\\\n\\n\\\n... elided paragraph last ...\\n\\\n\\n\\\nFrost Robert -----------------------\";\n \nfunction reverseString(s) {\n return s.split('\\n').map(\n function (line) {\n return line.split(/\\s/).reverse().join(' ');\n }\n ).join('\\n');\n}\n \nconsole.log(\n reverseString(strReversed)\n);"} {"title": "Roman numerals/Decode", "language": "JavaScript from Haskell", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "(() => {\n\n // -------------- ROMAN NUMERALS DECODED ---------------\n\n // Folding from right to left,\n // lower leftward characters are subtracted,\n // others are added.\n\n // fromRoman :: String -> Int\n const fromRoman = s =>\n foldr(l => ([r, n]) => [\n l,\n l >= r ? (\n n + l\n ) : n - l\n ])([0, 0])(\n [...s].map(charVal)\n )[1];\n\n // charVal :: Char -> Maybe Int\n const charVal = k => {\n const v = {\n I: 1,\n V: 5,\n X: 10,\n L: 50,\n C: 100,\n D: 500,\n M: 1000\n } [k];\n return v !== undefined ? v : 0;\n };\n\n // ----------------------- TEST ------------------------\n const main = () => [\n 'MDCLXVI', 'MCMXC', 'MMVIII', 'MMXVI', 'MMXVII'\n ]\n .map(fromRoman)\n .join('\\n');\n\n\n // ----------------- GENERIC FUNCTIONS -----------------\n\n // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = f =>\n // Note that that the Haskell signature of foldr \n // differs from that of foldl - the positions of \n // accumulator and current value are reversed.\n a => xs => [...xs].reduceRight(\n (a, x) => f(x)(a),\n a\n );\n\n // MAIN ---\n return main();\n})();"} {"title": "Roman numerals/Encode", "language": "JavaScript from Tcl", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "(function () {\n 'use strict';\n\n\n // If the Roman is a string, pass any delimiters through\n\n // (Int | String) -> String\n function romanTranscription(a) {\n if (typeof a === 'string') {\n var ps = a.split(/\\d+/),\n dlm = ps.length > 1 ? ps[1] : undefined;\n\n return (dlm ? a.split(dlm)\n .map(function (x) {\n return Number(x);\n }) : [a])\n .map(roman)\n .join(dlm);\n } else return roman(a);\n }\n\n // roman :: Int -> String\n function roman(n) {\n return [[1000, \"M\"], [900, \"CM\"], [500, \"D\"], [400, \"CD\"], [100,\n \"C\"], [90, \"XC\"], [50, \"L\"], [40, \"XL\"], [10, \"X\"], [9,\n \"IX\"], [5, \"V\"], [4, \"IV\"], [1, \"I\"]]\n .reduce(function (a, lstPair) {\n var m = a.remainder,\n v = lstPair[0];\n\n return (v > m ? a : {\n remainder: m % v,\n roman: a.roman + Array(\n Math.floor(m / v) + 1\n )\n .join(lstPair[1])\n });\n }, {\n remainder: n,\n roman: ''\n }).roman; \n }\n\n // TEST\n\n return [2016, 1990, 2008, \"14.09.2015\", 2000, 1666].map(\n romanTranscription);\n\n})();"} {"title": "Roman numerals/Encode", "language": "JavaScript from Haskell", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "(() => {\n \"use strict\";\n\n // -------------- ROMAN INTEGER STRINGS --------------\n\n // roman :: Int -> String\n const roman = n =>\n mapAccumL(residue =>\n ([k, v]) => second(\n q => 0 < q ? (\n k.repeat(q)\n ) : \"\"\n )(remQuot(residue)(v))\n )(n)(\n zip([\n \"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\",\n \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\"\n ])([\n 1000, 900, 500, 400, 100, 90,\n 50, 40, 10, 9, 5, 4, 1\n ])\n )[1]\n .join(\"\");\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () => (\n [2016, 1990, 2008, 2000, 2020, 1666].map(roman)\n ).join(\"\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc ->\n // [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 tpl = f(a[0])(x);\n\n return [\n tpl[0],\n a[1].concat(tpl[1])\n ];\n },\n [acc, []]\n );\n\n\n // remQuot :: Int -> Int -> (Int, Int)\n const remQuot = m =>\n n => [m % n, Math.trunc(m / n)];\n\n\n // second :: (a -> b) -> ((c, a) -> (c, b))\n const second = f =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n xy => [xy[0], f(xy[1])];\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 // MAIN --\n return main();\n})();"} {"title": "Runge-Kutta method", "language": "JavaScript", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "function rk4(y, x, dx, f) {\n var k1 = dx * f(x, y),\n k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0),\n k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0),\n k4 = dx * f(x + dx, +y + k3);\n\n return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;\n}\n\nfunction f(x, y) {\n return x * Math.sqrt(y);\n}\n\nfunction actual(x) {\n return (1/16) * (x*x+4)*(x*x+4);\n}\n\nvar y = 1.0,\n x = 0.0,\n step = 0.1,\n steps = 0,\n maxSteps = 101,\n sampleEveryN = 10;\n\nwhile (steps < maxSteps) {\n if (steps%sampleEveryN === 0) {\n console.log(\"y(\" + x + \") = \\t\" + y + \"\\t \u00b1 \" + (actual(x) - y).toExponential());\n }\n\n y = rk4(y, x, step, f);\n\n // using integer math for the step addition\n // to prevent floating point errors as 0.2 + 0.1 != 0.3\n x = ((x * 10) + (step * 10)) / 10;\n steps += 1;\n}\n"} {"title": "Runtime evaluation", "language": "JavaScript", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "var foo = eval('{value: 42}');\neval('var bar = \"Hello, world!\";');\n\ntypeof foo; // 'object'\ntypeof bar; // 'string'\n"} {"title": "Runtime evaluation/In an environment", "language": "JavaScript", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "function evalWithX(expr, a, b) {\n var x = a;\n var atA = eval(expr);\n x = b;\n var atB = eval(expr);\n return atB - atA;\n}"} {"title": "Sailors, coconuts and a monkey problem", "language": "JavaScript from Python", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "(function () {\n\n // wakeSplit :: Int -> Int -> Int -> Int\n function wakeSplit(intNuts, intSailors, intDepth) {\n var nDepth = intDepth !== undefined ? intDepth : intSailors,\n portion = Math.floor(intNuts / intSailors),\n remain = intNuts % intSailors;\n\n return 0 >= portion || remain !== (nDepth ? 1 : 0) ?\n null : nDepth ? wakeSplit(\n intNuts - portion - remain, intSailors, nDepth - 1\n ) : intNuts;\n }\n\n // TEST for 5, 6, and 7 intSailors\n return [5, 6, 7].map(function (intSailors) {\n var intNuts = intSailors;\n\n while (!wakeSplit(intNuts, intSailors)) intNuts += 1;\n\n return intNuts;\n });\n})();"} {"title": "Selectively replace multiple instances of a character within a string", "language": "JavaScript", "task": "Task\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\n\n\n", "solution": "function findNth(s, c, n) {\n if (n === 1) return s.indexOf(c);\n return s.indexOf(c, findNth(s, c, n - 1) + 1);\n}\n\nfunction selectiveReplace(s, ops) {\n const chars = Array.from(s);\n for ([n, old, rep] of ops) {\n chars[findNth(s, old, n)] = rep;\n }\n return chars.join(\"\");\n}\n\nconsole.log(\n selectiveReplace(\"abracadabra\", [\n [1, \"a\", \"A\"], // the first 'a' with 'A'\n [2, \"a\", \"B\"], // the second 'a' with 'B'\n [4, \"a\", \"C\"], // the fourth 'a' with 'C'\n [5, \"a\", \"D\"], // the fifth 'a' with 'D'\n [1, \"b\", \"E\"], // the first 'b' with 'E'\n [2, \"r\", \"F\"], // the second 'r' with 'F'\n ])\n);"} {"title": "Semordnilap", "language": "JavaScript from Clojure", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "#!/usr/bin/env node\nvar fs = require('fs');\nvar sys = require('sys');\n\nvar dictFile = process.argv[2] || \"unixdict.txt\";\n\nvar dict = {};\nfs.readFileSync(dictFile)\n .toString()\n .split('\\n')\n .forEach(function(word) {\n dict[word] = word.split(\"\").reverse().join(\"\");\n });\n\nfunction isSemordnilap(word) { return dict[dict[word]]; };\n\nvar semordnilaps = []\nfor (var key in dict) {\n if (isSemordnilap(key)) {\n var rev = dict[key];\n if (key < rev) {\n semordnilaps.push([key,rev]) ;\n }\n }\n}\n\nvar count = semordnilaps.length;\nsys.puts(\"There are \" + count + \" semordnilaps in \" +\n dictFile + \". Here are 5:\" );\n\nvar indices=[]\nfor (var i=0; i {\n 'use strict';\n\n // semordnilap :: [String] -> String\n const semordnilap = xs => {\n const go = ([s, ws], w) =>\n s.has(w.split('').reverse().join('')) ? (\n [s, [w].concat(ws)]\n ) : [s.add(w), ws];\n return xs.reduce(go, [new Set(), []])[1];\n };\n\n const main = () => {\n \n // xs :: [String]\n const xs = semordnilap(\n lines(readFile('unixdict.txt'))\n );\n\n console.log(xs.length);\n xs.filter(x => 4 < x.length).forEach(\n x => showLog(...[x, x.split('').reverse().join('')])\n )\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n // lines :: String -> [String]\n const lines = s => s.split(/[\\r\\n]/);\n\n // readFile :: FilePath -> IO String\n const readFile = fp => {\n const\n e = $(),\n uw = ObjC.unwrap,\n s = uw(\n $.NSString.stringWithContentsOfFileEncodingError(\n $(fp)\n .stringByStandardizingPath,\n $.NSUTF8StringEncoding,\n e\n )\n );\n return undefined !== s ? (\n s\n ) : uw(e.localizedDescription);\n };\n\n // 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": "Sequence: smallest number with exactly n divisors", "language": "JavaScript", "task": "Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "(() => {\n 'use strict';\n\n // a005179 :: () -> [Int]\n const a005179 = () =>\n fmapGen(\n n => find(\n compose(\n eq(n),\n succ,\n length,\n properDivisors\n )\n )(enumFrom(1)).Just\n )(enumFrom(1));\n\n\n // ------------------------TEST------------------------\n // main :: IO ()\n const main = () =>\n console.log(\n take(15)(\n a005179()\n )\n );\n\n // [1,2,4,6,16,12,64,24,36,48,1024,60,4096,192,144]\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n };\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = a =>\n // True when a and b are equivalent in the terms\n // defined below for their shared data type.\n b => a === b;\n\n // find :: (a -> Bool) -> Gen [a] -> Maybe a\n const find = p => xs => {\n const mb = until(tpl => {\n const nxt = tpl[0];\n return nxt.done || p(nxt.value);\n })(\n tpl => Tuple(tpl[1].next())(\n tpl[1]\n )\n )(Tuple(xs.next())(xs))[0];\n return mb.done ? (\n Nothing()\n ) : Just(mb.value);\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // group :: [a] -> [[a]]\n const group = xs => {\n // A list of lists, each containing only equal elements,\n // such that the concatenation of these lists is xs.\n const go = xs =>\n 0 < xs.length ? (() => {\n const\n h = xs[0],\n i = xs.findIndex(x => h !== x);\n return i !== -1 ? (\n [xs.slice(0, i)].concat(go(xs.slice(i)))\n ) : [xs];\n })() : [];\n return go(xs);\n };\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]\n const liftA2List = f => xs => ys =>\n // The binary operator f lifted to a function over two\n // lists. f applied to each pair of arguments in the\n // cartesian product of xs and ys.\n xs.flatMap(\n x => ys.map(f(x))\n );\n\n // mul (*) :: Num a => a -> a -> a\n const mul = a => b => a * b;\n\n // properDivisors :: Int -> [Int]\n const properDivisors = n =>\n // The ordered divisors of n,\n // excluding n itself.\n 1 < n ? (\n sort(group(primeFactors(n)).reduce(\n (a, g) => liftA2List(mul)(a)(\n scanl(mul)([1])(g)\n ),\n [1]\n )).slice(0, -1)\n ) : [];\n\n // primeFactors :: Int -> [Int]\n const primeFactors = n => {\n // A list of the prime factors of n.\n const\n go = x => {\n const\n root = Math.floor(Math.sqrt(x)),\n m = until(\n ([q, _]) => (root < q) || (0 === (x % q))\n )(\n ([_, r]) => [step(r), 1 + r]\n )(\n [0 === x % 2 ? 2 : 3, 1]\n )[0];\n return m > root ? (\n [x]\n ) : ([m].concat(go(Math.floor(x / m))));\n },\n step = x => 1 + (x << 2) - ((x >> 1) << 1);\n return go(n);\n };\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // succ :: Enum a => a -> a\n const succ = x =>\n 1 + x;\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Set consolidation", "language": "JavaScript", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "(() => {\n 'use strict';\n\n // consolidated :: Ord a => [Set a] -> [Set a]\n const consolidated = xs => {\n const go = (s, xs) =>\n 0 !== xs.length ? (() => {\n const h = xs[0];\n return 0 === intersection(h, s).size ? (\n [h].concat(go(s, tail(xs)))\n ) : go(union(h, s), tail(xs));\n })() : [s];\n return foldr(go, [], xs);\n };\n\n\n // TESTS ----------------------------------------------\n const main = () =>\n map(xs => intercalate(\n ', and ',\n map(showSet, consolidated(xs))\n ),\n map(x => map(\n s => new Set(chars(s)),\n x\n ),\n [\n ['ab', 'cd'],\n ['ab', 'bd'],\n ['ab', 'cd', 'db'],\n ['hik', 'ab', 'cd', 'db', 'fgh']\n ]\n )\n ).join('\\n');\n\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // elems :: Dict -> [a]\n // elems :: Set -> [a]\n const elems = x =>\n 'Set' !== x.constructor.name ? (\n Object.values(x)\n ) : Array.from(x.values());\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f =>\n 1 < f.length ? (\n (a, b) => f(b, a)\n ) : (x => y => f(y)(x));\n\n // Note that that the Haskell signature of foldr differs from that of\n // foldl - the positions of accumulator and current value are reversed\n\n // foldr :: (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = (sep, xs) =>\n 0 < xs.length && 'string' === typeof sep &&\n 'string' === typeof xs[0] ? (\n xs.join(sep)\n ) : concat(intersperse(sep, xs));\n\n // intersection :: Ord a => Set a -> Set a -> Set a\n const intersection = (s, s1) =>\n new Set([...s].filter(x => s1.has(x)));\n\n // intersperse :: a -> [a] -> [a]\n // intersperse :: Char -> String -> String\n const intersperse = (sep, xs) => {\n const bln = 'string' === typeof xs;\n return xs.length > 1 ? (\n (bln ? concat : x => x)(\n (bln ? (\n xs.split('')\n ) : xs)\n .slice(1)\n .reduce((a, x) => a.concat([sep, x]), [xs[0]])\n )) : xs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // showSet :: Set -> String\n const showSet = s =>\n intercalate(elems(s), ['{', '}']);\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // union :: Ord a => Set a -> Set a -> Set a\n const union = (s, s1) =>\n Array.from(s1.values())\n .reduce(\n (a, x) => (a.add(x), a),\n new Set(s)\n );\n\n // MAIN ---\n return main();\n})();"} {"title": "Set of real numbers", "language": "Javascript", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "function realSet(set1, set2, op, values) {\n const makeSet=(set0)=>{\n let res = []\n if(set0.rangeType===0){\n for(let i=set0.low;i<=set0.high;i++)\n res.push(i);\n } else if (set0.rangeType===1) {\n for(let i=set0.low+1;i {\n \"use strict\";\n\n // ------- SHOELACE FORMULA FOR POLYGONAL AREA -------\n\n // shoelaceArea :: [(Float, Float)] -> Float\n const shoeLaceArea = vertices => abs(\n uncurry(subtract)(\n ap(zip)(compose(tail, cycle))(\n vertices\n )\n .reduce(\n (a, x) => [0, 1].map(b => {\n const n = Number(b);\n\n return a[n] + (\n x[0][n] * x[1][Number(!b)]\n );\n }),\n [0, 0]\n )\n )\n ) / 2;\n\n\n // ----------------------- TEST -----------------------\n const main = () => {\n const ps = [\n [3, 4],\n [5, 11],\n [12, 8],\n [9, 5],\n [5, 6]\n ];\n\n return [\n \"Polygonal area by shoelace formula:\",\n `${JSON.stringify(ps)} -> ${shoeLaceArea(ps)}`\n ]\n .join(\"\\n\");\n };\n\n\n // ---------------- GENERIC FUNCTIONS -----------------\n\n // abs :: Num -> Num\n const abs = x =>\n // Absolute value of a given number\n // without the sign.\n 0 > x ? -x : x;\n\n\n // ap :: (a -> b -> c) -> (a -> b) -> (a -> c)\n const ap = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (...fs) =>\n // A function defined by the right-to-left\n // composition of all the functions in fs.\n fs.reduce(\n (f, g) => x => f(g(x)),\n x => x\n );\n\n\n // cycle :: [a] -> Generator [a]\n const cycle = function* (xs) {\n // An infinite repetition of xs,\n // from which an arbitrary prefix\n // may be taken.\n const lng = xs.length;\n let i = 0;\n\n while (true) {\n yield xs[i];\n i = (1 + i) % lng;\n }\n };\n\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n xs.length\n ) : Infinity;\n\n\n // subtract :: Num -> Num -> Num\n const subtract = x =>\n y => y - x;\n\n\n // tail :: [a] -> [a]\n const tail = xs =>\n // A new list consisting of all\n // items of xs except the first.\n \"GeneratorFunction\" !== xs.constructor\n .constructor.name ? (\n Boolean(xs.length) ? (\n xs.slice(1)\n ) : undefined\n ) : (take(1)(xs), xs);\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => \"GeneratorFunction\" !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : Array.from({\n length: n\n }, () => {\n const x = xs.next();\n\n return x.done ? [] : [x.value];\n }).flat();\n\n\n // uncurry :: (a -> b -> c) -> ((a, b) -> c)\n const uncurry = f =>\n // A function over a pair, derived\n // from a curried function.\n (...args) => {\n const [x, y] = Boolean(args.length % 2) ? (\n args[0]\n ) : args;\n\n return f(x)(y);\n };\n\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = xs => ys => {\n const\n n = Math.min(length(xs), length(ys)),\n vs = take(n)(ys);\n\n return take(n)(xs)\n .map((x, i) => [x, vs[i]]);\n };\n\n\n // MAIN ---\n return main();\n})();"} {"title": "Show ASCII table", "language": "JavaScript", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "(() => {\n\n \"use strict\";\n\n // ------------------- ASCII TABLE -------------------\n\n // asciiTable :: String\n const asciiTable = () =>\n transpose(\n chunksOf(16)(\n enumFromTo(32)(127)\n .map(asciiEntry)\n )\n )\n .map(\n xs => xs.map(justifyLeft(12)(\" \"))\n .join(\"\")\n )\n .join(\"\\n\");\n\n // asciiEntry :: Int -> String\n const asciiEntry = n => {\n const k = asciiName(n);\n\n return \"\" === k ? (\n \"\"\n ) : `${justifyRight(4)(\" \")(n.toString())} : ${k}`;\n };\n\n // asciiName :: Int -> String\n const asciiName = n =>\n 32 > n || 127 < n ? (\n \"\"\n ) : 32 === n ? (\n \"Spc\"\n ) : 127 === n ? (\n \"Del\"\n ) : chr(n);\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // chr :: Int -> Char\n const chr = x =>\n // The character at unix code-point x.\n String.fromCodePoint(x);\n\n\n // chunksOf :: Int -> [a] -> [[a]]\n const chunksOf = n => {\n // xs split into sublists of length n.\n // The last sublist will be short if n\n // does not evenly divide the length of xs .\n const go = xs => {\n const chunk = xs.slice(0, n);\n\n return 0 < chunk.length ? (\n [chunk].concat(\n go(xs.slice(n))\n )\n ) : [];\n };\n\n return go;\n };\n\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m =>\n n => Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n\n // justifyLeft :: Int -> Char -> String -> String\n const justifyLeft = n =>\n // The string s, followed by enough padding (with\n // the character c) to reach the string length n.\n c => s => n > s.length ? (\n s.padEnd(n, c)\n ) : s;\n\n\n // justifyRight :: Int -> Char -> String -> String\n const justifyRight = n =>\n // The string s, preceded by enough padding (with\n // the character c) to reach the string length n.\n c => s => Boolean(s) ? (\n s.padStart(n, c)\n ) : \"\";\n\n\n // transpose :: [[a]] -> [[a]]\n const transpose = rows =>\n // The columns of the input transposed\n // into new rows.\n // This version assumes input rows of even length.\n 0 < rows.length ? rows[0].map(\n (x, i) => rows.flatMap(\n v => v[i]\n )\n ) : [];\n\n\n // MAIN ---\n return asciiTable();\n})();"} {"title": "Sierpinski pentagon", "language": "JavaScript", "task": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\n\n;See also\n* Sierpinski pentagon\n\n", "solution": "\n\n\n\n \n \tClick Pentaflake to iterate.  Order:   \n \t  \n \t(Reset anytime: to start new Pentaflake and change color.)\n \t

\n \n \n\n"} {"title": "Sierpinski triangle/Graphical", "language": "JavaScript", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": ";Note:\n* \"Order\" to calculate a size of resulting plot/matrix is not used in this algorithm, Instead, construction is done in accordance to a square   m x m matrix. In our case it should be equal to a size of the square canvas.\n* Change canvas setting from size \"640\" to \"1280\". You will discover that density of dots in plotted triangle is stable for this algorithm. Size of the plotted figure is constantly increasing in the S-E direction. Also, the number of all triangles in N-W triangular part of the canvas is always the same.\n* So, in this case it could be called: \"Sierpinski ever-expanding field of triangles\".\n
\n"} {"title": "Smith numbers", "language": "JavaScript from Python", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "(() => {\n 'use strict';\n\n // isSmith :: Int -> Bool\n const isSmith = n => {\n const pfs = primeFactors(n);\n return (1 < pfs.length || n !== pfs[0]) && (\n sumDigits(n) === pfs.reduce(\n (a, x) => a + sumDigits(x),\n 0\n )\n );\n };\n\n // TEST -----------------------------------------------\n\n // main :: IO ()\n const main = () => {\n\n // lowSmiths :: [Int]\n const lowSmiths = enumFromTo(2)(9999)\n .filter(isSmith);\n\n // lowSmithCount :: Int\n const lowSmithCount = lowSmiths.length;\n return [\n \"Count of Smith Numbers below 10k:\",\n show(lowSmithCount),\n \"\\nFirst 15 Smith Numbers:\",\n unwords(take(15)(lowSmiths)),\n \"\\nLast 12 Smith Numbers below 10000:\",\n unwords(drop(lowSmithCount - 12)(lowSmiths))\n ].join('\\n');\n };\n\n // SMITH ----------------------------------------------\n\n // primeFactors :: Int -> [Int]\n const primeFactors = x => {\n const go = n => {\n const fs = take(1)(\n dropWhile(x => 0 != n % x)(\n enumFromTo(2)(\n floor(sqrt(n))\n )\n )\n );\n return 0 === fs.length ? [n] : fs.concat(\n go(floor(n / fs[0]))\n );\n };\n return go(x);\n };\n\n // sumDigits :: Int -> Int\n const sumDigits = n =>\n unfoldl(\n x => 0 === x ? (\n Nothing()\n ) : Just(quotRem(x)(10))\n )(n).reduce((a, x) => a + x, 0);\n\n\n // GENERIC --------------------------------------------\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a => b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // drop :: Int -> [a] -> [a]\n // drop :: Int -> String -> String\n const drop = n => xs =>\n xs.slice(n)\n\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n // dropWhile :: (Char -> Bool) -> String -> String\n const dropWhile = p => xs => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(i => i === lng || !p(xs[i]))(\n i => 1 + i\n )(0)\n ) : [];\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = m => n =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // floor :: Num -> Int\n const floor = Math.floor;\n\n\n // quotRem :: Int -> Int -> (Int, Int)\n const quotRem = m => n =>\n Tuple(Math.floor(m / n))(\n m % n\n );\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // sqrt :: Num -> Num\n const sqrt = n =>\n (0 <= n) ? Math.sqrt(n) : undefined;\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n => xs =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n\n // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\n const unfoldl = f => v => {\n let\n xr = [v, v],\n xs = [];\n while (true) {\n const mb = f(xr[0]);\n if (mb.Nothing) {\n return xs\n } else {\n xr = mb.Just;\n xs = [xr[1]].concat(xs);\n }\n }\n };\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = p => f => x => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n return main();\n})();"} {"title": "Solve a Holy Knight's tour", "language": "JavaScript", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "(() => {\n 'use strict';\n\n // problems :: [[String]]\n const problems = [\n [\n \" 000 \" //\n , \" 0 00 \" //\n , \" 0000000\" //\n , \"000 0 0\" //\n , \"0 0 000\" //\n , \"1000000 \" //\n , \" 00 0 \" //\n , \" 000 \" //\n ],\n [\n \"-----1-0-----\" //\n , \"-----0-0-----\" //\n , \"----00000----\" //\n , \"-----000-----\" //\n , \"--0--0-0--0--\" //\n , \"00000---00000\" //\n , \"--00-----00--\" //\n , \"00000---00000\" //\n , \"--0--0-0--0--\" //\n , \"-----000-----\" //\n , \"----00000----\" //\n , \"-----0-0-----\" //\n , \"-----0-0-----\" //\n ]\n ];\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n };\n\n // concat :: [[a]] -> [a] | [String] -> String\n const concat = xs =>\n xs.length > 0 ? (() => {\n const unit = typeof xs[0] === 'string' ? '' : [];\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // charColRow :: Char -> [String] -> Maybe (Int, Int)\n const charColRow = (c, rows) =>\n foldr((a, xs, iRow) =>\n a.nothing ? (() => {\n const mbiCol = elemIndex(c, xs);\n return mbiCol.nothing ? mbiCol : {\n just: [mbiCol.just, iRow],\n nothing: false\n };\n })() : a, {\n nothing: true\n }, rows);\n\n // 2 or more arguments\n // curry :: Function -> Function\n const curry = (f, ...args) => {\n const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :\n function () {\n return go(xs.concat(Array.from(arguments)));\n };\n return go([].slice.call(args, 1));\n };\n\n // elem :: Eq a => a -> [a] -> Bool\n const elem = (x, xs) => xs.indexOf(x) !== -1;\n\n // elemIndex :: Eq a => a -> [a] -> Maybe Int\n const elemIndex = (x, xs) => {\n const i = xs.indexOf(x);\n return {\n nothing: i === -1,\n just: i\n };\n };\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: Math.floor(n - m) + 1\n }, (_, i) => m + i);\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = (f, xs) => xs.filter(f);\n\n // findIndex :: (a -> Bool) -> [a] -> Maybe Int\n const findIndex = (f, xs) => {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n if (f(xs[i])) return {\n nothing: false,\n just: i\n };\n }\n return {\n nothing: true\n };\n };\n\n // foldl :: (b -> a -> b) -> b -> [a] -> b\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // foldr (a -> b -> b) -> b -> [a] -> b\n const foldr = (f, a, xs) => xs.reduceRight(f, a);\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = (f, xs) => {\n const dct = xs.slice(1)\n .reduce((a, x) => {\n const\n h = a.active.length > 0 ? a.active[0] : undefined,\n blnGroup = h !== undefined && f(h, x);\n return {\n active: blnGroup ? a.active.concat([x]) : [x],\n sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])\n };\n }, {\n active: xs.length > 0 ? [xs[0]] : [],\n sofar: []\n });\n return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);\n };\n\n // intercalate :: String -> [a] -> String\n const intercalate = (s, xs) => xs.join(s);\n\n // intersectBy::(a - > a - > Bool) - > [a] - > [a] - > [a]\n const intersectBy = (eq, xs, ys) =>\n (xs.length > 0 && ys.length > 0) ?\n xs.filter(x => ys.some(curry(eq)(x))) : [];\n\n // justifyRight :: Int -> Char -> Text -> Text\n const justifyRight = (n, cFiller, strText) =>\n n > strText.length ? (\n (cFiller.repeat(n) + strText)\n .slice(-n)\n ) : strText;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering)\n const mappendComparing = fs => (x, y) =>\n fs.reduce((ord, f) => {\n if (ord !== 0) return ord;\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : a > b ? 1 : 0\n }, 0);\n\n // maximumBy :: (a -> a -> Ordering) -> [a] -> a\n const maximumBy = (f, xs) =>\n xs.reduce((a, x) => a === undefined ? x : (\n f(x, a) > 0 ? x : a\n ), undefined);\n\n // min :: Ord a => a -> a -> a\n const min = (a, b) => b < a ? b : a;\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, a) => {\n let v = [a],\n o = [];\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) => xs.slice()\n .sort(f);\n\n // splitOn :: String -> String -> [String]\n const splitOn = (s, xs) => xs.split(s);\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, n);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // zip :: [a] -> [b] -> [(a,b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => [x, ys[i]]);\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) =>\n Array.from({\n length: min(xs.length, ys.length)\n }, (_, i) => f(xs[i], ys[i]));\n\n // HOLY KNIGHT's TOUR FUNCTIONS -------------------------------------------\n\n // kmoves :: (Int, Int) -> [(Int, Int)]\n const kmoves = ([x, y]) => map(\n ([a, b]) => [a + x, b + y], [\n [1, 2],\n [1, -2],\n [-1, 2],\n [-1, -2],\n [2, 1],\n [2, -1],\n [-2, 1],\n [-2, -1]\n ]);\n\n // rowPosns :: Int -> String -> [(Int, Int)]\n const rowPosns = (iRow, s) => {\n return foldl((a, x, i) => (elem(x, ['0', '1']) ? (\n a.concat([\n [i, iRow]\n ])\n ) : a), [], splitOn('', s));\n };\n\n // hash :: (Int, Int) -> String\n const hash = ([col, row]) => col.toString() + '.' + row.toString();\n\n // Start node, and degree-sorted cache of moves from each node\n // All node references are hash strings (for this cache)\n\n // problemModel :: [[String]] -> {cache: {nodeKey: [nodeKey], start:String}}\n const problemModel = boardLines => {\n const\n steps = foldl((a, xs, i) =>\n a.concat(rowPosns(i, xs)), [], boardLines),\n courseMoves = (xs, [x, y]) => intersectBy(\n ([a, b], [c, d]) => a === c && b === d, kmoves([x, y]), xs\n ),\n maybeStart = charColRow('1', boardLines);\n return {\n start: maybeStart.nothing ? '' : hash(maybeStart.just),\n boardWidth: boardLines.length > 0 ? boardLines[0].length : 0,\n stepCount: steps.length,\n cache: (() => {\n const moveCache = foldl((a, xy) => (\n a[hash(xy)] = map(hash, courseMoves(steps, xy)),\n a\n ), {}, steps),\n lstMoves = Object.keys(moveCache),\n dctDegree = foldl((a, k) =>\n (a[k] = moveCache[k].length,\n a), {}, lstMoves);\n\n return foldl((a, k) => (\n a[k] = sortBy(comparing(x => dctDegree[x]), moveCache[k]),\n a\n ), {}, lstMoves);\n })()\n };\n };\n\n // firstSolution :: {nodeKey: [nodeKey]} -> Int ->\n // nodeKey -> nodeKey -> [nodeKey] ->\n // -> {path::[nodeKey], pathLen::Int, found::Bool}\n const firstSolution = (dctMoves, intTarget, strStart, strNodeKey, path) => {\n const\n intPath = path.length,\n moves = dctMoves[strNodeKey];\n\n if ((intTarget - intPath) < 2 && elem(strStart, moves)) {\n return {\n nothing: false,\n just: [strStart, strNodeKey].concat(path),\n pathLen: intTarget\n };\n }\n\n const\n nexts = filter(k => !elem(k, path), moves),\n intNexts = nexts.length,\n lstFullPath = [strNodeKey].concat(path);\n\n // Until we find a full path back to start\n return until(\n x => (x.nothing === false || x.i >= intNexts),\n x => {\n const\n idx = x.i,\n dctSoln = firstSolution(\n dctMoves, intTarget, strStart, nexts[idx], lstFullPath\n );\n return {\n i: idx + 1,\n nothing: dctSoln.nothing,\n just: dctSoln.just,\n pathLen: dctSoln.pathLen\n };\n }, {\n nothing: true,\n just: [],\n i: 0\n }\n );\n };\n\n // maybeTour :: [String] -> {\n // nothing::Bool, Just::[nodeHash], i::Int: pathLen::Int }\n const maybeTour = trackLines => {\n const\n dctModel = problemModel(trackLines),\n strStart = dctModel.start;\n return strStart !== '' ? firstSolution(\n dctModel.cache, dctModel.stepCount, strStart, strStart, []\n ) : {\n nothing: true\n };\n };\n\n // showLine :: Int -> Int -> String -> Maybe (Int, Int) ->\n // [(Int, Int, String)] -> String\n const showLine = curry((intCell, strFiller, maybeStart, xs) => {\n const\n blnSoln = maybeStart.nothing,\n [startCol, startRow] = blnSoln ? [0, 0] : maybeStart.just;\n return foldl((a, [iCol, iRow, sVal], i, xs) => ({\n col: iCol + 1,\n txt: a.txt +\n concat(replicate((iCol - a.col) * intCell, strFiller)) +\n justifyRight(\n intCell, strFiller,\n (blnSoln ? sVal : (\n iRow === startRow &&\n iCol === startCol ? '1' : '0')\n )\n )\n }), {\n col: 0,\n txt: ''\n },\n xs\n )\n .txt\n });\n\n // solutionString :: [String] -> Int -> String\n const solutionString = (boardLines, iProblem) => {\n const\n dtePre = Date.now(),\n intCols = boardLines.length > 0 ? boardLines[0].length : 0,\n soln = maybeTour(boardLines),\n intMSeconds = Date.now() - dtePre;\n\n if (soln.nothing) return 'No solution found \u2026';\n\n const\n kCol = 0,\n kRow = 1,\n kSeq = 2,\n steps = soln.just,\n lstTriples = zipWith((h, n) => {\n const [col, row] = map(\n x => parseInt(x, 10), splitOn('.', h)\n );\n return [col, row, n.toString()];\n },\n steps,\n enumFromTo(1, soln.pathLen)),\n cellWidth = length(maximumBy(\n comparing(x => length(x[kSeq])), lstTriples\n )[kSeq]) + 1,\n lstGroups = groupBy(\n (a, b) => a[kRow] === b[kRow],\n sortBy(\n mappendComparing([x => x[kRow], x => x[kCol]]),\n lstTriples\n )),\n startXY = take(2, lstTriples[0]),\n strMap = 'PROBLEM ' + (parseInt(iProblem, 10) + 1) + '.\\n\\n' +\n unlines(map(showLine(cellWidth, ' ', {\n nothing: false,\n just: startXY\n }), lstGroups)),\n strSoln = 'First solution found in c. ' +\n intMSeconds + ' milliseconds:\\n\\n' +\n unlines(map(showLine(cellWidth, ' ', {\n nothing: true,\n just: startXY\n }), lstGroups)) + '\\n\\n';\n\n console.log(strSoln);\n return strMap + '\\n\\n' + strSoln;\n };\n\n // TEST -------------------------------------------------------------------\n return unlines(map(solutionString, problems));\n})();"} {"title": "Sparkline in unicode", "language": "JavaScript", "task": "A sparkline is a graph of successive values laid out horizontally \nwhere the height of the line is proportional to the values in succession.\n\n\n;Task:\nUse the following series of Unicode characters to create a program \nthat takes a series of numbers separated by one or more whitespace or comma characters \nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: '########'\n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input, \nhere on this page:\n# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \n:(note the mix of separators in this second case)!\n\n;Notes: \n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n:: \"0, 1, 19, 20\" -> ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n // sparkLine :: [Num] -> String\n const sparkLine = xs => {\n const hist = dataBins(8)(xs);\n return unlines([\n concat(map(\n i => '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588' [i],\n hist.indexes\n )),\n unwords(xs),\n [\n 'Min: ' + hist.min,\n 'Mean: ' + hist.mean.toFixed(2),\n 'Median: ' + hist.median,\n 'Max: ' + hist.max,\n ].join('\\t'),\n ''\n ]);\n };\n\n\n // dataBins :: Int -> [Num] ->\n // {indexes:: [Int], min:: Float, max:: Float,\n // range :: Float, lbounds :: [Float]}\n const dataBins = intBins => xs => {\n const\n iLast = intBins - 1,\n ys = sort(xs),\n mn = ys[0],\n mx = last(ys),\n rng = mx - mn,\n w = rng / intBins,\n lng = xs.length,\n mid = lng / 2,\n lbounds = map(\n i => mn + (w * i),\n enumFromTo(1, iLast)\n );\n return {\n indexes: map(\n x => {\n const mb = findIndex(b => b > x, lbounds);\n return mb.Nothing ? (\n iLast\n ) : mb.Just;\n },\n xs\n ),\n lbounds: lbounds,\n min: mn,\n median: even(lng) ? (\n sum([ys[mid - 1], ys[mid]]) / 2\n ) : ys[Math.floor(mid)],\n mean: sum(xs) / lng,\n max: mx,\n range: rng\n };\n };\n\n // numbersFromString :: String -> [Float]\n const numbersFromString = s =>\n map(x => parseFloat(x, 10),\n s.split(/[,\\s]+/)\n );\n\n return unlines(map(\n compose(sparkLine, numbersFromString),\n [\n '0, 1, 19, 20',\n '0, 999, 4000, 4999, 7000, 7999',\n '1 2 3 4 5 6 7 8 7 6 5 4 3 2 1',\n '1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5'\n ]\n ));\n };\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n\n // enumFromTo :: (Int, Int) -> [Int]\n const enumFromTo = (m, n) =>\n Array.from({\n length: 1 + n - m\n }, (_, i) => m + i);\n\n // even :: Int -> Bool\n const even = n => 0 === n % 2;\n\n // last :: [a] -> a\n const last = xs =>\n 0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) =>\n (Array.isArray(xs) ? (\n xs\n ) : xs.split('')).map(f);\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs => xs.slice()\n .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));\n\n\n // findIndex :: (a -> Bool) -> [a] -> Maybe Int\n const findIndex = (p, xs) => {\n const\n i = (\n 'string' !== typeof xs ? (\n xs\n ) : xs.split('')\n ).findIndex(p);\n return -1 !== i ? (\n Just(i)\n ) : Nothing();\n };\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // unwords :: [String] -> String\n const unwords = xs => xs.join(' ');\n\n // MAIN ---\n return main();\n})();"} {"title": "Split a character string based on change of character", "language": "JavaScript from Haskell", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "(() => {\n \"use strict\";\n\n // ----------- SPLIT ON CHARACTER CHANGES ------------\n const main = () =>\n group(\"gHHH5YY++///\\\\\")\n .map(x => x.join(\"\"))\n .join(\", \");\n\n\n // --------------------- GENERIC ---------------------\n\n // group :: [a] -> [[a]]\n const group = xs =>\n // A list of lists, each containing only\n // elements equal under (===), such that the\n // concatenation of these lists is xs.\n groupBy(a => b => a === b)(xs);\n\n\n // groupBy :: (a -> a -> Bool) [a] -> [[a]]\n const groupBy = eqOp =>\n // A list of lists, each containing only elements\n // equal under the given equality operator,\n // such that the concatenation of these lists is xs.\n xs => 0 < xs.length ? (() => {\n const [h, ...t] = xs;\n const [groups, g] = t.reduce(\n ([gs, a], x) => eqOp(x)(a[0]) ? (\n Tuple(gs)([...a, x])\n ) : Tuple([...gs, a])([x]),\n Tuple([])([h])\n );\n\n return [...groups, g];\n })() : [];\n\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: \"Tuple\",\n \"0\": a,\n \"1\": b,\n length: 2,\n *[Symbol.iterator]() {\n for (const k in this) {\n if (!isNaN(k)) {\n yield this[k];\n }\n }\n }\n });\n\n // MAIN ---\n return main();\n})();"} {"title": "Square but not cube", "language": "JavaScript", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n unlines(map(\n x => x.toString() + (\n isCube(x) ? (\n ` (cube of ${cubeRootInt(x)} and square of ${\n Math.pow(x, 1/2)\n })`\n ) : ''\n ),\n map(x => x * x, enumFromTo(1, 33))\n ));\n\n // isCube :: Int -> Bool\n const isCube = n =>\n n === Math.pow(cubeRootInt(n), 3);\n\n // cubeRootInt :: Int -> Int\n const cubeRootInt = n => Math.round(Math.pow(n, 1 / 3));\n \n\n // GENERIC FUNCTIONS ----------------------------------\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} {"title": "Stern-Brocot sequence", "language": "JavaScript", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () => {\n\n // sternBrocot :: Generator [Int]\n const sternBrocot = () => {\n const go = xs => {\n const x = snd(xs);\n return tail(append(xs, [fst(xs) + x, x]));\n };\n return fmapGen(head, iterate(go, [1, 1]));\n };\n\n\n // TESTS ------------------------------------------\n const\n sbs = take(1200, sternBrocot()),\n ixSB = zip(sbs, enumFrom(1));\n\n return unlines(map(\n JSON.stringify,\n [\n take(15, sbs),\n take(10,\n map(listFromTuple,\n nubBy(\n on(eq, fst),\n sortBy(\n comparing(fst),\n takeWhile(x => 12 !== fst(x), ixSB)\n )\n )\n )\n ),\n listFromTuple(\n take(1, dropWhile(x => 100 !== fst(x), ixSB))[0]\n ),\n all(tpl => 1 === gcd(fst(tpl), snd(tpl)),\n take(1000, zip(sbs, tail(sbs)))\n )\n ]\n ));\n };\n\n // GENERIC ABSTRACTIONS -------------------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // | Absolute value.\n\n // abs :: Num -> Num\n const abs = Math.abs;\n\n // Determines whether all elements of the structure\n // satisfy the predicate.\n\n // all :: (a -> Bool) -> [a] -> Bool\n const all = (p, xs) => xs.every(p);\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = (xs, ys) => xs.concat(ys);\n\n // chr :: Int -> Char\n const chr = String.fromCodePoint;\n\n // comparing :: (a -> b) -> (a -> a -> Ordering)\n const comparing = f =>\n (x, y) => {\n const\n a = f(x),\n b = f(y);\n return a < b ? -1 : (a > b ? 1 : 0);\n };\n\n // dropWhile :: (a -> Bool) -> [a] -> [a]\n // dropWhile :: (Char -> Bool) -> String -> String\n const dropWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // enumFrom :: a -> [a]\n function* enumFrom(x) {\n let v = x;\n while (true) {\n yield v;\n v = succ(v);\n }\n }\n\n // eq (==) :: Eq a => a -> a -> Bool\n const eq = (a, b) => {\n const t = typeof a;\n return t !== typeof b ? (\n false\n ) : 'object' !== t ? (\n 'function' !== t ? (\n a === b\n ) : a.toString() === b.toString()\n ) : (() => {\n const aks = Object.keys(a);\n return aks.length !== Object.keys(b).length ? (\n false\n ) : aks.every(k => eq(a[k], b[k]));\n })();\n };\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n function* fmapGen(f, gen) {\n const g = gen;\n let v = take(1, g)[0];\n while (0 < v.length) {\n yield(f(v))\n v = take(1, g)[0]\n }\n }\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // gcd :: Int -> Int -> Int\n const gcd = (x, y) => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // head :: [a] -> a\n const head = xs => xs.length ? xs[0] : undefined;\n\n // isChar :: a -> Bool\n const isChar = x =>\n ('string' === typeof x) && (1 === x.length);\n\n // iterate :: (a -> a) -> a -> Gen [a]\n function* iterate(f, x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n }\n\n // Returns Infinity over objects without finite length\n // this enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs => xs.length || Infinity;\n\n // listFromTuple :: (a, a ...) -> [a]\n const listFromTuple = tpl =>\n Array.from(tpl);\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // nubBy :: (a -> a -> Bool) -> [a] -> [a]\n const nubBy = (p, xs) => {\n const go = xs => 0 < xs.length ? (() => {\n const x = xs[0];\n return [x].concat(\n go(xs.slice(1)\n .filter(y => !p(x, y))\n )\n )\n })() : [];\n return go(xs);\n };\n\n // e.g. sortBy(on(compare,length), xs)\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n const on = (f, g) => (a, b) => f(g(a), g(b));\n\n // ord :: Char -> Int\n const ord = c => c.codePointAt(0);\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // sortBy :: (a -> a -> Ordering) -> [a] -> [a]\n const sortBy = (f, xs) =>\n xs.slice()\n .sort(f);\n\n // succ :: Enum a => a -> a\n const succ = x =>\n isChar(x) ? (\n chr(1 + ord(x))\n ) : isNaN(x) ? (\n undefined\n ) : 1 + x;\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n xs.constructor.constructor.name !== 'GeneratorFunction' ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // takeWhile :: (a -> Bool) -> [a] -> [a]\n // takeWhile :: (Char -> Bool) -> String -> String\n const takeWhile = (p, xs) =>\n xs.constructor.constructor.name !==\n 'GeneratorFunction' ? (() => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n 0,\n until(\n i => lng === i || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n })() : takeWhileGen(p, xs);\n\n // takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]\n const takeWhileGen = (p, xs) => {\n const ys = [];\n let\n nxt = xs.next(),\n v = nxt.value;\n while (!nxt.done && p(v)) {\n ys.push(v);\n nxt = xs.next();\n v = nxt.value\n }\n return ys;\n };\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n const lng = length(xs);\n return (0 < lng) ? (\n lng < Infinity ? (\n Just(Tuple(xs[0], xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1, xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0], xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // Use of `take` and `length` here allows for zipping with non-finite\n // lists - i.e. generators like cycle, repeat, iterate.\n\n // zip :: [a] -> [b] -> [(a, b)]\n const zip = (xs, ys) => {\n const lng = Math.min(length(xs), length(ys));\n return Infinity !== lng ? (() => {\n const bs = take(lng, ys);\n return take(lng, xs).map((x, i) => Tuple(x, bs[i]));\n })() : zipGen(xs, ys);\n };\n\n // zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]\n const zipGen = (ga, gb) => {\n function* go(ma, mb) {\n let\n a = ma,\n b = mb;\n while (!a.Nothing && !b.Nothing) {\n let\n ta = a.Just,\n tb = b.Just\n yield(Tuple(fst(ta), fst(tb)));\n a = uncons(snd(ta));\n b = uncons(snd(tb));\n }\n }\n return go(uncons(ga), uncons(gb));\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Strip control codes and extended characters from a string", "language": "JavaScript", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "(function (strTest) {\n\n // s -> s\n function strip(s) {\n return s.split('').filter(function (x) {\n var n = x.charCodeAt(0);\n \n return 31 < n && 127 > n;\n }).join('');\n }\n\n return strip(strTest);\n\n})(\"\\ba\\x00b\\n\\rc\\fd\\xc3\");"} {"title": "Substring/Top and tail", "language": "JavaScript", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "alert(\"knight\".slice(1)); // strip first character\nalert(\"socks\".slice(0, -1)); // strip last character\nalert(\"brooms\".slice(1, -1)); // strip both first and last characters"} {"title": "Sum and product puzzle", "language": "JavaScript from Haskell", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "(() => {\n \"use strict\";\n\n // ------------- SUM AND PRODUCT PUZZLE --------------\n\n // main :: IO ()\n const main = () => {\n const\n // xs :: [Int]\n xs = enumFromTo(1)(100),\n\n // s1 s2, s3, s4 :: [(Int, Int)]\n s1 = xs.flatMap(\n x => xs.flatMap(y =>\n (1 < x) && (x < y) && 100 > (x + y) ? [\n [x, y]\n ] : []\n )\n ),\n s2 = s1.filter(\n p => sumEq(p, s1).every(\n q => 1 < mulEq(q, s1).length\n )\n ),\n s3 = s2.filter(\n p => 1 === intersectBy(pairEQ)(\n mulEq(p, s1)\n )(s2).length\n );\n\n return s3.filter(\n p => 1 === intersectBy(pairEQ)(\n sumEq(p, s1)\n )(s3).length\n );\n };\n\n // ---------------- PROBLEM FUNCTIONS ----------------\n\n // add, mul :: (Int, Int) -> Int\n const\n add = xy => xy[0] + xy[1],\n mul = xy => xy[0] * xy[1],\n\n // sumEq, mulEq :: (Int, Int) ->\n // [(Int, Int)] -> [(Int, Int)]\n sumEq = (p, s) => {\n const addP = add(p);\n\n return s.filter(q => add(q) === addP);\n },\n mulEq = (p, s) => {\n const mulP = mul(p);\n\n return s.filter(q => mul(q) === mulP);\n },\n\n // pairEQ :: ((a, a) -> (a, a)) -> Bool\n pairEQ = a => b => (\n a[0] === b[0]\n ) && (a[1] === b[1]);\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\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 // intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]\n const intersectBy = eqFn =>\n // The intersection of the lists xs and ys\n // in terms of the equality defined by eq.\n xs => ys => xs.filter(\n x => ys.some(eqFn(x))\n );\n\n // MAIN ---\n return main();\n})();"} {"title": "Sum digits of an integer", "language": "JavaScript", "task": "Take a Natural Number in a given base and return the sum of its digits:\n:* '''1'''10 sums to '''1'''\n:* '''1234'''10 sums to '''10'''\n:* '''fe'''16 sums to '''29'''\n:* '''f0e'''16 sums to '''29'''\n\n", "solution": "function sumDigits(n) {\n\tn += ''\n\tfor (var s=0, i=0, e=n.length; i')\n"} {"title": "Sum multiples of 3 and 5", "language": "JavaScript", "task": "The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. \n\nShow output for ''n'' = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "(function (lstFactors, intExponent) {\n\n // [n] -> n -> n\n function sumMultiplesBelow(lstIntegers, limit) {\n return range(1, limit - 1).filter(function (x) {\n return isMultiple(lstIntegers, x);\n }).reduce(function (a, n) {\n return a + n;\n }, 0)\n }\n\n // [n] -> n -> bool\n function isMultiple(lst, n) {\n var i = lng;\n while (i--)\n if (n % (lst[i]) === 0) return true;\n return false;\n }\n\n // [m..n]\n function range(m, n) {\n var a = Array(n - m + 1),\n i = n + 1;\n while (i--) a[i - 1] = i;\n return a;\n }\n\n\n /* TESTING */\n\n // [[a]] -> bool -> s -> s\n function wikiTable(lstRows, blnHeaderRow, strStyle) {\n return '{| class=\"wikitable\" ' + (\n strStyle ? 'style=\"' + strStyle + '\"' : ''\n ) + lstRows.map(function (lstRow, iRow) {\n var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');\n\n return '\\n|-\\n' + strDelim + ' ' + lstRow.map(function (v) {\n return typeof v === 'undefined' ? ' ' : v;\n }).join(' ' + strDelim + strDelim + ' ');\n }).join('') + '\\n|}';\n }\n\n var lng = lstFactors.length,\n lstSorted = lstFactors.slice(0).sort();\n\n var lstTable = [['Below', 'Sum']].concat(\n range(1, intExponent).map(function (x) {\n var pwr = Math.pow(10, x);\n\n return ['10^' + x, sumMultiplesBelow(lstSorted, pwr)];\n })\n );\n\n return 'For ' + JSON.stringify(lstFactors) + ':\\n\\n' +\n wikiTable(lstTable, true) + '\\n\\n' +\n JSON.stringify(lstTable);\n\n})([3, 5], 8);"} {"title": "Sum of elements below main diagonal of matrix", "language": "JavaScript", "task": "Find and display the sum of elements that are below the main diagonal of a matrix.\n\nThe matrix should be a square matrix.\n\n\n::: --- Matrix to be used: ---\n\n [[1,3,7,8,10],\n [2,4,16,14,4],\n [3,1,9,18,11],\n [12,14,17,18,20],\n [7,1,3,9,5]] \n\n", "solution": "(() => {\n \"use strict\";\n\n // -------- LOWER TRIANGLE OF A SQUARE MATRIX --------\n\n // lowerTriangle :: [[a]] -> Either String [[a]]\n const lowerTriangle = matrix =>\n // Either a message, if the matrix is not square,\n // or the lower triangle of the matrix.\n isSquare(matrix) ? (\n Right(\n matrix.reduce(\n ([n, rows], xs) => [\n 1 + n,\n rows.concat([xs.slice(0, n)])\n ],\n [0, []]\n )[1]\n )\n ) : Left(\"Not a square matrix\");\n\n\n // isSquare :: [[a]] -> Bool\n const isSquare = rows => {\n // True if the length of every row in the matrix\n // matches the number of rows in the matrix.\n const n = rows.length;\n\n return rows.every(x => n === x.length);\n };\n\n // ---------------------- TEST -----------------------\n const main = () =>\n either(\n msg => `Lower triangle undefined :: ${msg}`\n )(\n rows => sum([].concat(...rows))\n )(\n lowerTriangle([\n [1, 3, 7, 8, 10],\n [2, 4, 16, 14, 4],\n [3, 1, 9, 18, 11],\n [12, 14, 17, 18, 20],\n [7, 1, 3, 9, 5]\n ])\n );\n\n // --------------------- GENERIC ---------------------\n\n // Left :: a -> Either a b\n const Left = x => ({\n type: \"Either\",\n Left: x\n });\n\n\n // Right :: b -> Either a b\n const Right = x => ({\n type: \"Either\",\n Right: x\n });\n\n\n // either :: (a -> c) -> (b -> c) -> Either a b -> c\n const either = fl =>\n // Application of the function fl to the\n // contents of any Left value in e, or\n // the application of fr to its Right value.\n fr => e => e.Left ? (\n fl(e.Left)\n ) : fr(e.Right);\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n // MAIN ---\n return main();\n})();"} {"title": "Sum to 100", "language": "JavaScript from Haskell", "task": "Find solutions to the ''sum to one hundred'' puzzle.\n\n\nAdd (insert) the mathematical\noperators '''+''' or '''-''' (plus\nor minus) before any of the digits in the\ndecimal numeric string '''123456789''' such that the\nresulting mathematical expression adds up to a\nparticular sum (in this iconic case, '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* Show all solutions that sum to '''100''' \n:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)\n:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task\n:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)\n\n++ (where ''infinity'' would be a relatively small 123,456,789)\n\n\nAn example of a sum that can't be expressed (within the rules of this task) is: '''5074'''\n(which, of course, isn't the lowest positive sum that can't be expressed).\n\n", "solution": "(() => {\n 'use strict';\n\n // GENERIC FUNCTIONS ----------------------------------------------------\n\n // permutationsWithRepetition :: Int -> [a] -> [[a]]\n const permutationsWithRepetition = (n, as) =>\n as.length > 0 ? (\n foldl1(curry(cartesianProduct)(as), replicate(n, as))\n ) : [];\n\n // cartesianProduct :: [a] -> [b] -> [[a, b]]\n const cartesianProduct = (xs, ys) =>\n [].concat.apply([], xs.map(x =>\n [].concat.apply([], ys.map(y => [[x].concat(y)]))));\n\n // curry :: ((a, b) -> c) -> a -> b -> c\n const curry = f => a => b => f(a, b);\n\n // flip :: (a -> b -> c) -> b -> a -> c\n const flip = f => (a, b) => f.apply(null, [b, a]);\n\n // foldl1 :: (a -> a -> a) -> [a] -> a\n const foldl1 = (f, xs) =>\n xs.length > 0 ? xs.slice(1)\n .reduce(f, xs[0]) : [];\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, a) => {\n let v = [a],\n o = [];\n if (n < 1) return o;\n while (n > 1) {\n if (n & 1) o = o.concat(v);\n n >>= 1;\n v = v.concat(v);\n }\n return o.concat(v);\n };\n\n // group :: Eq a => [a] -> [[a]]\n const group = xs => groupBy((a, b) => a === b, xs);\n\n // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\n const groupBy = (f, xs) => {\n const dct = xs.slice(1)\n .reduce((a, x) => {\n const\n h = a.active.length > 0 ? a.active[0] : undefined,\n blnGroup = h !== undefined && f(h, x);\n\n return {\n active: blnGroup ? a.active.concat(x) : [x],\n sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])\n };\n }, {\n active: xs.length > 0 ? [xs[0]] : [],\n sofar: []\n });\n return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);\n };\n\n // compare :: a -> a -> Ordering\n const compare = (a, b) => a < b ? -1 : (a > b ? 1 : 0);\n\n // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c\n const on = (f, g) => (a, b) => f(g(a), g(b));\n\n // nub :: [a] -> [a]\n const nub = xs => nubBy((a, b) => a === b, xs);\n\n // nubBy :: (a -> a -> Bool) -> [a] -> [a]\n const nubBy = (p, xs) => {\n const x = xs.length ? xs[0] : undefined;\n\n return x !== undefined ? [x].concat(\n nubBy(p, xs.slice(1)\n .filter(y => !p(x, y)))\n ) : [];\n };\n\n // find :: (a -> Bool) -> [a] -> Maybe a\n const find = (f, xs) => {\n for (var i = 0, lng = xs.length; i < lng; i++) {\n if (f(xs[i], i)) return xs[i];\n }\n return undefined;\n }\n\n // Int -> [a] -> [a]\n const take = (n, xs) => xs.slice(0, n);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // show :: a -> String\n const show = x => JSON.stringify(x); //, null, 2);\n\n // head :: [a] -> a\n const head = xs => xs.length ? xs[0] : undefined;\n\n // tail :: [a] -> [a]\n const tail = xs => xs.length ? xs.slice(1) : undefined;\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n\n // SIGNED DIGIT SEQUENCES (mapped to sums and to strings)\n\n // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )\n // asSum :: [Sign] -> Int\n const asSum = xs => {\n const dct = xs.reduceRight((a, sign, i) => {\n const d = i + 1; // zero-based index to [1-9] positions\n if (sign !== 0) { // Sum increased, digits cleared\n return {\n digits: [],\n n: a.n + (sign * parseInt([d].concat(a.digits)\n .join(''), 10))\n };\n } else return { // Digits extended, sum unchanged\n digits: [d].concat(a.digits),\n n: a.n\n };\n }, {\n digits: [],\n n: 0\n });\n return dct.n + (dct.digits.length > 0 ? (\n parseInt(dct.digits.join(''), 10)\n ) : 0);\n };\n\n // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )\n // asString :: [Sign] -> String\n const asString = xs => {\n const ns = xs.reduce((a, sign, i) => {\n const d = (i + 1)\n .toString();\n return (sign === 0 ? (\n a + d\n ) : (a + (sign > 0 ? ' +' : ' -') + d));\n }, '');\n\n return ns[0] === '+' ? tail(ns) : ns;\n };\n\n\n // SUM T0 100 ------------------------------------------------------------\n\n // universe :: [[Sign]]\n const universe = permutationsWithRepetition(9, [0, 1, -1])\n .filter(x => x[0] !== 1);\n\n // allNonNegativeSums :: [Int]\n const allNonNegativeSums = universe.map(asSum)\n .filter(x => x >= 0)\n .sort();\n\n // uniqueNonNegativeSums :: [Int]\n const uniqueNonNegativeSums = nub(allNonNegativeSums);\n\n\n return [\n \"Sums to 100:\\n\",\n unlines(universe.filter(x => asSum(x) === 100)\n .map(asString)),\n\n \"\\n\\n10 commonest sums (sum, followed by number of routes to it):\\n\",\n show(take(10, group(allNonNegativeSums)\n .sort(on(flip(compare), length))\n .map(xs => [xs[0], xs.length]))),\n\n \"\\n\\nFirst positive integer not expressible as a sum of this kind:\\n\",\n show(find(\n (x, i) => x !== i,\n uniqueNonNegativeSums.sort(compare)\n ) - 1), // i is the the zero-based Array index.\n\n \"\\n10 largest sums:\\n\",\n show(take(10, uniqueNonNegativeSums.sort(flip(compare))))\n ].join('\\n') + '\\n';\n})();"} {"title": "Sum to 100", "language": "JavaScript from AWK", "task": "Find solutions to the ''sum to one hundred'' puzzle.\n\n\nAdd (insert) the mathematical\noperators '''+''' or '''-''' (plus\nor minus) before any of the digits in the\ndecimal numeric string '''123456789''' such that the\nresulting mathematical expression adds up to a\nparticular sum (in this iconic case, '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* Show all solutions that sum to '''100''' \n:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)\n:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task\n:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)\n\n++ (where ''infinity'' would be a relatively small 123,456,789)\n\n\nAn example of a sum that can't be expressed (within the rules of this task) is: '''5074'''\n(which, of course, isn't the lowest positive sum that can't be expressed).\n\n", "solution": "SumTo100();\n\nfunction SumTo100()\n{ \n var \n ADD = 0, \n SUB = 1, \n JOIN = 2;\n \n var \n nexpr = 13122; \n\n function out(something) \n { \n WScript.Echo(something); \n }\n\n function evaluate(code)\n {\n var \n value = 0, \n number = 0, \n power = 1;\n\n for ( var k = 9; k >= 1; k-- )\n {\n number = power*k + number;\n switch( code % 3 )\n {\n case ADD: value = value + number; number = 0; power = 1; break;\n case SUB: value = value - number; number = 0; power = 1; break;\n case JOIN: power = power * 10 ; break;\n }\n code = Math.floor(code/3);\n }\n return value; \n }\n\n function print(code)\n {\n var \n s = \"\";\n var \n a = 19683,\n b = 6561; \n \n for ( var k = 1; k <= 9; k++ )\n {\n switch( Math.floor( (code % a) / b ) ){\n case ADD: if ( k > 1 ) s = s + '+'; break;\n case SUB: s = s + '-'; break;\n }\n a = b;\n b = Math.floor(b/3);\n s = s + String.fromCharCode(0x30+k);\n } \n out(evaluate(code) + \" = \" + s);\n }\n \n function comment(commentString)\n {\n out(\"\");\n out(commentString);\n out(\"\"); \n }\n \n comment(\"Show all solutions that sum to 100\");\n for ( var i = 0; i < nexpr; i++) \n if ( evaluate(i) == 100 ) \n print(i); \n \n comment(\"Show the sum that has the maximum number of solutions\"); \n var stat = {};\n for ( var i = 0; i < nexpr; i++ )\n {\n var sum = evaluate(i);\n if (stat[sum])\n stat[sum]++;\n else\n stat[sum] = 1;\n }\n \n var best = 0;\n var nbest = -1;\n for ( var i = 0; i < nexpr; i++ )\n {\n var sum = evaluate(i);\n if ( sum > 0 )\n if ( stat[sum] > nbest )\n {\n best = i; \n nbest = stat[sum];\n }\n }\n out(\"\" + evaluate(best) + \" has \" + nbest + \" solutions\");\n \n comment(\"Show the lowest positive number that can't be expressed\");\n for ( var i = 0; i <= 123456789; i++ )\n {\n for ( var j = 0; j < nexpr; j++) \n if ( i == evaluate(j) ) break; \n if ( i != evaluate(j) ) break;\n }\n out(i);\n \n comment(\"Show the ten highest numbers that can be expressed\");\n var limit = 123456789 + 1;\n for ( i = 1; i <= 10; i++ ) \n {\n var best = 0;\n for ( var j = 0; j < nexpr; j++)\n {\n var test = evaluate(j);\n if ( test < limit && test > best ) \n best = test;\n }\n for ( var j = 0; j < nexpr; j++)\n if ( evaluate(j) == best ) print(j);\n limit = best;\n }\n \n}\n"} {"title": "Summarize and say sequence", "language": "Javascript", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "function selfReferential(n) {\n n = n.toString();\n let res = [n];\n const makeNext = (n) => {\n let matchs = {\n '9':0,'8':0,'7':0,'6':0,'5':0,'4':0,'3':0,'2':0,'1':0,'0':0}, res = [];\n for(let index=0;index=0;index--)\n if(matchs[index]>0)\n res.push(matchs[index],index);\n return res.join(\"\").toString();\n }\n for(let i=0;i<10;i++)\n res.push(makeNext(res[res.length-1]));\n return [...new Set(res)];\n}\n"} {"title": "Superellipse", "language": "JavaScript", "task": "A superellipse is a geometric figure defined as the set of all points (x, y) with \n\n\n::: \\left|\\frac{x}{a}\\right|^n\\! + \\left|\\frac{y}{b}\\right|^n\\! = 1,\n\nwhere ''n'', ''a'', and ''b'' are positive numbers.\n\n\n;Task\nDraw a superellipse with n = 2.5, and a = b = 200\n\n", "solution": "var n = 2.5, a = 200, b = 200, ctx;\n\nfunction point( x, y ) {\n ctx.fillRect( x, y, 1, 1);\n}\n\nfunction start() {\n var can = document.createElement('canvas');\n can.width = can.height = 600;\n ctx = can.getContext( \"2d\" );\n ctx.rect( 0, 0, can.width, can.height );\n ctx.fillStyle = \"#000000\"; ctx.fill();\n document.body.appendChild( can );\n\n ctx.fillStyle = \"#ffffff\";\n for( var t = 0; t < 1000; t += .1 ) {\n x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) );\n y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) );\n\n point( x + ( can.width >> 1 ), y + ( can.height >> 1 ) );\n }\n}\n"} {"title": "Teacup rim text", "language": "JavaScript", "task": "On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). \n\nIt occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: unixdict.txt. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) \n\nHaving listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. \n\nThe words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "===Set() objects===\nReading a local dictionary with the macOS JS for Automation library:\n"} {"title": "Temperature conversion", "language": "JavaScript", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "var k2c = k => k - 273.15\nvar k2r = k => k * 1.8\nvar k2f = k => k2r(k) - 459.67\n\nNumber.prototype.toMaxDecimal = function (d) {\n return +this.toFixed(d) + ''\n}\n\nfunction kCnv(k) {\n document.write( k,'K\u00b0 = ', k2c(k).toMaxDecimal(2),'C\u00b0 = ', k2r(k).toMaxDecimal(2),'R\u00b0 = ', k2f(k).toMaxDecimal(2),'F\u00b0
' ) \n}\n \nkCnv(21)\nkCnv(295)"} {"title": "The Name Game", "language": "JavaScript", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "function singNameGame(name) {\n\n // normalize name\n name = name.toLowerCase();\n name = name[0].toUpperCase() + name.slice(1);\n\n // ... and sometimes y\n // let's pray this works\n let firstVowelPos = (function() {\n let vowels =\n 'aeiou\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00f9\u00fa\u00fb\u00fc\u0101\u0103\u0105\u0113\u0115\u0117\u0119\u011b\u0129\u012b\u012d\u012f\u0131\u0133\u014d\u014f\u0151\u0153\u0169\u016b\u016d\u016f\u0171\u0173'\n .split('');\n function isVowel(char) {\n return vowels.indexOf(char) >= 0;\n }\n if (isVowel(name[0].toLowerCase())) return 0;\n if (name[0] == 'Y' && !isVowel(name[1])) return 0;\n if (name[0] == 'Y' && isVowel(name[1])) return 1;\n vowels = vowels.concat(vowels, 'y\u00ff\u00fd'.split(''));\n for (let i = 1; i < name.length; i++)\n if (isVowel(name[i])) return i;\n })();\n\n let init = name[0].toLowerCase(),\n trunk = name.slice(firstVowelPos).toLowerCase(),\n b = trunk, f = trunk, m = trunk;\n\n switch (init) {\n case 'b': f = 'f' + trunk; m = 'm' + trunk; break;\n case 'f': b = 'b' + trunk; m = 'm' + trunk; break;\n case 'm': b = 'b' + trunk; f = 'f' + trunk; break;\n default: b = 'b' + trunk; f = 'f' + trunk; m = 'm' + trunk;\n }\n\n return `\n

${name}, ${name}, bo-${b}
\n Banana-fana fo-${f}
\n Fee-fi-fo-mo-${m}
\n ${name}!

\n `\n}\n\n// testing\nlet names =\n 'Gary Earl Billy Felix Mary Christine Brian Yvonne Yannick'.split(' ');\nfor (let i = 0; i < names.length; i++)\n document.write(singNameGame(names[i]));"} {"title": "The Twelve Days of Christmas", "language": "JavaScript", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "JSON.stringify(\n (function (\n strPrepn,\n strHoliday,\n strUnit,\n strRole,\n strProcess,\n strRecipient\n ) {\n var lstOrdinal =\n 'first second third fourth fifth sixth\\\n seventh eighth ninth tenth eleventh twelfth'\n .split(/\\s+/),\n lngUnits = lstOrdinal.length,\n\n lstGoods =\n 'A partridge in a pear tree.\\\n Two turtle doves\\\n Three french hens\\\n Four calling birds\\\n Five golden rings\\\n Six geese a-laying\\\n Seven swans a-swimming\\\n Eight maids a-milking\\\n Nine ladies dancing\\\n Ten lords a-leaping\\\n Eleven pipers piping\\\n Twelve drummers drumming'\n .split(/\\s{2,}/),\n\n lstReversed = (function () {\n var lst = lstGoods.slice(0);\n return (lst.reverse(), lst);\n })(),\n\n strProvenance = [strRole, strProcess, strRecipient + ':'].join(' '),\n\n strPenultimate = lstReversed[lngUnits - 2] + ' and',\n strFinal = lstGoods[0];\n\n return lstOrdinal.reduce(\n function (sofar, day, i) {\n return sofar.concat(\n [\n [\n [ // abstraction of line 1\n strPrepn,\n 'the',\n lstOrdinal[i],\n strUnit,\n 'of',\n strHoliday\n ].join(' '),\n strProvenance\n ].concat( // reversed descent through memory\n (i > 1 ? [lstGoods[i]] : []).concat(\n lstReversed.slice(\n lngUnits - i,\n lngUnits - 2\n )\n ).concat( // penultimate line ends with 'and'\n [\n strPenultimate,\n strFinal\n ].slice(i ? 0 : 1)\n )\n )\n ]\n );\n }, []\n );\n })(\n 'On', 'Christmas', 'day', 'my true love', 'gave to', 'me'\n ), null, 2\n);"} {"title": "Thue-Morse", "language": "JavaScript from Java", "task": "Create a Thue-Morse sequence.\n\n\n;See also\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: [[Fairshare between two and more]]\n\n", "solution": "(() => {\n 'use strict';\n\n // thueMorsePrefixes :: () -> [[Int]]\n const thueMorsePrefixes = () =>\n iterate(\n ap(append)(\n map(x => 1 - x)\n )\n )([0]);\n\n // ----------------------- TEST -----------------------\n const main = () =>\n // Fifth iteration.\n // 2 ^ 5 = 32 terms of the Thue-Morse sequence.\n showList(\n index(thueMorsePrefixes())(\n 5\n )\n );\n\n\n // ---------------- GENERIC FUNCTIONS -----------------\n\n // ap :: (a -> b -> c) -> (a -> b) -> a -> c\n const ap = f =>\n // Applicative instance for functions.\n // f(x) applied to g(x).\n g => x => f(x)(\n g(x)\n );\n\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = xs =>\n // A list or string composed by\n // the concatenation of two others.\n ys => xs.concat(ys);\n\n\n // index (!!) :: Generator (Int, a) -> Int -> Maybe a\n const index = xs =>\n i => (take(i)(xs), xs.next().value);\n\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n function*(x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n };\n\n\n // map :: (a -> b) -> [a] -> [b]\n const map = f =>\n // The list obtained by applying f\n // to each element of xs.\n // (The image of xs under f).\n xs => xs.map(f);\n\n\n // showList :: [a] -> String\n const showList = xs =>\n '[' + xs.map(x => x.toString())\n .join(',')\n .replace(/[\\\"]/g, '') + ']';\n\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // MAIN ---\n return main();\n})();"} {"title": "Top rank per group", "language": "JavaScript", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "var data = [\n {name: \"Tyler Bennett\", id: \"E10297\", salary: 32000, dept: \"D101\"},\n {name: \"John Rappl\", id: \"E21437\", salary: 47000, dept: \"D050\"},\n {name: \"George Woltman\", id: \"E00127\", salary: 53500, dept: \"D101\"},\n {name: \"Adam Smith\", id: \"E63535\", salary: 18000, dept: \"D202\"},\n {name: \"Claire Buckman\", id: \"E39876\", salary: 27800, dept: \"D202\"},\n {name: \"David McClellan\", id: \"E04242\", salary: 41500, dept: \"D101\"},\n {name: \"Rich Holcomb\", id: \"E01234\", salary: 49500, dept: \"D202\"},\n {name: \"Nathan Adams\", id: \"E41298\", salary: 21900, dept: \"D050\"},\n {name: \"Richard Potter\", id: \"E43128\", salary: 15900, dept: \"D101\"},\n {name: \"David Motsinger\", id: \"E27002\", salary: 19250, dept: \"D202\"},\n {name: \"Tim Sampair\", id: \"E03033\", salary: 27000, dept: \"D101\"},\n {name: \"Kim Arlich\", id: \"E10001\", salary: 57000, dept: \"D190\"},\n {name: \"Timothy Grove\", id: \"E16398\", salary: 29900, dept: \"D190\"},\n];\n\nfunction top_rank(n) {\n var by_dept = group_by_dept(data);\n for (var dept in by_dept) {\n output(dept);\n for (var i = 0; i < n && i < by_dept[dept].length; i++) {\n var emp = by_dept[dept][i];\n output(emp.name + \", id=\" + emp.id + \", salary=\" + emp.salary);\n }\n output(\"\");\n }\n}\n\n// group by dept, and sort by salary\nfunction group_by_dept(data) {\n var by_dept = {};\n for (var idx in data) {\n var dept = data[idx].dept;\n if ( ! has_property(by_dept, dept)) {\n by_dept[dept] = new Array();\n }\n by_dept[dept].push(data[idx]);\n }\n for (var dept in by_dept) {\n // numeric sort\n by_dept[dept].sort(function (a,b){return b.salary - a.salary});\n }\n return by_dept;\n}\n\nfunction has_property(obj, propname) {\n return typeof(obj[propname]) != \"undefined\";\n}\n\nfunction output(str) {\n try {\n WScript.Echo(str); // WSH\n } catch(err) {\n print(str); // Rhino\n }\n}\n\ntop_rank(3);\n"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "JavaScript", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "#!/usr/bin/env js\n\nfunction main() {\n var nums = getNumbers(11);\n nums.reverse();\n for (var i in nums) {\n pardoKnuth(nums[i], fn, 400);\n }\n}\n\nfunction pardoKnuth(n, f, max) {\n var res = f(n);\n putstr('f(' + String(n) + ')');\n if (res > max) {\n print(' is too large');\n } else {\n print(' = ' + String(res));\n } \n}\n\nfunction fn(x) {\n return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3);\n}\n\nfunction getNumbers(n) {\n var nums = [];\n print('Enter', n, 'numbers.');\n for (var i = 1; i <= n; i++) {\n putstr(' ' + i + ': ');\n var num = readline();\n nums.push(Number(num)); \n }\n return nums;\n}\n\nmain();\n"} {"title": "Truth table", "language": "JavaScript", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* [[Boolean values]]\n* [[Ternary logic]]\n\n\n;See also:\n* Wolfram MathWorld entry on truth tables.\n* some \"truth table\" examples from Google.\n\n", "solution": "Truth table"} {"title": "Two bullet roulette", "language": "JavaScript", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "let Pistol = function(method) {\n this.fired = false;\n this.cylinder = new Array(6).fill(false);\n this.trigger = 0;\n this.rshift = function() {\n this.trigger = this.trigger == 0 ? 5 : this.trigger-1;\n }\n this.load = function() {\n while (this.cylinder[this.trigger]) this.rshift();\n this.cylinder[this.trigger] = true;\n this.rshift();\n }\n // actually we don't need this here: just for completeness\n this.unload = function() { this.cylinder.fill(false); }\n\n this.spin = function() { this.trigger = Math.floor(Math.random() * 6); }\n this.fire = function() {\n if (this.cylinder[this.trigger]) this.fired = true;\n this.rshift();\n }\n this.exec = function() {\n if (!method) console.error('No method provided');\n else {\n method = method.toUpperCase();\n for (let x = 0; x < method.length; x++)\n switch (method[x]) {\n case 'F' : this.fire(); break;\n case 'L' : this.load(); break;\n case 'S' : this.spin(); break;\n case 'U' : this.unload(); break;\n default: console.error(`Unknown character in method: ${method[x]}`);\n }\n return this.fired;\n }\n }\n}\n\n// simulating\nconst ITERATIONS = 25e4;\nlet methods = 'lslsfsf lslsff llsfsf llsff'.split(' '),\n bodyCount;\nconsole.log(`@ ${ITERATIONS.toLocaleString('en')} iterations:`);\nconsole.log();\nfor (let x = 0; x < methods.length; x++) {\n bodyCount = 0;\n for (let y = 1; y <= ITERATIONS; y++)\n if (new Pistol(methods[x]).exec()) bodyCount++;\n console.log(`${methods[x]}:`);\n console.log(`deaths: ${bodyCount.toLocaleString('en')} (${(bodyCount / ITERATIONS * 100).toPrecision(3)} %) `);\n console.log();\n}\n"} {"title": "URL encoding", "language": "JavaScript", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "var normal = 'http://foo/bar/';\nvar encoded = encodeURIComponent(normal);"} {"title": "URL parser", "language": "JavaScript", "task": "URLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...\n\n\nNote: this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded ('''%''') in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* Here is the official standard: https://tools.ietf.org/html/rfc3986, \n* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:\n::* scheme = foo\n::* domain = example.com\n::* port = :8042\n::* path = over/there\n::* query = name=ferret\n::* fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' should parse into:\n::* scheme = urn\n::* path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* mailto:John.Doe@example.com \n:* news:comp.infosystems.www.servers.unix \n:* tel:+1-816-555-1212 \n:* telnet://192.0.2.16:80/ \n:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "[\n {\n \"hash\": \"#nose\",\n \"host\": \"example.com:8042\",\n \"hostname\": \"example.com\",\n \"origin\": \"foo://example.com:8042\",\n \"pathname\": \"/over/there\",\n \"port\": \"8042\",\n \"protocol\": \"foo:\",\n \"search\": \"?name=ferret\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"urn://\",\n \"pathname\": \"example:animal:ferret:nose\",\n \"port\": \"\",\n \"protocol\": \"urn:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"jdbc://\",\n \"pathname\": \"mysql://test_user:ouupppssss@localhost:3306/sakila\",\n \"port\": \"\",\n \"protocol\": \"jdbc:\",\n \"search\": \"?profileSQL=true\"\n },\n {\n \"hash\": \"\",\n \"host\": \"ftp.is.co.za\",\n \"hostname\": \"ftp.is.co.za\",\n \"origin\": \"ftp://ftp.is.co.za\",\n \"pathname\": \"/rfc/rfc1808.txt\",\n \"port\": \"\",\n \"protocol\": \"ftp:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"#header1\",\n \"host\": \"www.ietf.org\",\n \"hostname\": \"www.ietf.org\",\n \"origin\": \"http://www.ietf.org\",\n \"pathname\": \"/rfc/rfc2396.txt\",\n \"port\": \"\",\n \"protocol\": \"http:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"[2001:db8::7]\",\n \"hostname\": \"[2001:db8::7]\",\n \"origin\": \"ldap://[2001:db8::7]\",\n \"pathname\": \"/c=GB\",\n \"port\": \"\",\n \"protocol\": \"ldap:\",\n \"search\": \"?objectClass=one&objectClass=two\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"mailto://\",\n \"pathname\": \"John.Doe@example.com\",\n \"port\": \"\",\n \"protocol\": \"mailto:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"news://\",\n \"pathname\": \"comp.infosystems.www.servers.unix\",\n \"port\": \"\",\n \"protocol\": \"news:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"tel://\",\n \"pathname\": \"+1-816-555-1212\",\n \"port\": \"\",\n \"protocol\": \"tel:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"192.0.2.16:80\",\n \"hostname\": \"192.0.2.16\",\n \"origin\": \"telnet://192.0.2.16:80\",\n \"pathname\": \"/\",\n \"port\": \"80\",\n \"protocol\": \"telnet:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"\",\n \"hostname\": \"\",\n \"origin\": \"urn://\",\n \"pathname\": \"oasis:names:specification:docbook:dtd:xml:4.1.2\",\n \"port\": \"\",\n \"protocol\": \"urn:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"ssh://example.com\",\n \"pathname\": \"\",\n \"port\": \"\",\n \"protocol\": \"ssh:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"https://example.com\",\n \"pathname\": \"/place\",\n \"port\": \"\",\n \"protocol\": \"https:\",\n \"search\": \"\"\n },\n {\n \"hash\": \"\",\n \"host\": \"example.com\",\n \"hostname\": \"example.com\",\n \"origin\": \"http://example.com\",\n \"pathname\": \"/\",\n \"port\": \"\",\n \"protocol\": \"http:\",\n \"search\": \"?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\"\n }\n]"} {"title": "UTF-8 encode and decode", "language": "JavaScript", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "/***************************************************************************\\\n|* Pure UTF-8 handling without detailed error reporting functionality. *|\n|***************************************************************************|\n|* utf8encode *|\n|* < String character or UInt32 code point *|\n|* > Uint8Array encoded_character *|\n|* | ErrorString *|\n|* *|\n|* utf8encode takes a string or uint32 representing a single code point *|\n|* as its argument and returns an array of length 1 up to 4 containing *|\n|* utf8 code units representing that character. *|\n|***************************************************************************|\n|* utf8decode *|\n|* < Unit8Array [highendbyte highmidendbyte lowmidendbyte lowendbyte] *|\n|* > uint32 character *|\n|* | ErrorString *|\n|* *|\n|* utf8decode takes an array of one to four uint8 representing utf8 code *|\n|* units and returns a uint32 representing that code point. *|\n\\***************************************************************************/\n\nconst\n utf8encode=\n n=>\n (m=>\n m<0x80\n ?Uint8Array.from(\n [ m>>0&0x7f|0x00])\n :m<0x800\n ?Uint8Array.from(\n [ m>>6&0x1f|0xc0,m>>0&0x3f|0x80])\n :m<0x10000\n ?Uint8Array.from(\n [ m>>12&0x0f|0xe0,m>>6&0x3f|0x80,m>>0&0x3f|0x80])\n :m<0x110000\n ?Uint8Array.from(\n [ m>>18&0x07|0xf0,m>>12&0x3f|0x80,m>>6&0x3f|0x80,m>>0&0x3f|0x80])\n :(()=>{throw'Invalid Unicode Code Point!'})())\n ( typeof n==='string'\n ?n.codePointAt(0)\n :n&0x1fffff),\n utf8decode=\n ([m,n,o,p])=>\n m<0x80\n ?( m&0x7f)<<0\n :0xc1{throw'Invalid UTF-8 encoding!'})()\n"} {"title": "Van Eck sequence", "language": "JavaScript from Python", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "(() => {\n \"use strict\";\n\n // vanEck :: Int -> [Int]\n const vanEck = n =>\n // First n terms of the vanEck series.\n [0].concat(mapAccumL(\n ([x, seen]) => i => {\n const\n prev = seen[x],\n v = Boolean(prev) ? (\n i - prev\n ) : 0;\n\n return [\n [v, (seen[x] = i, seen)], v\n ];\n })(\n [0, {}]\n )(\n enumFromTo(1)(n - 1)\n )[1]);\n\n\n // ----------------------- TEST ------------------------\n const main = () =>\n fTable(\n \"Terms of the VanEck series:\\n\"\n )(\n n => `${str(n - 10)}-${str(n)}`\n )(\n xs => JSON.stringify(xs.slice(-10))\n )(\n vanEck\n )([10, 1000, 10000]);\n\n\n // ----------------- GENERIC FUNCTIONS -----------------\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 // fTable :: String -> (a -> String) ->\n // (b -> String) -> (a -> b) -> [a] -> String\n const fTable = s =>\n // Heading -> x display function ->\n // fx display function ->\n // f -> values -> tabular string\n xShow => fxShow => f => xs => {\n const\n ys = xs.map(xShow),\n w = Math.max(...ys.map(y => [...y].length)),\n table = zipWith(\n a => b => `${a.padStart(w, \" \")} -> ${b}`\n )(ys)(\n xs.map(x => fxShow(f(x)))\n ).join(\"\\n\");\n\n return `${s}\\n${table}`;\n };\n\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc ->\n // [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, bs], x) => second(\n v => bs.concat(v)\n )(\n f(a)(x)\n ),\n [acc, []]\n );\n\n\n // second :: (a -> b) -> ((c, a) -> (c, b))\n const second = f =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n ([x, y]) => [x, f(y)];\n\n\n // str :: a -> String\n const str = x => x.toString();\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": "Variable declaration reset", "language": "JavaScript", "task": "A decidely non-challenging task to highlight a potential difference between programming languages.\n\nUsing a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. \nThe purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.\nThere is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.\nShould your first attempt bomb with \"unassigned variable\" exceptions, feel free to code it as (say)\n // int prev // crashes with unassigned variable\n int prev = -1 // predictably no output\nIf your programming language does not support block scope (eg assembly) it should be omitted from this task.\n\n", "solution": "\n\n \n \n \n variable declaration reset\n \n \n \n \n"} {"title": "Vector products", "language": "JavaScript", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "function dotProduct() {\n var len = arguments[0] && arguments[0].length;\n var argsLen = arguments.length;\n var i, j = len;\n var prod, sum = 0;\n \n // If no arguments supplied, return undefined\n if (!len) {\n return;\n }\n \n // If all vectors not same length, return undefined\n i = argsLen;\n while (i--) {\n \n if (arguments[i].length != len) {\n return; // return undefined\n }\n }\n \n // Sum terms\n while (j--) {\n i = argsLen;\n prod = 1;\n \n while (i--) {\n prod *= arguments[i][j];\n }\n sum += prod;\n }\n return sum;\n}\n\nfunction crossProduct(a, b) {\n\n // Check lengths\n if (a.length != 3 || b.length != 3) {\n return;\n }\n \n return [a[1]*b[2] - a[2]*b[1],\n a[2]*b[0] - a[0]*b[2],\n a[0]*b[1] - a[1]*b[0]];\n \n}\n\nfunction scalarTripleProduct(a, b, c) {\n return dotProduct(a, crossProduct(b, c));\n}\n\nfunction vectorTripleProduct(a, b, c) {\n return crossProduct(a, crossProduct(b, c));\n}\n\n// Run tests\n(function () {\n var a = [3, 4, 5];\n var b = [4, 3, 5];\n var c = [-5, -12, -13];\n \n alert(\n 'A . B: ' + dotProduct(a, b) +\n '\\n' +\n 'A x B: ' + crossProduct(a, b) +\n '\\n' +\n 'A . (B x C): ' + scalarTripleProduct(a, b, c) +\n '\\n' +\n 'A x (B x C): ' + vectorTripleProduct(a, b, c)\n ); \n}());"} {"title": "Visualize a tree", "language": "JavaScript", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "\n\n \n Stuff\n \n \n \n \n
\n
\n

Headline

\n Blah blah\n
\n
\n

More headline

\n
Something something
\n

Nested section

\n\t Somethin somethin list:\n\t
    \n\t
  • Apples
  • \n\t
  • Oranges
  • \n\t
  • Cetera Fruits
  • \n\t
\n\t
\n
\n
\n \n \n"} {"title": "Visualize a tree", "language": "JavaScript from Python", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "(() => {\n 'use strict';\n\n // UTF8 character-drawn tree, with options for compacting vs\n // centering parents, and for pruning out nodeless lines.\n\n const example = `\n \u250c Epsilon\n \u250c\u2500 Beta \u253c\u2500\u2500\u2500 Zeta\n \u2502 \u2514\u2500\u2500\u2500\u2500 Eta\n Alpha \u253c Gamma \u2500\u2500\u2500 Theta\n \u2502 \u250c\u2500\u2500\u2500 Iota\n \u2514 Delta \u253c\u2500\u2500 Kappa\n \u2514\u2500 Lambda`\n\n // drawTree2 :: Bool -> Bool -> Tree String -> String\n const drawTree2 = blnCompact => blnPruned => tree => {\n // Tree design and algorithm inspired by the Haskell snippet at:\n // https://doisinkidney.com/snippets/drawing-trees.html\n const\n // Lefts, Middle, Rights\n lmrFromStrings = xs => {\n const [ls, rs] = Array.from(splitAt(\n Math.floor(xs.length / 2),\n xs\n ));\n return Tuple3(ls, rs[0], rs.slice(1));\n },\n stringsFromLMR = lmr =>\n Array.from(lmr).reduce((a, x) => a.concat(x), []),\n fghOverLMR = (f, g, h) => lmr => {\n const [ls, m, rs] = Array.from(lmr);\n return Tuple3(ls.map(f), g(m), rs.map(h));\n };\n\n const lmrBuild = (f, w) => wsTree => {\n const\n leftPad = n => s => ' '.repeat(n) + s,\n xs = wsTree.nest,\n lng = xs.length,\n [nChars, x] = Array.from(wsTree.root);\n\n // LEAF NODE --------------------------------------\n return 0 === lng ? (\n Tuple3([], '\u2500'.repeat(w - nChars) + x, [])\n\n // NODE WITH SINGLE CHILD -------------------------\n ) : 1 === lng ? (() => {\n const indented = leftPad(1 + w);\n return fghOverLMR(\n indented,\n z => '\u2500'.repeat(w - nChars) + x + '\u2500' + z,\n indented\n )(f(xs[0]));\n\n // NODE WITH CHILDREN -----------------------------\n })() : (() => {\n const\n cFix = x => xs => x + xs,\n treeFix = (l, m, r) => compose(\n stringsFromLMR,\n fghOverLMR(cFix(l), cFix(m), cFix(r))\n ),\n _x = '\u2500'.repeat(w - nChars) + x,\n indented = leftPad(w),\n lmrs = xs.map(f);\n return fghOverLMR(\n indented,\n s => _x + ({\n '\u250c': '\u252c',\n '\u251c': '\u253c',\n '\u2502': '\u2524',\n '\u2514': '\u2534'\n })[s[0]] + s.slice(1),\n indented\n )(lmrFromStrings(\n intercalate(\n blnCompact ? [] : ['\u2502'],\n [treeFix(' ', '\u250c', '\u2502')(lmrs[0])]\n .concat(init(lmrs.slice(1)).map(\n treeFix('\u2502', '\u251c', '\u2502')\n ))\n .concat([treeFix('\u2502', '\u2514', ' ')(\n lmrs[lmrs.length - 1]\n )])\n )\n ));\n })();\n };\n const\n measuredTree = fmapTree(\n v => {\n const s = ' ' + v + ' ';\n return Tuple(s.length, s)\n }, tree\n ),\n levelWidths = init(levels(measuredTree))\n .reduce(\n (a, level) => a.concat(maximum(level.map(fst))),\n []\n ),\n treeLines = stringsFromLMR(\n levelWidths.reduceRight(\n lmrBuild, x => x\n )(measuredTree)\n );\n return unlines(\n blnPruned ? (\n treeLines.filter(\n s => s.split('')\n .some(c => !' \u2502'.includes(c))\n )\n ) : treeLines\n );\n };\n\n // TESTS ----------------------------------------------\n const main = () => {\n\n // tree :: Tree String\n const tree = Node(\n 'Alpha', [\n Node('Beta', [\n Node('Epsilon', []),\n Node('Zeta', []),\n Node('Eta', [])\n ]),\n Node('Gamma', [Node('Theta', [])]),\n Node('Delta', [\n Node('Iota', []),\n Node('Kappa', []),\n Node('Lambda', [])\n ])\n ]);\n\n // tree2 :: Tree Int\n const tree2 = Node(\n 1,\n [\n Node(2, [\n Node(4, []),\n Node(5, [Node(7, [])])\n ]),\n Node(3, [\n Node(6, [\n Node(8, []),\n Node(9, [])\n ])\n ])\n ]\n );\n\n // strTrees :: String\n const strTrees = ([\n 'Compacted (parents not all vertically centered):',\n drawTree2(true)(false)(tree2),\n 'Fully expanded, with vertical centering:',\n drawTree2(false)(false)(tree),\n 'Vertically centered, with nodeless lines pruned out:',\n drawTree2(false)(true)(tree),\n ].join('\\n\\n'));\n\n return (\n console.log(strTrees),\n strTrees\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // Tuple3 (,,) :: a -> b -> c -> (a, b, c)\n const Tuple3 = (a, b, c) => ({\n type: 'Tuple3',\n '0': a,\n '1': b,\n '2': c,\n length: 3\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = (f, tree) => {\n const go = node => Node(\n f(node.root),\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // identity :: a -> a\n const identity = x => x;\n\n // init :: [a] -> [a]\n const init = xs =>\n 0 < xs.length ? (\n xs.slice(0, -1)\n ) : undefined;\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = (sep, xs) =>\n 0 < xs.length && 'string' === typeof sep &&\n 'string' === typeof xs[0] ? (\n xs.join(sep)\n ) : concat(intersperse(sep, xs));\n\n // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]\n\n // intersperse :: a -> [a] -> [a]\n // intersperse :: Char -> String -> String\n const intersperse = (sep, xs) => {\n const bln = 'string' === typeof xs;\n return xs.length > 1 ? (\n (bln ? concat : x => x)(\n (bln ? (\n xs.split('')\n ) : xs)\n .slice(1)\n .reduce((a, x) => a.concat([sep, x]), [xs[0]])\n )) : xs;\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // levels :: Tree a -> [[a]]\n const levels = tree =>\n iterateUntil(\n xs => 1 > xs.length,\n ys => [].concat(...ys.map(nest)),\n [tree]\n ).map(xs => xs.map(root));\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n 0 < xs.length ? (\n xs.slice(1).reduce((a, x) => x > a ? x : a, xs[0])\n ) : undefined;\n\n // nest :: Tree a -> [a]\n const nest = tree => tree.nest;\n\n // root :: Tree a -> a\n const root = tree => tree.root;\n\n // splitAt :: Int -> [a] -> ([a], [a])\n const splitAt = (n, xs) =>\n Tuple(xs.slice(0, n), xs.slice(n));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();"} {"title": "Voronoi diagram", "language": "JavaScript", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "===Version #1.===\nThe obvious route to this in JavaScript would be to use Mike Bostock's D3.js library.\n\nThere are various examples of Voronoi tesselations,\n\nsome dynamic:\n\nhttps://bl.ocks.org/mbostock/d1d81455dc21e10f742f\n\nsome interactive:\n\nhttps://bl.ocks.org/mbostock/4060366\n\nand all with source code, at https://bl.ocks.org/mbostock\n\n===Version #2.===\nI would agree: using D3.js library can be very helpful. But having stable and compact algorithm in Python (Sidef) made it possible to develop looking the same Voronoi diagram in \"pure\" JavaScript.\nA few custom helper functions simplified code, and they can be used for any other applications.\n"} {"title": "Water collected between towers", "language": "JavaScript from Haskell", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "(() => {\n \"use strict\";\n\n // --------- WATER COLLECTED BETWEEN TOWERS ----------\n\n // waterCollected :: [Int] -> Int\n const waterCollected = xs =>\n sum(filter(lt(0))(\n zipWith(subtract)(xs)(\n zipWith(min)(\n scanl1(max)(xs)\n )(\n scanr1(max)(xs)\n )\n )\n ));\n\n\n // ---------------------- TEST -----------------------\n const main = () => [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n ].map(waterCollected);\n\n\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 });\n\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = p =>\n // The elements of xs which match\n // the predicate p.\n xs => [...xs].filter(p);\n\n\n // lt (<) :: Ord a => a -> a -> Bool\n const lt = a =>\n b => a < b;\n\n\n // max :: Ord a => a -> a -> a\n const max = a =>\n // b if its greater than a,\n // otherwise a.\n b => a > b ? a : b;\n\n\n // min :: Ord a => a -> a -> a\n const min = a =>\n b => b < a ? b : a;\n\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n\n // scanl1 :: (a -> a -> a) -> [a] -> [a]\n const scanl1 = f =>\n // scanl1 is a variant of scanl that\n // has no starting value argument.\n xs => xs.length > 0 ? (\n scanl(f)(\n xs[0]\n )(xs.slice(1))\n ) : [];\n\n\n // scanr :: (a -> b -> b) -> b -> [a] -> [b]\n const scanr = f =>\n startValue => xs => xs.reduceRight(\n (a, x) => {\n const v = f(x)(a[0]);\n\n return Tuple(v)([v].concat(a[1]));\n }, Tuple(startValue)([startValue])\n )[1];\n\n\n // scanr1 :: (a -> a -> a) -> [a] -> [a]\n const scanr1 = f =>\n // scanr1 is a variant of scanr that has no\n // seed-value argument, and assumes that\n // xs is not empty.\n xs => xs.length > 0 ? (\n scanr(f)(\n xs.slice(-1)[0]\n )(xs.slice(0, -1))\n ) : [];\n\n\n // subtract :: Num -> Num -> Num\n const subtract = x =>\n y => y - x;\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": "Weird numbers", "language": "JavaScript from Haskell", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n take(25, weirds());\n\n\n // weirds :: Gen [Int]\n function* weirds() {\n let\n x = 1,\n i = 1;\n while (true) {\n x = until(isWeird, succ, x)\n console.log(i.toString() + ' -> ' + x)\n yield x;\n x = 1 + x;\n i = 1 + i;\n }\n }\n\n\n // isWeird :: Int -> Bool\n const isWeird = n => {\n const\n ds = descProperDivisors(n),\n d = sum(ds) - n;\n return 0 < d && !hasSum(d, ds)\n };\n\n // hasSum :: Int -> [Int] -> Bool\n const hasSum = (n, xs) => {\n const go = (n, xs) =>\n 0 < xs.length ? (() => {\n const\n h = xs[0],\n t = xs.slice(1);\n return n < h ? (\n go(n, t)\n ) : (\n n == h || hasSum(n - h, t) || hasSum(n, t)\n );\n })() : false;\n return go(n, xs);\n };\n\n\n // descProperDivisors :: Int -> [Int]\n const descProperDivisors = n => {\n const\n rRoot = Math.sqrt(n),\n intRoot = Math.floor(rRoot),\n blnPerfect = rRoot === intRoot,\n lows = enumFromThenTo(intRoot, intRoot - 1, 1)\n .filter(x => (n % x) === 0);\n return (\n reverse(lows)\n .slice(1)\n .map(x => n / x)\n ).concat((blnPerfect ? tail : id)(lows))\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // id :: a -> a\n const id = x => x;\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // succ :: Enum a => a -> a\n const succ = x => 1 + x;\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Word wrap", "language": "JavaScript", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "function wrap (text, limit) {\n if (text.length > limit) {\n // find the last space within limit\n var edge = text.slice(0, limit).lastIndexOf(' ');\n if (edge > 0) {\n var line = text.slice(0, edge);\n var remainder = text.slice(edge + 1);\n return line + '\\n' + wrap(remainder, limit);\n }\n }\n return text;\n}\n"} {"title": "Zeckendorf number representation", "language": "JavaScript from Haskell", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "(() => {\n 'use strict';\n\n const main = () =>\n unlines(\n map(n => concat(zeckendorf(n)),\n enumFromTo(0, 20)\n )\n );\n\n // zeckendorf :: Int -> String\n const zeckendorf = n => {\n const go = (n, x) =>\n n < x ? (\n Tuple(n, '0')\n ) : Tuple(n - x, '1')\n return 0 < n ? (\n snd(mapAccumL(\n go, n,\n reverse(fibUntil(n))\n ))\n ) : ['0'];\n };\n\n // fibUntil :: Int -> [Int]\n const fibUntil = n =>\n cons(1, takeWhile(x => n >= x,\n map(snd, iterateUntil(\n tpl => n <= fst(tpl),\n tpl => {\n const x = snd(tpl);\n return Tuple(x, x + fst(tpl));\n },\n Tuple(1, 2)\n ))));\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) =>\n Array.isArray(xs) ? (\n [x].concat(xs)\n ) : (x + xs);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See Hoogle)\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = (f, acc, xs) =>\n xs.reduce((a, x, i) => {\n const pair = f(a[0], x, i);\n return Tuple(pair[0], a[1].concat(pair[1]));\n }, Tuple(acc, []));\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // takeWhile :: (a -> Bool) -> [a] -> [a]\n // takeWhile :: (Char -> Bool) -> String -> String\n const takeWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n 0,\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();"} {"title": "Zhang-Suen thinning algorithm", "language": "JavaScript from Java", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "function Point(x, y) {\n this.x = x;\n this.y = y;\n}\nvar ZhangSuen = (function () {\n function ZhangSuen() {\n }\n ZhangSuen.image = \n [\" \",\n \" ################# ############# \",\n \" ################## ################ \",\n \" ################### ################## \",\n \" ######## ####### ################### \",\n \" ###### ####### ####### ###### \",\n \" ###### ####### ####### \",\n \" ################# ####### \",\n \" ################ ####### \",\n \" ################# ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### ###### \",\n \" ######## ####### ################### \",\n \" ######## ####### ###### ################## ###### \",\n \" ######## ####### ###### ################ ###### \",\n \" ######## ####### ###### ############# ###### \",\n \" \"];\n\n ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]];\n\n ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]];\n\n ZhangSuen.toWhite = new Array();\n ;\n ZhangSuen.main = function (args) {\n ZhangSuen.grid = new Array(ZhangSuen.image.length);\n for (var r = 0; r < ZhangSuen.image.length; r++)\n ZhangSuen.grid[r] = (ZhangSuen.image[r]).split('');\n ZhangSuen.thinImage();\n };\n ZhangSuen.thinImage = function () {\n var firstStep = false;\n var hasChanged;\n do {\n hasChanged = false;\n firstStep = !firstStep;\n for (var r = 1; r < ZhangSuen.grid.length - 1; r++) {\n for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) {\n if (ZhangSuen.grid[r][c] !== '#')\n continue;\n var nn = ZhangSuen.numNeighbors(r, c);\n if (nn < 2 || nn > 6)\n continue;\n if (ZhangSuen.numTransitions(r, c) !== 1)\n continue;\n if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1))\n continue;\n ZhangSuen.toWhite.push(new Point(c, r));\n hasChanged = true;\n }\n }\n for (let i = 0; i < ZhangSuen.toWhite.length; i++) {\n var p = ZhangSuen.toWhite[i];\n ZhangSuen.grid[p.y][p.x] = ' ';\n }\n ZhangSuen.toWhite = new Array();\n } while ((firstStep || hasChanged));\n ZhangSuen.printResult();\n };\n ZhangSuen.numNeighbors = function (r, c) {\n var count = 0;\n for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++)\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#')\n count++;\n return count;\n };\n ZhangSuen.numTransitions = function (r, c) {\n var count = 0;\n for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++)\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') {\n if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#')\n count++;\n }\n return count;\n };\n ZhangSuen.atLeastOneIsWhite = function (r, c, step) {\n var count = 0;\n var group = ZhangSuen.nbrGroups[step];\n for (var i = 0; i < 2; i++)\n for (var j = 0; j < group[i].length; j++) {\n var nbr = ZhangSuen.nbrs[group[i][j]];\n if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') {\n count++;\n break;\n }\n }\n return count > 1;\n };\n ZhangSuen.printResult = function () {\n for (var i = 0; i < ZhangSuen.grid.length; i++) {\n var row = ZhangSuen.grid[i];\n console.log(row.join(''));\n }\n };\n return ZhangSuen;\n}());\nZhangSuen.main(null);"}
SidesPerimeterArea
\" + list[i][0] + \" x \" + list[i][1] + \" x \" + list[i][2] + \"\" + list[i][3] + \"\" + list[i][4] + \"