{"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 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\nUse buttons to play.
\n\n