[ { "filename": "100 doors_1.txt", "content": "V doors = [0B] * 100\nL(i) 100\n L(j) (i .< 100).step(i + 1)\n doors[j] = !doors[j]\n print(\u2018Door \u2019(i + 1)\u2018: \u2019(I doors[i] {\u2018open\u2019} E \u2018close\u2019))", "safe": true }, { "filename": "100 doors_10.txt", "content": "page:\tequ\t2\t; Store doors in page 2\ndoors:\tequ\t100\t; 100 doors\nputs:\tequ\t9\t; CP/M string output\n\torg\t100h\n\txra\ta\t; Set all doors to zero\n\tlxi\th,256*page\n\tmvi\tc,doors\nzero:\tmov\tm,a\n\tinx\th\n\tdcr\tc\n\tjnz\tzero\n\tmvi\tm,'$'\t; CP/M string terminator (for easier output later)\n\tmov\td,a\t; D=0 so that DE=E=pass counter\n\tmov\te,a\t; E=0, first pass\n\tmvi\ta,doors-1\t; Last pass and door\npass:\tmov\tl,e\t; L=door counter, start at first door in pass\ndoor:\tinr\tm\t; Incrementing always toggles the low bit\n\tdad\td\t; Go to next door in pass\n\tinr\tl\n\tcmp\tl\t; Was this the last door?\n\tjnc\tdoor\t; If not, do the next door\n\tinr\te\t; Next pass\n\tcmp\te\t; Was this the last pass?\n\tjnc\tpass\t; If not, do the next pass\n\tlxi\th,256*page\n\tmvi\tc,doors\t; Door counter\n\tlxi\td,130h\t; D=1 (low bit), E=30h (ascii 0)\nchar:\tmov\ta,m\t; Get door\t\n\tana\td\t; Low bit gives door status\n\tora\te\t; ASCII 0 or 1\n\tmov\tm,a\t; Write character back\n\tinx\th\t; Next door\n\tdcr\tc\t; Any doors left?\n\tjnz\tchar\t; If so, next door\n\tlxi\td,256*page\n\tmvi\tc,puts\t; CP/M system call to print the string\n\tjmp\t5", "safe": true }, { "filename": "100 doors_100.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=I TO 100 STEP I\n40 LET D(J)=NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I,\n90 NEXT I\n", "safe": true }, { "filename": "100 doors_101.txt", "content": "@echo off\nsetlocal enableDelayedExpansion\n:: 0 = closed\n:: 1 = open\n:: SET /A treats undefined variable as 0\n:: Negation operator\u00a0! must be escaped because delayed expansion is enabled\nfor /l %%p in (1 1 100) do for /l %%d in (%%p %%p 100) do set /a \"door%%d=^!door%%d\"\nfor /l %%d in (1 1 100) do if !door%%d!==1 (\n echo door %%d is open\n) else echo door %%d is closed\n", "safe": true }, { "filename": "100 doors_102.txt", "content": "@echo off\nsetlocal enableDelayedExpansion\nset /a square=1, incr=3\nfor /l %%d in (1 1 100) do (\n if %%d neq !square! (echo door %%d is closed) else (\n echo door %%d is open\n set /a square+=incr, incr+=2\n )\n)\n", "safe": true }, { "filename": "100 doors_103.txt", "content": "DIM doors%(100)\nFOR pass% = 1 TO 100\n FOR door% = pass% TO 100 STEP pass%\n doors%(door%) = NOT doors%(door%)\n NEXT door%\nNEXT pass% \nFOR door% = 1 TO 100\n IF doors%(door%) PRINT \"Door \" ; door% \" is open\"\nNEXT door%\n", "safe": true }, { "filename": "100 doors_104.txt", "content": "/* 0 means door is closed, 1 means door is open */\nfor (i = 0; i < 100; i++) {\n for (j = i; j < 100; j += (i + 1)) {\n d[j] = 1 - d[j] /* Toggle door */\n }\n}\n\n\"Open doors:\n\"\nfor (i = 0; i < 100; i++) {\n if (d[i] == 1) (i + 1)\n}\n", "safe": true }, { "filename": "100 doors_105.txt", "content": "get \"libhdr\"\n\nlet start() be \n$( let doors = vec 100\n\n // close all doors\n for n = 1 to 100 do doors!n\u00a0:= 0\n\n // make 100 passes\n for pass = 1 to 100 do\n $( let n = pass\n while n <= 100 do\n $( doors!n\u00a0:= ~doors!n\n n\u00a0:= n + pass\n $)\n $)\n \n // report which doors are open\n for n = 1 to 100 do\n if doors!n then\n writef(\"Door %N is open.*N\", n)\n$)", "safe": true }, { "filename": "100 doors_106.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_107.txt", "content": ">\"d\">:00p1-:>:::9%\\9/9+g2%!\\:9v\n$.v_^#!$::$_^#`\"c\":+g00p+9/9\\%<\n::<_@#`$:\\*:+55:+1p27g1g+9/9\\%9\n", "safe": true }, { "filename": "100 doors_108.txt", "content": "1+:::*.9`#@_\n", "safe": true }, { "filename": "100 doors_109.txt", "content": "108p0>:18p;;>:9g!18g9p08g]\n*`!0\\|+relet|-1`*aap81::+]\n;::+1$08g1+:08paa[\n*`#@_^._aa\n", "safe": true }, { "filename": "100 doors_11.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100 doors_110.txt", "content": "0001000100010101000110100000010110000011001110110010100011010000000000101111111000000101111101011001011001000110100001111100110100101111101111000000001011111111110110011001111111011100000000101111110000001011111010110011011100101011000000101111011001011110011110011110110100000000001011011100111011110000000001000000111001110100000000101101110110", "safe": true }, { "filename": "100 doors_111.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100 doors_112.txt", "content": "var doors = [false] * 100\nfor i in 0..100 {\n iter var j = i; j < 100; j += i + 1 {\n doors[j] = !doors[j]\n }\n var state = doors[i]\u00a0? 'open'\u00a0: 'closed'\n echo 'Door ${i + 1} is ${state}'\n}", "safe": true }, { "filename": "100 doors_113.txt", "content": "for i in 1..101 {\n echo 'Door ${i} is ${i ** 0.5\u00a0% 1 > 0\u00a0? \"closed\"\u00a0: \"open\"}'\n}", "safe": true }, { "filename": "100 doors_114.txt", "content": "for i in 1..11 echo 'Door ${i**2} is open'", "safe": true }, { "filename": "100 doors_115.txt", "content": "Graphics 640,480\ni=1\nWhile ((i*i)<=100)\n\ta$=i*i\n\tDrawText a$,10,20*i\n\tPrint i*i\n\ti=i+1 \nWend\nFlip \nWaitKey\n", "safe": true }, { "filename": "100 doors_116.txt", "content": "DEFINE PROCEDURE ''DIVIDE'' [A,B]:\nBLOCK 0: BEGIN\n IF A < B, THEN:\n QUIT BLOCK 0;\n CELL(0) <= 1;\n OUTPUT <= 1;\n LOOP AT MOST A TIMES:\n BLOCK 2: BEGIN\n IF OUTPUT * B = A, THEN:\n QUIT BLOCK 0;\n OUTPUT <= OUTPUT + 1;\n IF OUTPUT * B > A, THEN:\n BLOCK 3: BEGIN\n OUTPUT <= CELL(0);\n QUIT BLOCK 0;\n BLOCK 3: END;\n CELL(0) <= OUTPUT;\n BLOCK 2: END;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''MINUS'' [A,B]:\nBLOCK 0: BEGIN\n IF A < B, THEN:\n QUIT BLOCK 0;\n LOOP AT MOST A TIMES:\n BLOCK 1: BEGIN\n IF OUTPUT + B = A, THEN:\n QUIT BLOCK 0;\n OUTPUT <= OUTPUT + 1;\n BLOCK 1: END;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''MODULUS'' [A,B]:\nBLOCK 0: BEGIN\n CELL(0) <= DIVIDE[A,B];\n OUTPUT <= MINUS[A,CELL(0) * B];\nBLOCK 0: END.\n\n\n\nDEFINE PROCEDURE ''TOGGLE'' [DOOR]:\nBLOCK 0: BEGIN\n IF DOOR = 1, THEN:\n QUIT BLOCK 0;\n OUTPUT <= 1;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''NUMBERS'' [DOOR, COUNT]:\nBLOCK 0: BEGIN\n CELL(0) <= 1; /*each number*/\n OUTPUT <= 0; /*current door state*/\n \n LOOP COUNT TIMES:\n BLOCK 1: BEGIN\n\n IF MODULUS[DOOR, CELL(0)] = 0, THEN:\n OUTPUT <= TOGGLE[OUTPUT];\n \n CELL(0) <= CELL(0) + 1;\n\n BLOCK 1: END;\n\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''DOORS'' [COUNT]:\nBLOCK 0: BEGIN\n\n CELL(0) <= 1; /*each door*/\n LOOP COUNT TIMES:\n BLOCK 1: BEGIN\n\n CELL(1) <= NUMBERS[CELL(0), COUNT]; /*iterate over the states of this door to get its final state*/\n IF CELL(1) = 1, THEN: /*door state = open*/\n PRINT[CELL(0), ' '];\n \n CELL(0) <= CELL(0) + 1;\n\n BLOCK 1: END;\nBLOCK 0: END.\n\nDOORS[100];", "safe": true }, { "filename": "100 doors_117.txt", "content": " > 1 \n > 4 \n > 9 \n > 16 \n > 25 \n > 36 \n > 49 \n > 64 \n > 81 \n > 100 \n", "safe": true }, { "filename": "100 doors_118.txt", "content": "( 100doors-tbl\n= door step\n . tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }\n & 0:?step\n & whl\n ' ( 1+!step:~>100:?step { ~> means 'not greater than', i.e. 'less than or equal' }\n & 0:?door\n & whl\n ' ( !step+!door:~>100:?door\n & 1+-1*!(!door$doors):?doors { $ sets the current index, which stays the same until explicitly changed. }\n )\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & out\n $ ( door\n !door\n is\n (\u00a0!(!door$doors):1&open\n | closed\n )\n )\n )\n & tbl$(doors.0) { clean up the array }\n)", "safe": true }, { "filename": "100 doors_119.txt", "content": "( 100doors-var\n= step door\n . 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & closed:?!door { this creates a variable and assigns a value 'closed' to it }\n )\n & 0:?step\n & whl\n ' ( 1+!step:~>100:?step\n & 0:?door\n & whl\n ' ( !step+!door:~>100:?door\n & (\u00a0!!door:closed&open\n | closed\n )\n \u00a0:\u00a0?!door \n )\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & out$(door !door is\u00a0!!door)\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & tbl$(!door.0) { cleanup the variable }\n )\n)", "safe": true }, { "filename": "100 doors_12.txt", "content": "\\ Array of doors; init to empty; accessing a non-extant member will return\n\\ 'null', which is treated as 'false', so we don't need to initialize it:\n[] var, doors \n\n\\ given a door number, get the value and toggle it:\n: toggle-door \\ n --\n\tdoors @ over a:@\n\tnot rot swap a:! drop ;\n\n\\ print which doors are open:\n: .doors\n\t( \n\t\tdoors @ over a:@ nip\n\t\tif . space else drop then\n\t) 1 100 loop ;\n\n\\ iterate over the doors, skipping 'n':\n: main-pass \\ n --\n\t0\n\ttrue\n\trepeat\n\t\tdrop\n\t\tdup toggle-door\n\t\tover n:+\n\t\tdup 101 <\n\twhile 2drop drop ;\n\n\\ calculate the first 100 doors:\n' main-pass 1 100 loop\n\\ print the results:\n.doors cr bye\n", "safe": true }, { "filename": "100 doors_120.txt", "content": "( 100doors-list\n= doors door doorIndex step\n . \u00a0:?doors\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & closed !doors:?doors\n )\n & 0:?skip\n & whl\n ' (\u00a0:?ndoors\n & whl\n ' ( !doors:?skipped [!skip\u00a0%?door ?doors { the [ pattern only succeeds when the scanning cursor is at position }\n & !ndoors\n !skipped\n ( !door:open&closed\n | open\n )\n \u00a0: ?ndoors\n )\n & !ndoors !doors:?doors\n & 1+!skip:<100:?skip\n )\n & out$!doors\n)", "safe": true }, { "filename": "100 doors_121.txt", "content": "( 100doors-obj\n= doors door doorIndex step\n . \u00a0:?doors\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & new$(=closed) !doors:?doors\n )\n & 0:?skip\n & whl\n ' ( !doors:?tododoors\n & whl\n ' ( !tododoors:? [!skip\u00a0%?door ?tododoors\n & (\u00a0!(door.):open&closed\n | open\n )\n \u00a0:\u00a0?(door.)\n )\n & 1+!skip:<100:?skip\n )\n & out$!doors\n)", "safe": true }, { "filename": "100 doors_122.txt", "content": "100doors-tbl$\n& 100doors-var$\n& 100doors-list$\n& 100doors-obj$;", "safe": true }, { "filename": "100 doors_123.txt", "content": "blsq ) 10ro2?^\n{1 4 9 16 25 36 49 64 81 100}", "safe": true }, { "filename": "100 doors_124.txt", "content": "swch \u2190 \u2260\u00b4{100\u294a1\u00ab\ud835\udd69\u294a0}\u00a81+\u2195100\n\u00af1\u2193\u223e{\ud835\udd69\u223e@+10}\u00a8\u2022Fmt\u00a8\u27e8swch,/swch\u27e9\n", "safe": true }, { "filename": "100 doors_125.txt", "content": "\"\u27e8 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \u27e9\n\u27e8 0 3 8 15 24 35 48 63 80 99 \u27e9\"\n", "safe": true }, { "filename": "100 doors_126.txt", "content": "swch\n", "safe": true }, { "filename": "100 doors_127.txt", "content": "#include \n\nint main()\n{\n char is_open[100] = { 0 };\n int pass, door;\n\n /* do the 100 passes */\n for (pass = 0; pass < 100; ++pass)\n for (door = pass; door < 100; door += pass+1)\n is_open[door] = !is_open[door];\n\n /* output the result */\n for (door = 0; door < 100; ++door)\n printf(\"door #%d is %s.\\n\", door+1, (is_open[door]? \"open\" : \"closed\"));\n\n return 0;\n}\n", "safe": true }, { "filename": "100 doors_128.txt", "content": "#include \n\n#define NUM_DOORS 100\n\nint main(int argc, char *argv[])\n{\n int is_open[NUM_DOORS] = { 0 } ;\n int * doorptr, * doorlimit = is_open + NUM_DOORS ;\n int pass ;\n\n /* do the N passes, go backwards because the order is not important */\n for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) {\n for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) {\n ( * doorptr ) ^= 1 ;\n }\n }\n\n /* output results */\n for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) {\n printf(\"door #%lld is %s\\n\", ( doorptr - is_open ) + 1, ( * doorptr ) ? \"open\" : \"closed\" ) ;\n }\n}\n", "safe": true }, { "filename": "100 doors_129.txt", "content": "#include \n\nint main()\n{\n int square = 1, increment = 3, door;\n for (door = 1; door <= 100; ++door)\n {\n printf(\"door #%d\", door);\n if (door == square)\n {\n printf(\" is open.\\n\");\n square += increment;\n increment += 2;\n }\n else\n printf(\" is closed.\\n\");\n }\n return 0;\n}\n", "safe": true }, { "filename": "100 doors_13.txt", "content": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program 100doors64.s */\n \n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"The door @ is open.\\n\"\n \n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \nstTableDoors: .skip 8 * NBDOORS\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: // entry of program \n // display first line\n ldr x3,qAdrstTableDoors // table address\n mov x5,1 \n1:\n mov x4,x5\n2: // begin loop\n ldr x2,[x3,x4,lsl #3] // read doors index x4\n cmp x2,#0\n cset x2,eq\n //moveq x2,#1 // if x2 = 0 1 -> x2\n //movne x2,#0 // if x2 = 1 0 -> x2\n str x2,[x3,x4,lsl #3] // store value of doors\n add x4,x4,x5 // increment x4 with x5 value\n cmp x4,NBDOORS // number of doors\u00a0?\n ble 2b // no -> loop\n add x5,x5,#1 // increment the increment\u00a0!!\n cmp x5,NBDOORS // number of doors\u00a0?\n ble 1b // no -> loop\n \n // loop display state doors\n mov x4,#0 \n3:\n ldr x2,[x3,x4,lsl #3] // read state doors x4 index\n cmp x2,#0\n beq 4f\n mov x0,x4 // open -> display message\n ldr x1,qAdrsZoneConv // display value index\n bl conversion10 // call function\n ldr x0,qAdrsMessResult\n ldr x1,qAdrsZoneConv \n bl strInsertAtCharInc // insert result at first @ character\n bl affichageMess // display message\n4:\n add x4,x4,1\n cmp x4,NBDOORS\n ble 3b // loop\n \n \n100: // standard end of the program \n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n \nqAdrstTableDoors: .quad stTableDoors\nqAdrsMessResult: .quad sMessResult\nqAdrsZoneConv: .quad sZoneConv\n/***********************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"", "safe": true }, { "filename": "100 doors_130.txt", "content": "#include \n\nint main()\n{\n int door, square, increment;\n for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2))\n printf(\"door #%d is %s.\\n\", door, (door == square? \"open\" : \"closed\"));\n return 0;\n}\n", "safe": true }, { "filename": "100 doors_131.txt", "content": "#include \n\nint main()\n{\n\tint i;\n\tfor (i = 1; i * i <= 100; i++)\n\t\tprintf(\"door %d open\\n\", i * i);\n\n\treturn 0;\n}\n", "safe": true }, { "filename": "100 doors_132.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main(string[] args)\n {\n bool[] doors = new bool[100];\n\n //Close all doors to start.\n for (int d = 0; d < 100; d++) doors[d] = false;\n\n //For each pass...\n for (int p = 0; p < 100; p++)//number of passes\n {\n //For each door to toggle...\n for (int d = 0; d < 100; d++)//door number\n {\n if ((d + 1) % (p + 1) == 0)\n {\n doors[d] = !doors[d];\n }\n }\n }\n\n //Output the results.\n Console.WriteLine(\"Passes Completed!!! Here are the results: \\r\\n\");\n for (int d = 0; d < 100; d++)\n {\n if (doors[d])\n {\n Console.WriteLine(String.Format(\"Door #{0}: Open\", d + 1));\n }\n else\n {\n Console.WriteLine(String.Format(\"Door #{0}: Closed\", d + 1));\n }\n }\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100 doors_133.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main(string[] args)\n {\n //Perform the operation.\n bool[] doors = new bool[100];\n int n = 0;\n int d;\n while ((d = (++n * n)) <= 100)\n doors[d - 1] = true;\n\n //Perform the presentation.\n for (d = 0; d < doors.Length; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d + 1, doors[d] ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100 doors_134.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main()\n {\n bool[] doors = new bool[100];\n\n //The number of passes can be 1-based, but the number of doors must be 0-based.\n for (int p = 1; p <= 100; p++)\n for (int d = p - 1; d < 100; d += p)\n doors[d] = !doors[d];\n for (int d = 0; d < 100; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d + 1, doors[d] ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100 doors_135.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main()\n {\n double n;\n\n //If the current door number is the perfect square of an integer, say it is open, else say it is closed.\n for (int d = 1; d <= 100; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d, (n = Math.Sqrt(d)) == (int)n ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100 doors_136.txt", "content": "using System;\nusing System.IO;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n Console.Clear();\n Console.WriteLine(\"Input a number of doors to calculate, then press enter\");\n StartCalculator();\n }\n \n static void StartCalculator()\n {\n //The number to calculate is input here\n string input = Console.ReadLine();\n Console.Clear();\n \n try\n {\n //The program attempts to convert the string to an int\n //Exceptions will be caught on this line\n int numberOfDoors = Convert.ToInt32(input);\n \n //Will call method recursively if input number is less than 1\n if (numberOfDoors <= 0)\n {\n Console.WriteLine(\"Please use a number greater than 0\");\n StartCalculator();\n }\n \n //The program then starts the calculation process\n Calculate(numberOfDoors);\n \n //After calculation process is finished, restart method is called\n RestartCalculator();\n }\n catch(FormatException)\n {\n //Code will be executed if the number has a decimal or has an unrecognizable symbol\n Console.WriteLine(\"Unable to read. Please use a real number without a decimal\");\n StartCalculator();\n }\n catch (OverflowException)\n {\n //Code will be executed if number is too long\n Console.WriteLine(\"You number is too long\");\n StartCalculator();\n }\n }\n \n static void Calculate(int numberOfDoors)\n {\n //Increases numberOfDoors by 1 since array starts at 0\n numberOfDoors++;\n \n //Dictionary key represents door number, value represents if the door is open\n //if value == true, the door is open\n Dictionary doors = new Dictionary();\n \n //Creates Dictionary size of numberOfDoors, all initialized at false\n for(int i = 0; i < numberOfDoors; i++)\n {\n doors.Add(i, false);\n }\n \n //Creates interval between doors, starting at 0, while less than numberOfDoors\n for (int doorInterval = 0; doorInterval < numberOfDoors; doorInterval++)\n {\n //Will alter every cubby at doorInterval\n //1 needs to be added since doorInterval will start at 0 and end when equal to numberOfDoors\n for(int i = 0; i < numberOfDoors; i += doorInterval + 1)\n {\n //Changes a false value to true and vice versa\n doors[i] = doors[i] ? false: true;\n }\n }\n \n //Writes each door and whether it is open or closed\n for(int i = 0; i < numberOfDoors; i++)\n {\n //Skips over door 0\n if (i == 0) continue;\n //Writes open if door value is true, writes closed if door value is false\n Console.WriteLine(\"Door \" + (i) + \" is \" + (doors[i] ? \"open\" : \"closed\"));\n }\n }\n \n static void RestartCalculator()\n { \n Console.WriteLine(\"Press any key to restart\");\n Console.ReadKey(true);\n Main();\n }\n}\n", "safe": true }, { "filename": "100 doors_137.txt", "content": "#include \n\nint main()\n{\n bool is_open[100] = { false };\n\n // do the 100 passes\n for (int pass = 0; pass < 100; ++pass)\n for (int door = pass; door < 100; door += pass+1)\n is_open[door] = !is_open[door];\n\n // output the result\n for (int door = 0; door < 100; ++door)\n std::cout << \"door #\" << door+1 << (is_open[door]? \" is open.\" : \" is closed.\") << std::endl;\n return 0;\n}\n", "safe": true }, { "filename": "100 doors_138.txt", "content": "#include \n\nint main()\n{\n int square = 1, increment = 3;\n for (int door = 1; door <= 100; ++door)\n {\n std::cout << \"door #\" << door;\n if (door == square)\n {\n std::cout << \" is open.\" << std::endl;\n square += increment;\n increment += 2;\n }\n else\n std::cout << \" is closed.\" << std::endl;\n }\n return 0;\n}\n", "safe": true }, { "filename": "100 doors_139.txt", "content": "#include //compiled with \"Dev-C++\" , from RaptorOne\n\nint main()\n{\n for(int i=1; i*i<=100; i++)\n std::cout<<\"Door \"< // compiled with clang (tags/RELEASE_600/final)\n#include // or g++ (GCC) 7.3.1 20180406 -- from hare1039\nnamespace functional_list // basic building block for template meta programming\n{\nstruct NIL\n{\n\tusing head = NIL;\n\tusing tail = NIL;\n\tfriend std::ostream& operator << (std::ostream& os, NIL const) { return os; }\n};\n\ntemplate \nstruct list\n{\n\tusing head = H;\n\tusing tail = T;\n};\n\ntemplate \nstruct integer\n{\n\tstatic constexpr int value = i;\n\tfriend std::ostream& operator << (std::ostream& os, integer const) { os << integer::value; return os;}\n};\n\ntemplate constexpr\nauto at()\n{\n\tif constexpr (nTH == 0)\n\t\treturn (typename L::head){};\n\telse if constexpr (not std::is_same_v) \n\t\treturn at();\n\telse\n\t\treturn NIL{};\n}\ntemplate \nusing at_t = decltype(at());\n\ntemplate constexpr\nauto prepend() { return list{}; }\n\ntemplate \nusing prepend_t = decltype(prepend());\n\t\ntemplate > constexpr\nauto gen_list()\n{\n\tif constexpr (Size == 0)\n\t\treturn NIL{};\n\telse\n\t{\n\t\tusing next = decltype(gen_list());\n\t\treturn prepend();\n\t}\n}\ntemplate >\nusing gen_list_t = decltype(gen_list());\n\t\n} namespace fl = functional_list;\n\nconstexpr int door_amount = 101; // index from 1 to 100\n\ntemplate constexpr\nauto construct_loop()\n{\n\tusing val_t = fl::at_t;\n\tif constexpr (std::is_same_v)\n\t\treturn fl::NIL{};\n\telse\n\t{\n\t\tconstexpr int val = val_t::value;\n\t\tusing val_add_t = fl::integer;\n\t\tusing val_old_t = fl::integer;\n\t\n\t\tif constexpr (current == door_amount)\n\t\t{\n\t\t\tif constexpr(current % moder == 0)\n\t\t\t\treturn fl::list{};\n\t\t\telse\n\t\t\t\treturn fl::list{};\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusing sub_list = decltype(construct_loop());\n\t\t\tif constexpr(current % moder == 0)\n\t\t\t\treturn fl::prepend();\n\t\t\telse\n\t\t\t\treturn fl::prepend();\n\t\t}\n\t}\n}\n\ntemplate constexpr\nauto construct()\n{\n\tif constexpr (iteration == 1) // door index = 1\n\t{\n\t\tusing l = fl::gen_list_t;\n\t\treturn construct_loop();\n\t}\n\telse\n\t{\n\t\tusing prev_iter_list = decltype(construct());\n\t\treturn construct_loop();\n\t}\n}\n\ntemplate constexpr\nvoid show_ans()\n{\n\tif constexpr (std::is_same_v)\n\t\treturn;\n\telse\n\t{\n\t\tif constexpr (L::head::value % 2 == 1)\n\t\t\tstd::cout << \"Door \" << pos << \" is opened.\\n\";\n\t\tshow_ans();\n\t}\n}\n\nint main()\n{\n\tusing result = decltype(construct<100>());\n\tshow_ans();\n}\n", "safe": true }, { "filename": "100 doors_141.txt", "content": "100_doors\n", "safe": true }, { "filename": "100 doors_142.txt", "content": " for i=1:1:100 {\n\t set doors(i) = 0\n }\n for i=1:1:100 {\n\t for door=i:i:100 {\n\t\t Set doors(door)='doors(door)\n\t }\n }\n for i = 1:1:100\n {\n\tif doors(i)=1 write i_\": open\",!\n }\n", "safe": true }, { "filename": "100 doors_143.txt", "content": "1: open\n4: open\n9: open\n16: open\n25: open\n36: open\n49: open\n64: open\n81: open\n100: open\n", "safe": true }, { "filename": "100 doors_144.txt", "content": "shared void run() {\n print(\"Open doors (naive): ``naive()``\n Open doors (optimized): ``optimized()``\");\n \n}\n\nshared {Integer*} naive(Integer count = 100) {\n variable value doors = [ for (_ in 1..count) closed ];\n for (step in 1..count) {\n doors = [for (i->door in doors.indexed) let (index = i+1) if (step == 1 || step.divides(index)) then door.toggle() else door ];\n }\n return doors.indexesWhere((door) => door == opened).map(1.plusInteger);\n}\n\nshared {Integer*} optimized(Integer count = 100) =>\n { for (i in 1..count) i*i }.takeWhile(count.notSmallerThan);\n\n\nshared abstract class Door(shared actual String string) of opened | closed {\n shared formal Door toggle();\n}\nobject opened extends Door(\"opened\") { toggle() => closed; }\nobject closed extends Door(\"closed\") { toggle() => opened; }\n", "safe": true }, { "filename": "100 doors_145.txt", "content": "Open doors (naive): { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }\nOpen doors (optimized): { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }", "safe": true }, { "filename": "100 doors_146.txt", "content": " program\n\n map\n end\n\nMAX_DOOR_NUMBER equate(100)\nCRLF equate('<13,10>')\n\nDoors byte,dim(MAX_DOOR_NUMBER)\nPass byte\nDoorNumber byte\nDisplayString cstring(2000)\n\nResultWindow window('Result'),at(,,133,291),center,double,auto\n prompt('Door states:'),at(8,4),use(?PromptTitle)\n text,at(8,16,116,266),use(DisplayString),boxed,vscroll,font('Courier New',,,,CHARSET:ANSI),readonly\n end\n\n code\n\n Doors\u00a0:=: false\n loop Pass = 1 to MAX_DOOR_NUMBER\n loop DoorNumber = Pass to MAX_DOOR_NUMBER by Pass\n Doors[DoorNumber] = choose(Doors[DoorNumber], false, true)\n end\n end\n\n clear(DisplayString)\n loop DoorNumber = 1 to MAX_DOOR_NUMBER\n DisplayString = DisplayString & format(DoorNumber, @n3) & ' is ' & choose(Doors[DoorNumber], 'opened', 'closed') & CRLF\n end\n open(ResultWindow)\n accept\n end\n close(ResultWindow)\n\n return", "safe": true }, { "filename": "100 doors_147.txt", "content": "fn visit-doors doors step:\n if step > 100: doors\n else:\n [1:100]\n -> * fn index:\n if index\u00a0% step: doors[(index - 1)]\n else: not doors[(index - 1)]\n -> visit-doors (step + 1)\n\n[1:100] -> * n: false -> visit-doors 1 => doors\n[1:100] -> * (@eager) fn i:\n doors[(i - 1)]\n -> if = true: #open\n else: #closed\n -> print #Door i #is @", "safe": true }, { "filename": "100 doors_148.txt", "content": "[1:100] -> * (@eager) fn i:\n i ^ 0.5\n -> eq @ (transform i: floor)\n -> if = true: #open\n else: #closed\n -> print #Door i #is @", "safe": true }, { "filename": "100 doors_149.txt", "content": "(deffacts initial-state\n (door-count 100)\n)\n\n(deffunction toggle\n (?state)\n (switch ?state\n (case \"open\" then \"closed\")\n (case \"closed\" then \"open\")\n )\n)\n\n(defrule create-doors-and-visits\n (door-count ?count)\n =>\n (loop-for-count (?num 1 ?count) do\n (assert (door ?num \"closed\"))\n (assert (visit-from ?num ?num))\n )\n (assert (doors initialized))\n)\n\n(defrule visit\n (door-count ?max)\n ?visit <- (visit-from ?num ?step)\n ?door <- (door ?num ?state)\n =>\n (retract ?visit)\n (retract ?door)\n (assert (door ?num (toggle ?state)))\n (if\n (<= (+ ?num ?step) ?max)\n then\n (assert (visit-from (+ ?num ?step) ?step))\n )\n)\n\n(defrule start-printing\n (doors initialized)\n (not (visit-from\u00a0?\u00a0?))\n =>\n (printout t \"These doors are open:\" crlf)\n (assert (print-from 1))\n)\n\n(defrule print-door\n (door-count ?max)\n ?pf <- (print-from ?num)\n (door ?num ?state)\n =>\n (retract ?pf)\n (if\n (= 0 (str-compare \"open\" ?state))\n then\n (printout t ?num \" \")\n )\n (if\n (< ?num ?max)\n then\n (assert (print-from (+ ?num 1)))\n else\n (printout t crlf \"All other doors are closed.\" crlf)\n )\n)", "safe": true }, { "filename": "100 doors_15.txt", "content": "form open_doors_unopt.\n data: lv_door type i,\n lv_count type i value 1.\n data: lt_doors type standard table of c initial size 100.\n field-symbols: type c.\n do 100 times.\n append initial line to lt_doors assigning .\n = 'X'.\n enddo.\n\n while lv_count < 100.\n lv_count = lv_count + 1.\n lv_door = lv_count.\n while lv_door < 100.\n read table lt_doors index lv_door assigning .\n if = ' '.\n = 'X'.\n else.\n = ' '.\n endif.\n add lv_count to lv_door.\n endwhile.\n endwhile.\n\n loop at lt_doors assigning .\n if = 'X'.\n write : / 'Door', (4) sy-tabix right-justified, 'is open' no-gap.\n endif.\n endloop.\nendform.\n", "safe": true }, { "filename": "100 doors_150.txt", "content": "(deffacts initial-state\n (door-count 100)\n)\n\n(deffunction is-square\n (?num)\n (= (sqrt ?num) (integer (sqrt ?num)))\n)\n\n(defrule check-doors\n (door-count ?count)\n =>\n (printout t \"These doors are open:\" crlf)\n (loop-for-count (?num 1 ?count) do\n (if (is-square ?num) then\n (printout t ?num \" \")\n )\n )\n (printout t crlf \"All other doors are closed.\" crlf)\n)", "safe": true }, { "filename": "100 doors_151.txt", "content": "(defn doors []\n (let [doors (into-array (repeat 100 false))]\n (doseq [pass (range 1 101) \n i (range (dec pass) 100 pass) ]\n (aset doors i (not (aget doors i))))\n doors)) \n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100 doors_152.txt", "content": "(defn doors []\n (reduce (fn [doors toggle-idx] (update-in doors [toggle-idx] not))\n (into [] (repeat 100 false))\n (for [pass (range 1 101)\n i (range (dec pass) 100 pass) ]\n i)))\n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100 doors_153.txt", "content": "(defn open-doors []\n (->> (for [step (range 1 101), occ (range step 101 step)] occ)\n frequencies\n (filter (comp odd? val))\n keys\n sort))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100 doors_154.txt", "content": "(defn doors []\n\t(reduce (fn [doors idx] (assoc doors idx true)) \n\t (into [] (repeat 100 false))\n\t (map #(dec (* % %)) (range 1 11))))\n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100 doors_155.txt", "content": "(defn open-doors [] (->> (iterate inc 1) (map #(* % %)) (take-while #(<= % 100))))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100 doors_156.txt", "content": "start_up = proc ()\n max = 100\n po: stream\u00a0:= stream$primary_output()\n open: array[bool]\u00a0:= array[bool]$fill(1, max, false)\n\n for pass: int in int$from_to(1, max) do\n for door: int in int$from_to_by(pass, max, pass) do\n open[door]\u00a0:= ~open[door]\n end\n end\n\n for door: int in array[bool]$indexes(open) do\n if open[door] then\n stream$putl(po, \"Door \" || int$unparse(door) || \" is open.\")\n end\n end\nend start_up", "safe": true }, { "filename": "100 doors_157.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_158.txt", "content": " IDENTIFICATION DIVISION.\n PROGRAM-ID. 100Doors.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 Current-n PIC 9(3).\n 01 StepSize PIC 9(3).\n 01 DoorTable.\n 02 Doors PIC 9(1) OCCURS 100 TIMES.\n 88 ClosedDoor VALUE ZERO.\n 01 Idx PIC 9(3).\n\n PROCEDURE DIVISION.\n Begin.\n INITIALIZE DoorTable\n PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100\n PERFORM VARYING Current-n FROM StepSize BY StepSize\n UNTIL Current-n > 100\n SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n)\n END-PERFORM\n END-PERFORM\n\n PERFORM VARYING Idx FROM 1 BY 1\n UNTIL Idx > 100\n IF ClosedDoor (Idx)\n DISPLAY Idx \" is closed.\"\n ELSE\n DISPLAY Idx \" is open.\"\n END-IF\n END-PERFORM\n\n STOP RUN\n .\n", "safe": true }, { "filename": "100 doors_159.txt", "content": "doors = [false] * 100\n\nfor pass til doors.length\n for i from pass til doors.length by pass + 1\n \u00a0! = doors[i]\n\nfor i til doors.length\n console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed'", "safe": true }, { "filename": "100 doors_16.txt", "content": "cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab\n aux TYPE i\n FOR door = 1 WHILE door <= 100\n FOR pass = 1 WHILE pass <= 100\n NEXT aux = COND #( WHEN pass = 1 THEN 1\n WHEN door MOD pass = 0 THEN aux + 1 ELSE aux )\n list = COND #( WHEN pass = 100\n THEN COND #( WHEN aux MOD 2 <> 0 THEN VALUE #( BASE list ( CONV #( door ) ) )\n ELSE list ) ELSE list ) ) ).\n", "safe": true }, { "filename": "100 doors_160.txt", "content": "doors = []\n \nfor pass in [1..100]\n for i in [pass..100] by pass\n doors[i] = !doors[i]\n \nconsole.log \"Doors #{index for index, open of doors when open} are open\"\n \n# matrix output\nconsole.log doors.map (open) -> +open\n", "safe": true }, { "filename": "100 doors_161.txt", "content": "isInteger = (i) -> Math.floor(i) == i\n\nconsole.log door for door in [1..100] when isInteger Math.sqrt door\n", "safe": true }, { "filename": "100 doors_162.txt", "content": "console.log Math.pow(i,2) for i in [1..10]\n", "safe": true }, { "filename": "100 doors_163.txt", "content": "\tdoorCount = 1;\n\tdoorList = \"\";\n\t// create all doors and set all doors to open\n\twhile (doorCount LTE 100) {\n\t\tdoorList = ListAppend(doorList,\"1\");\n\t\tdoorCount = doorCount + 1;\n\t}\n\tloopCount = 2;\n\tdoorListLen = ListLen(doorList);\n\twhile (loopCount LTE 100) {\n\t\tloopDoorListCount = 1;\n\t\twhile (loopDoorListCount LTE 100) {\n\t\t\ttestDoor = loopDoorListCount / loopCount;\n\t\t\tif (testDoor EQ Int(testDoor)) {\n\t\t\t\tcheckOpen = ListGetAt(doorList,loopDoorListCount);\n\t\t\t\tif (checkOpen EQ 1) {\n\t\t\t\t\tdoorList = ListSetAt(doorList,loopDoorListCount,\"0\");\n\t\t\t\t} else {\n\t\t\t\t\tdoorList = ListSetAt(doorList,loopDoorListCount,\"1\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tloopDoorListCount = loopDoorListCount + 1;\n\t\t}\n\t\tloopCount = loopCount + 1;\n\t}", "safe": true }, { "filename": "100 doors_164.txt", "content": "\tdoorCount = 1;\n\tdoorList = \"\";\n\tloopCount = 1;\n\twhile (loopCount LTE 100) {\n\t\tif (Sqr(loopCount) NEQ Int(Sqr(loopCount))) {\n\t\t\tdoorList = ListAppend(doorList,0);\n\t\t} else {\n\t\t\tdoorList = ListAppend(doorList,1);\n\t\t}\n\t\tloopCount = loopCount + 1;\n\t}", "safe": true }, { "filename": "100 doors_165.txt", "content": "// Display all doors\n\n Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#
\n
\n\n// Output only open doors\n\n \n #x#
\n
\n
\n", "safe": true }, { "filename": "100 doors_166.txt", "content": "\n\n \n\n\n \n \n \n \n \n \n \n\n#doorlist#\n", "safe": true }, { "filename": "100 doors_167.txt", "content": "0010 DIM doors#(100)\n0020 FOR pass#:=1 TO 100 DO\n0030 FOR door#:=pass# TO 100 STEP pass# DO doors#(door#):=NOT doors#(door#)\n0040 ENDFOR pass#\n0050 FOR door#:=1 TO 100 DO\n0060 IF doors#(door#) THEN PRINT \"Door \",door#,\" is open.\"\n0070 ENDFOR door#\n0080 END\n", "safe": true }, { "filename": "100 doors_168.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_169.txt", "content": "10 D=100: DIMD(D): P=1\n20 PRINT CHR$(147);\"PASS: \";P\n22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT\n30 IF P=100 THEN 40\n32 P=P+1: GOTO20\n40 PRINT: PRINT\"THE FOLLOWING DOORS ARE OPEN: \"\n42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI;\n44 NEXT\n", "safe": true }, { "filename": "100 doors_17.txt", "content": "form open_doors_opt.\n data: lv_square type i value 1,\n lv_inc type i value 3.\n data: lt_doors type standard table of c initial size 100.\n field-symbols: type c.\n do 100 times.\n append initial line to lt_doors assigning .\n if sy-index = lv_square.\n = 'X'.\n add: lv_inc to lv_square, 2 to lv_inc.\n write : / 'Door', (4) sy-index right-justified, 'is open' no-gap.\n endif.\n enddo.\nendform.\n", "safe": true }, { "filename": "100 doors_170.txt", "content": "(defun visit-door (doors doornum value1 value2)\n \"visits a door, swapping the value1 to value2 or vice-versa\"\n (let ((d (copy-list doors))\n (n (- doornum 1)))\n (if (eql (nth n d) value1)\n (setf (nth n d) value2)\n (setf (nth n d) value1))\n d))\n\n(defun visit-every (doors num iter value1 value2)\n \"visits every 'num' door in the list\"\n (if (> (* iter num) (length doors))\n doors\n (visit-every (visit-door doors (* num iter) value1 value2)\n num\n (+ 1 iter)\n value1\n value2)))\n\n(defun do-all-visits (doors cnt value1 value2)\n \"Visits all doors changing the values accordingly\"\n (if (< cnt 1)\n doors\n (do-all-visits (visit-every doors cnt 1 value1 value2)\n (- cnt 1)\n value1\n value2)))\n\n(defun print-doors (doors)\n \"Pretty prints the doors list\"\n (format T \"~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%\" doors))\n\n(defun start (&optional (size 100))\n \"Start the program\"\n (let* ((open \"_\")\n (shut \"#\")\n (doors (make-list size :initial-element shut)))\n (print-doors (do-all-visits doors size open shut))))\n", "safe": true }, { "filename": "100 doors_171.txt", "content": "(define-modify-macro toggle () not)\n\n(defun 100-doors ()\n (let ((doors (make-array 100)))\n (dotimes (i 100)\n (loop for j from i below 100 by (1+ i)\n\t do (toggle (svref doors j))))\n (dotimes (i 100)\n (format t \"door ~a: ~:[closed~;open~]~%\" (1+ i) (svref doors i)))))\n", "safe": true }, { "filename": "100 doors_172.txt", "content": "(defun doors (z &optional (w (make-list z)) (n 1))\n (if (> n z) w (doors z (toggle w n z) (1+ n))))\n\n(defun toggle (w m z)\n (loop for a in w for n from 1 to z\n collect (if (zerop (mod n m)) (not a) a)))\n\n> (doors 100)\n(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)\n", "safe": true }, { "filename": "100 doors_173.txt", "content": "(defun doors (n)\n (loop for a from 1 to n collect\n (zerop (mod (sqrt a) 1))))\n \n> (doors 100)\n(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)\n", "safe": true }, { "filename": "100 doors_174.txt", "content": "(defun 100-doors ()\n (let ((doors (make-array 100)))\n (dotimes (i 10)\n (setf (svref doors (* i i)) t))\n (dotimes (i 100)\n (format t \"door ~a: ~:[closed~;open~]~%\" (1+ i) (svref doors i)))))\n", "safe": true }, { "filename": "100 doors_175.txt", "content": "(defun perfect-square-list (n) \n \"Generates a list of perfect squares from 0 up to n\"\n (loop for i from 1 to (isqrt n) collect (expt i 2))) \n \n(defun print-doors (doors)\n \"Pretty prints the doors list\"\n (format T \"~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%\" doors))\n\n(defun open-door (doors num open)\n \"Sets door at num to open\"\n (setf (nth (- num 1) doors) open)) \n\n(defun visit-all (doors vlist open)\n \"Visits and opens all the doors indicated in vlist\"\n (dolist (dn vlist doors)\n (open-door doors dn open)))\n\n(defun start2 (&optional (size 100)) \n \"Start the program\"\n (print-doors\n (visit-all (make-list size :initial-element '\\#)\n (perfect-square-list size)\n '_)))\n", "safe": true }, { "filename": "100 doors_176.txt", "content": "(let ((i 0))\n (mapcar (lambda (x)\n (if (zerop (mod (sqrt (incf i)) 1))\n \"_\" \"#\"))\n (make-list 100)))\n", "safe": true }, { "filename": "100 doors_177.txt", "content": "MODULE Doors100;\nIMPORT StdLog;\n\nPROCEDURE Do*;\nVAR\n\ti,j: INTEGER;\n\tclosed: ARRAY 101 OF BOOLEAN;\nBEGIN\n\t(* initialization of closed to true *)\n\tFOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END;\n\t(* process *)\n\tFOR i := 1 TO LEN(closed) DO;\n\t\tj := 1;\n\t\tWHILE j < LEN(closed) DO\n\t\t\tIF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j)\n\t\tEND\n\tEND;\n\t(* print results *)\n\ti := 1;\n\tWHILE i < LEN(closed) DO\n\t\tIF (i - 1) MOD 10 = 0 THEN StdLog.Ln END;\n\t\tIF closed[i] THEN StdLog.String(\"C \") ELSE StdLog.String(\"O \") END;\n\t\tINC(i) \n\tEND;\nEND Do;\nEND Doors100.\n", "safe": true }, { "filename": "100 doors_178.txt", "content": "O C C O C C C C O C \nC C C C C O C C C C \nC C C C O C C C C C \nC C C C C O C C C C \nC C C C C C C C O C \nC C C C C C C C C C \nC C C O C C C C C C \nC C C C C C C C C C \nO C C C C C C C C C \nC C C C C C C C C O \n", "safe": true }, { "filename": "100 doors_179.txt", "content": "Require Import List.\n\nFixpoint rep {A} (a : A) n :=\n match n with\n | O => nil\n | S n' => a::(rep a n')\n end.\n\nFixpoint flip (l : list bool) (n k : nat) : list bool :=\n match l with\n | nil => nil\n | cons h t => match k with\n | O => (negb h) :: (flip t n n)\n | S k' => h :: (flip t n k')\n end\n end.\n\nDefinition flipeach l n := flip l n n.\n\nFixpoint flipwhile l n :=\n match n with\n | O => flipeach l 0\n | S n' => flipwhile (flipeach l (S n')) n'\n end.\n\nDefinition prison cells := flipwhile (rep false cells) cells.\n", "safe": true }, { "filename": "100 doors_18.txt", "content": "DO 10 TIMES.\n DATA(val) = sy-index * sy-index.\n WRITE: / val.\nENDDO.\n", "safe": true }, { "filename": "100 doors_180.txt", "content": "Require Import List.\n\nFixpoint prisoo' nd n k accu :=\n match nd with\n | O => rev accu\n | S nd' => let ra := match k with\n | O => (true, S n, (n + n))\n | S k' => (false, n, k')\n end in\n prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu)\n end.\n\nDefinition prisoo cells := prisoo' cells 1 0 nil.\n", "safe": true }, { "filename": "100 doors_181.txt", "content": "Goal prison 100 = prisoo 100. compute. reflexivity. Qed.", "safe": true }, { "filename": "100 doors_182.txt", "content": "Goal forall n, prison n = prisoo n. Abort.", "safe": true }, { "filename": "100 doors_183.txt", "content": "include \"cowgol.coh\";\n\nvar doors: uint8[101]; # one extra so we can start at 1\nvar pass: @indexof doors;\nvar door: @indexof doors;\n\nMemZero(&doors as [uint8], @bytesof doors);\n\npass\u00a0:= 1;\nwhile pass <= 100 loop\n door\u00a0:= pass;\n while door <= 100 loop\n doors[door]\u00a0:= 1-doors[door];\n door\u00a0:= door + pass;\n end loop;\n pass\u00a0:= pass + 1;\nend loop;\n\ndoor\u00a0:= 1;\nwhile door <= 100 loop\n if doors[door] == 1 then\n print_i8(door);\n print(\" is open\\n\");\n end if;\n door\u00a0:= door + 1;\nend loop;", "safe": true }, { "filename": "100 doors_184.txt", "content": "1 is open\n4 is open\n9 is open\n16 is open\n25 is open\n36 is open\n49 is open\n64 is open\n81 is open\n100 is open", "safe": true }, { "filename": "100 doors_185.txt", "content": "do\n\n\tlet i = i + 1\n\tprint i * i, \" \",\n\nloop i * i < 100", "safe": true }, { "filename": "100 doors_186.txt", "content": "1 4 9 16 25 36 49 64 81 100 ", "safe": true }, { "filename": "100 doors_187.txt", "content": "doors = Array.new(100, false)\n\n1.upto(100) do |i|\n i.step(by: i, to: 100) do |j|\n doors[j - 1] = !doors[j - 1]\n end\nend\n\ndoors.each_with_index do |open, i|\n puts \"Door #{i + 1} is #{open\u00a0? \"open\"\u00a0: \"closed\"}\"\nend", "safe": true }, { "filename": "100 doors_188.txt", "content": "import std.stdio;\nconst N = 101; // #doors + 1\nvoid main() {\n bool[N] doors = false;\n for(auto door=1; doordisplay( REDUCE stringtab( INIT list TYPE stringtab\n FOR i = 1 WHILE i <= 10\n NEXT list = VALUE #( BASE list ( i * i ) ) ) ).\n", "safe": true }, { "filename": "100 doors_190.txt", "content": "import std.stdio;\nconst N = 101; // #doors + 1\nvoid main() {\n for( auto door=1,s=3; door open[i - 1]).writeln;\n}", "safe": true }, { "filename": "100 doors_193.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_194.txt", "content": "import std.stdio;\n\nvoid printAllDoors(bool[] doors)\n{\n // Prints the state of all the doors\n foreach(i, door; doors)\n {\n writeln(\"#: \", i + 1, (door)\u00a0? \" open\"\u00a0: \" closed\");\n }\n}\nvoid main()\n{\n bool[100] doors = false; //Create 100 closed doors\n for(int a = 0; a < 100; ++a) {\n writefln(\"Pass #%s; visiting every %s door.\", a + 1, a + 1); // Optional\n\t for(int i = a; i < 100; i += (a + 1)) {\n\t writefln(\"Visited door %s\", i + 1); //Optional\n\t doors[i] = !doors[i];\n\t }\n writeln(); // Optional\n }\n printAllDoors(doors); // Prints the state of each door\n}", "safe": true }, { "filename": "100 doors_195.txt", "content": "datatype Door = Closed | Open\n\nmethod InitializeDoors(n:int) returns (doors:array)\n // Precondition: n must be a valid array size.\n requires n >= 0\n // Postcondition: doors is an array, which is not an alias for any other\n // object, with a length of n, all of whose elements are Closed. The \"fresh\"\n // (non-alias) condition is needed to allow doors to be modified by the\n // remaining code.\n ensures doors\u00a0!= null && fresh(doors) && doors.Length == n\n ensures forall j\u00a0:: 0 <= j < doors.Length ==> doors[j] == Closed;\n{\n doors\u00a0:= new Door[n];\n var i\u00a0:= 0;\n // Invariant: i is always a valid index inside the loop, and all doors less\n // than i are Closed. These invariants are needed to ensure the second\n // postcondition.\n while i < doors.Length\n invariant i <= doors.Length\n invariant forall j\u00a0:: 0 <= j < i ==> doors[j] == Closed;\n {\n doors[i]\u00a0:= Closed;\n i\u00a0:= i + 1;\n }\n}\n\nmethod Main ()\n{\n var doors\u00a0:= InitializeDoors(100);\n\n var pass\u00a0:= 1;\n while pass <= doors.Length\n {\n var door\u00a0:= pass;\n while door < doors.Length\n {\n doors[door]\u00a0:= if doors[door] == Closed then Open else Closed;\n door\u00a0:= door + pass;\n }\n pass\u00a0:= pass + 1;\n }\n var i\u00a0:= 0;\n while i < doors.Length\n {\n print i, \" is \", if doors[i] == Closed then \"closed\\n\" else \"open\\n\";\n i\u00a0:= i + 1;\n }\n}", "safe": true }, { "filename": "100 doors_196.txt", "content": "main() {\n for (var k = 1, x = new List(101); k <= 100; k++) {\n for (int i = k; i <= 100; i += k)\n x[i] = !x[i];\n if (x[k]) print(\"$k open\");\n }\n}", "safe": true }, { "filename": "100 doors_197.txt", "content": "main() {\n for(int i=1,s=3;i<=100;i+=s,s+=2)\n print(\"door $i is open\");\n}", "safe": true }, { "filename": "100 doors_198.txt", "content": "import 'dart:io';\n\nfinal numDoors = 100;\nfinal List doorClosed = List(numDoors);\n\nString stateToString(String message) {\n var res = '';\n for (var i = 0; i < numDoors; i++) {\n res += (doorClosed[i]\u00a0? 'X'\u00a0: '\\u2610');\n }\n return res + \" \" + message;\n}\n\nmain() {\n for (var i = 0; i < numDoors; i++) {\n doorClosed[i] = true;\n }\n stdout.writeln(stateToString(\"after initialization\"));\n for (var step = 1; step <= numDoors; step++) {\n final start = step - 1;\n for (var i = start; i < numDoors; i += step) {\n doorClosed[i] = !doorClosed[i];\n }\n stdout.writeln(stateToString(\"after toggling with step = $step\"));\n }\n}", "safe": true }, { "filename": "100 doors_199.txt", "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX after initialization\n\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610 after toggling with step = 1\n\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X after toggling with step = 2\n\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX after toggling with step = 3\n\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610 after toggling with step = 4\n\u2610XX\u2610X\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610X\u2610\u2610\u2610X\u2610XX\u2610\u2610\u2610XX\u2610X\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XXX after toggling with step = 5\n\u2610XX\u2610XX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XXX\u2610X\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610XX\u2610XX\u2610X\u2610XX\u2610XX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XXX after toggling with step = 6\n\u2610XX\u2610XXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610XXXX\u2610\u2610\u2610\u2610XX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610XXXXX\u2610X\u2610X\u2610\u2610XX\u2610\u2610XX\u2610\u2610\u2610X\u2610\u2610XX\u2610XXX\u2610XXXX\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610XX after toggling with step = 7\n\u2610XX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XX\u2610X\u2610\u2610XX\u2610XX\u2610X\u2610X\u2610XXX\u2610\u2610XX\u2610X\u2610X\u2610\u2610XX\u2610\u2610XX\u2610XXXXX\u2610\u2610X\u2610XXXX\u2610\u2610XX after toggling with step = 8\n\u2610XX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610\u2610\u2610XXX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610XX\u2610X\u2610\u2610\u2610X\u2610XX\u2610X\u2610XXXXX\u2610\u2610XX\u2610\u2610\u2610X\u2610\u2610XX\u2610\u2610\u2610X\u2610XXXXX\u2610XX\u2610XXXX\u2610\u2610\u2610X after toggling with step = 9\n\u2610XX\u2610XXXX\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610\u2610XX\u2610XXXX\u2610\u2610\u2610X\u2610XX\u2610\u2610\u2610XXXXX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610XX\u2610X\u2610X\u2610XXXXX\u2610\u2610X\u2610XXXX\u2610\u2610\u2610\u2610 after toggling with step = 10\n\u2610XX\u2610XXXX\u2610XX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610XX\u2610\u2610\u2610XXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610XXXX\u2610\u2610\u2610X\u2610XXXX\u2610\u2610X\u2610 after toggling with step = 11\n\u2610XX\u2610XXXX\u2610XXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXXX\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610XXX\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610X\u2610 after toggling with step = 12\n\u2610XX\u2610XXXX\u2610XXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610XXXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610 after toggling with step = 13\n\u2610XX\u2610XXXX\u2610XXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610XXXX\u2610\u2610\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XX\u2610 after toggling with step = 14\n\u2610XX\u2610XXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610XXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610X\u2610X\u2610XXXX\u2610\u2610X\u2610\u2610XXX\u2610\u2610XX\u2610 after toggling with step = 15\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 16\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610X\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 17\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 18\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610 after toggling with step = 19\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 20\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 21\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 22\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610X\u2610XXX after toggling with step = 23\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX after toggling with step = 24\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 25\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 26\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 27\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 28\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 29\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 30\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XX\u2610 after toggling with step = 31\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XX\u2610 after toggling with step = 32\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 33\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 34\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 35\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 36\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 37\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 38\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 39\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 40\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 41\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 42\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 43\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 44\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 45\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 46\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610 after toggling with step = 47\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610 after toggling with step = 48\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610 after toggling with step = 49\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 50\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 51\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 52\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 53\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 54\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 55\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 56\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 57\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 58\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 59\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 60\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 61\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 62\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 63\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 64\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 65\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 66\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 67\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 68\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 69\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 70\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 71\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 72\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 73\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 74\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 75\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 76\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 77\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 78\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 79\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 80\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 81\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 82\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 83\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 84\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 85\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 86\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 87\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 88\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 89\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 90\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 91\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 92\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 93\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610X after toggling with step = 94\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610\u2610\u2610X after toggling with step = 95\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610\u2610\u2610X after toggling with step = 96\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610\u2610X after toggling with step = 97\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXX\u2610X after toggling with step = 98\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXXXX after toggling with step = 99\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXXX\u2610 after toggling with step = 100", "safe": true }, { "filename": "100 doors_2.txt", "content": "* 100 doors 13/08/2015\nHUNDOOR CSECT\n USING HUNDOOR,R12\n LR R12,R15\n LA R6,0\n LA R8,1 step 1\n LA R9,100\nLOOPI BXH R6,R8,ELOOPI do ipass=1 to 100 (R6)\n LR R7,R6\n SR R7,R6\n LR R10,R6 step ipass\n LA R11,100\nLOOPJ BXH R7,R10,ELOOPJ do idoor=ipass to 100 by ipass (R7)\n LA R5,DOORS-1\n AR R5,R7\n XI 0(R5),X'01' doors(idoor)=not(doors(idoor))\nNEXTJ B LOOPJ\nELOOPJ B LOOPI\nELOOPI LA R10,BUFFER R10 address of the buffer\n LA R5,DOORS R5 address of doors item\n LA R6,1 idoor=1 (R6)\n LA R9,100 loop counter\nLOOPN CLI 0(R5),X'01' if doors(idoor)=1\n BNE NEXTN\n XDECO R6,XDEC idoor to decimal\n MVC 0(4,R10),XDEC+8 move decimal to buffer\n LA R10,4(R10)\nNEXTN\t LA R6,1(R6) idoor=idoor+1\n LA R5,1(R5)\n BCT R9,LOOPN loop\nELOOPN XPRNT BUFFER,80\nRETURN XR R15,R15\n BR R14\nDOORS DC 100X'00'\nBUFFER DC CL80' '\nXDEC DS CL12\n YREGS\n END HUNDOOR", "safe": true }, { "filename": "100 doors_20.txt", "content": "HOW TO INITIALIZE:\n SHARE doors\n PUT {} IN doors\n FOR door IN {1..100}:\n PUT 0 IN doors[door]\n\nHOW TO TOGGLE door:\n SHARE doors\n PUT 1-doors[door] IN doors[door]\n\nHOW TO WALK step:\n SHARE doors\n PUT step IN door\n WHILE door <= 100:\n TOGGLE door\n PUT door+step IN door\n\nHOW TO DISPLAY OPEN DOORS:\n SHARE doors\n FOR door IN {1..100}:\n IF doors[door] = 1:\n WRITE \"Door\", door, \"is open\"/\n\nINITIALIZE\nFOR pass IN {1..100}: WALK pass\nDISPLAY OPEN DOORS", "safe": true }, { "filename": "100 doors_200.txt", "content": "## NB: This code uses the dc command \"r\" via register \"r\".\n## You may comment out the unwanted version.\n[SxSyLxLy]sr # this should work with every \"dc\"\n[r]sr # GNU dc can exchange top 2 stack values by \"r\"\n## Now use \"lrx\" instead of \"r\" ...\n\n0k # we work without decimal places\n[q]sq # useful e.g. as loop termination\n\n## (x)(y)>R == if (y)>(x) eval R\n## isle x y --> (x <= y)\n[\n [1q]S. [\u00a0!<. 0 ]x s.L.\n]sl\n## l: isle\n\n[\n 100 llx\n]sL\n## L: isle100\n\n## for initcode condcode incrcode body\n## [1] [2] [3] [4]\n[\n [q]S. 4:. 3:. 2:. 1:. 1;.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x Os.L.o\n]sf\n## f: for\n##----------------------------------------------------------------------------\n\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## door[i] = 0;\n## }\n#[init ...]P []ps-\n[1si] [li lLx] [li1+si] [\n li 0:d\n]lfx\n\n## for( s=1\u00a0; s<=100\u00a0; ++s ) {\n## for( i=s\u00a0; i<=100\u00a0; i+=s ) {\n## door[i] = 1 - door[i]\n## }\n## }\n[1ss] [ls lLx] [ls1+ss] [\n #[step ]P lsn [ ...]ps-\n [lssi] [li lLx] [lils+si] [\n 1 li;d - li:d\n ]lfx\n]lfx\n\n## long output:\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## print \"door #\", i, \" is \", (door[i]\u00a0? \"open\"\u00a0: \"closed\")), NL\n## }\n[\n [1si] [li lLx] [li1+si] [\n [door #]P\n li n\n [ is ]P\n [closed]\n [open]\n li;d 0=r lrx s- n\n [.]ps-\n ]lfx\n]\n\n## terse output:\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## if( door[i] ) {\n## print i\n## }\n## print NL\n## }\n[\n [1si] [li lLx] [li1+si] [\n [] [ [ ]n lin ]\n li;d 0=r lrx s- x\n ]lfx\n []ps-\n]\n\nlrx # comment out for the long output version\ns- x\n#[stack rest...]P []ps- f", "safe": true }, { "filename": "100 doors_201.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_202.txt", "content": "$! doors.com\n$! Excecute by running @doors at prompt.\n$ square = 1\n$ incr = 3\n$ count2 = 0\n$ d = 1\n$ LOOP2:\n$ count2 = count2 + 1\n$ IF (d .NE. square)\n$ THEN WRITE SYS$OUTPUT \"door ''d' is closed\"\n$ ELSE WRITE SYS$OUTPUT \"door ''d' is open\"\n$ square = incr + square\n$ incr = incr + 2\n$ ENDIF\n$ d = d + 1\n$ IF (count2 .LT. 100) THEN GOTO LOOP2", "safe": true }, { "filename": "100 doors_203.txt", "content": "proc nonrec main() void:\n byte DOORS = 100;\n [DOORS+1] bool door_open;\n unsigned DOORS i, j;\n\n /* make sure all doors are closed */\n for i from 1 upto DOORS do door_open[i]\u00a0:= false od;\n\n /* pass through the doors */\n for i from 1 upto DOORS do\n for j from i by i upto DOORS do\n door_open[j]\u00a0:= not door_open[j]\n od\n od;\n\n /* show the open doors */\n for i from 1 upto DOORS do\n if door_open[i] then\n writeln(\"Door \", i, \" is open.\")\n fi\n od\ncorp", "safe": true }, { "filename": "100 doors_204.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_205.txt", "content": "100[$][0^:1-]# {initialize doors}\n%\n[s;[$101<][$$;~\\:s;+]#%]d: {function d, switch door state function}\n1s:[s;101<][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}\n1[$101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]# {loop through doors, print door number and state}", "safe": true }, { "filename": "100 doors_206.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n11 closed\n12 closed\n...\n94 closed\n95 closed\n96 closed\n97 closed\n98 closed\n99 closed\n100 open", "safe": true }, { "filename": "100 doors_207.txt", "content": "var doors\u00a0: array [1..100] of Boolean;\nvar i, j\u00a0: Integer;\n\nfor i\u00a0:= 1 to 100 do\n for j\u00a0:= i to 100 do\n if (j mod i) = 0 then\n doors[j]\u00a0:= not doors[j];F\n\nfor i\u00a0:= 1 to 100 do\n if doors[i] then\n PrintLn('Door '+IntToStr(i)+' is open');", "safe": true }, { "filename": "100 doors_208.txt", "content": "var doors = Array.Empty(100, false)\n \nfor p in 0..99 {\n for d in 0..99 {\n if (d + 1)\u00a0% (p + 1) == 0 {\n doors[d] = !doors[d];\n }\n }\n}\n \nfor d in doors.Indices() when doors[d] {\n print(\"Door \\(d+1): Open\")\n}", "safe": true }, { "filename": "100 doors_209.txt", "content": "Door 1: Open\nDoor 4: Open\nDoor 9: Open\nDoor 16: Open\nDoor 25: Open\nDoor 36: Open\nDoor 49: Open\nDoor 64: Open\nDoor 81: Open\nDoor 100: Open", "safe": true }, { "filename": "100 doors_21.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100 doors_210.txt", "content": "define function doors ()\n let n = 100;\n let doors = make(, size: n, fill: #f);\n for (x from 0 below n)\n for (y from x below n by x + 1)\n doors[y]\u00a0:= ~doors[y]\n end\n end;\n format-out(\"open: \");\n for (x from 0 below n) \n if (doors[x]) \n format-out(\"%d \", x + 1)\n end\n end\nend function;", "safe": true }, { "filename": "100 doors_211.txt", "content": "local :open-doors [ rep 101 false ]\n\nfor i range 1 100:\n\tlocal :j i\n\twhile <= j 100:\n\t\tset-to open-doors j not open-doors! j\n\t\tset :j + j i\n\n!print\\ \"Open doors: \"\nfor i range 1 100:\n\tif open-doors! i:\n\t\t!print\\( to-str i \" \" )", "safe": true }, { "filename": "100 doors_212.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100 ", "safe": true }, { "filename": "100 doors_213.txt", "content": "#!/usr/bin/env rune\n\nvar toggles\u00a0:= []\nvar gets\u00a0:= []\n\n# Set up GUI (and data model)\ndef frame\u00a0:= (\"100 doors\")\nframe.getContentPane().setLayout((10, 10))\nfor i in 1..100 {\n def component\u00a0:= (E.toString(i))\n toggles with= fn { component.setSelected(!component.isSelected()) }\n gets with= fn { component.isSelected() }\n frame.getContentPane().add(component)\n}\n\n# Set up termination condition\ndef done\nframe.addWindowListener(def _ {\n to windowClosing(event) {\n bind done\u00a0:= true\n }\n match _ {}\n})\n\n# Open and close doors\ndef loop(step, i) {\n toggles[i] <- ()\n def next\u00a0:= i + step\n timer.whenPast(timer.now() + 10, fn {\n if (next >= 100) {\n if (step >= 100) {\n # Done.\n } else {\n loop <- (step + 1, step)\n }\n } else {\n loop <- (step, i + step)\n } \n })\n}\nloop(1, 0)\n\nframe.pack()\nframe.show()\ninterp.waitAtTop(done)", "safe": true }, { "filename": "100 doors_214.txt", "content": "len d[] 100\nfor p = 1 to 100\n i = p\n while i <= 100\n d[i] = 1 - d[i]\n i += p\n .\n.\nfor i = 1 to 100\n if d[i] = 1\n print i\n .\n.", "safe": true }, { "filename": "100 doors_215.txt", "content": "; initial state = closed = #f\n(define doors (make-vector 101 #f))\n; run pass 100 to 1\n(for* \n ((pass (in-range 100 0 -1)) \n (door (in-range 0 101 pass))) \n (when (and \n (vector-set! doors door (not (vector-ref doors door))) \n (= pass 1)) \n (writeln door \"is open\"))) \n\n1 \"is open\" \n4 \"is open\" \n9 \"is open\" \n16 \"is open\" \n25 \"is open\" \n36 \"is open\" \n49 \"is open\" \n64 \"is open\" \n81 \"is open\" \n100 \"is open\"", "safe": true }, { "filename": "100 doors_216.txt", "content": "Doors\u00a0:= RECORD\n UNSIGNED1 DoorNumber;\n STRING6 State;\nEND;\n\nAllDoors\u00a0:= DATASET([{0,0}],Doors);\n\nDoors OpenThem(AllDoors L,INTEGER Cnt)\u00a0:= TRANSFORM\n SELF.DoorNumber\u00a0:= Cnt;\n SELF.State \u00a0:= IF((CNT * 10)\u00a0% (SQRT(CNT)*10)<>0,'Closed','Opened');\nEND;\n\nOpenDoors\u00a0:= NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));\n \nOpenDoors;", "safe": true }, { "filename": "100 doors_217.txt", "content": "Doors\u00a0:= RECORD\n UNSIGNED1 DoorNumber;\n STRING6 State;\nEND;\n\nAllDoors\u00a0:= DATASET([{0,'0'}],Doors);\n\n//first build the 100 doors\n\nDoors OpenThem(AllDoors L,INTEGER Cnt)\u00a0:= TRANSFORM\n SELF.DoorNumber\u00a0:= Cnt;\n SELF.State \u00a0:= 'Closed';\nEND;\n\nClosedDoors\u00a0:= NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));\n\n//now iterate through them and use door logic\n\nloopBody(DATASET(Doors) ds, UNSIGNED4 c)\u00a0:=\n PROJECT(ds, //ds=original input\n TRANSFORM(Doors,\n \tSELF.State\u00a0:= CASE((COUNTER\u00a0% c) * 100,\n\t\t 0 => IF(LEFT.STATE = 'Opened','Closed','Opened')\n\t\t\t\t\t ,LEFT.STATE);\n\t\t\tSELF.DoorNumber\u00a0:= COUNTER; //PROJECT COUNTER\n ));\n \ng1\u00a0:= LOOP(ClosedDoors,100,loopBody(ROWS(LEFT),COUNTER));\n \nOUTPUT(g1);", "safe": true }, { "filename": "100 doors_218.txt", "content": "DoorSet\u00a0:= DATASET(100,TRANSFORM({UNSIGNED1 DoorState},SELF.DoorState\u00a0:= 1));\nSetDoors\u00a0:= SET(DoorSet,DoorState);\n\nDoors\u00a0:= RECORD\n UNSIGNED1 Pass;\n SET OF UNSIGNED1 DoorSet;\nEND;\n\nStartDoors\u00a0:= DATASET(100,TRANSFORM(Doors,SELF.Pass\u00a0:= COUNTER,SELF.DoorSet\u00a0:= SetDoors));\n\nDoors XF(Doors L, Doors R)\u00a0:= TRANSFORM\n ds\u00a0:= DATASET(L.DoorSet,{UNSIGNED1 DoorState});\n NextDoorSet\u00a0:= PROJECT(ds, \n TRANSFORM({UNSIGNED1 DoorState},\n \t SELF.DoorState\u00a0:= CASE((COUNTER\u00a0% R.Pass) * 100,\n 0 => IF(LEFT.DoorState = 1,0,1),\n LEFT.DoorState)));\n SELF.DoorSet\u00a0:= IF(L.Pass=0,R.DoorSet,SET(NextDoorSet,DoorState));\t\t\t\t\t\t\t\t\t\n SELF.Pass\u00a0:= R.Pass\t\t\t\t\t\t\t\t\t\t\nEND;\t\t\t\t\t\t\t\t\t\t\n \nRes\u00a0:= DATASET(ITERATE(StartDoors,XF(LEFT,RIGHT))[100].DoorSet,{UNSIGNED1 DoorState});\nPROJECT(Res,TRANSFORM({STRING20 txt},SELF.Txt\u00a0:= 'Door ' + COUNTER + ' is ' + IF(LEFT.DoorState=1,'Open','Closed')));", "safe": true }, { "filename": "100 doors_219.txt", "content": "module OneHundredDoors {\n void run() {\n Boolean[] doors = new Boolean[100];\n for (Int pass\u00a0: 0 ..< 100) {\n for (Int door = pass; door < 100; door += 1+pass) {\n doors[door] = !doors[door];\n }\n }\n\n @Inject Console console;\n console.print($|open doors: {doors.mapIndexed((d, i) -> d\u00a0? i+1\u00a0: 0)\n | .filter(i -> i > 0)}\n );\n }\n}", "safe": true }, { "filename": "100 doors_22.txt", "content": "(defun rep (n x)\n (if (zp n)\n nil\n (cons x\n (rep (- n 1) x))))\n\n(defun toggle-every-r (n i bs)\n (if (endp bs)\n nil\n (cons (if (zp i)\n (not (first bs))\n (first bs))\n (toggle-every-r n (mod (1- i) n) (rest bs)))))\n\n(defun toggle-every (n bs)\n (toggle-every-r n (1- n) bs))\n\n(defun 100-doors (i doors)\n (if (zp i)\n doors\n (100-doors (1- i) (toggle-every i doors))))\n", "safe": true }, { "filename": "100 doors_220.txt", "content": "open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100 doors_221.txt", "content": "[Hundred doors problem from Rosetta Code website]\n[EDSAC program, Initial Orders 2]\n\n[Library subroutine M3. Prints header and is then overwritten.\nHere, the last character sets the teleprinter to figures.]\n PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF\n @&*THE!OPEN!DOORS!ARE@&#\n ..PZ [blank tape, needed to mark end of header text]\n\n[Library subroutine P6. Prints strictly positive integer.\n32 locations; working locations 1, 4, 5]\n T56K [define load address for subroutine]\n GKA3FT25@H29@VFT4DA3@TFH30@S6@T1F\n V4DU4DAFG26@TFTFO5FA4DF4FS4F\n L4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F\n\n T88K [define load address for main program]\n GK [set @ (theta) for relative addresses]\n\n[The 100 doors are at locations 200..299.\nDoors are numbered 0..99 internally, and 1..100 for output.\nThe base address and the number of doors can be varied.\nThe value of a door is 0 if open, negative if closed.]\n\n [Constants. Program also uses order 'P 1 F'\n which is permanently at absolute address 2.]\n [0] P200F [address of door #0]\n [1] P100F [number of doors, as an address]\n [2] UF [makes S order from T, since 'S' = 'T' + 'U']\n [3] MF [makes A order from T, since 'A' = 'T' + 'M']\n [4] V2047D [all 1's for \"closed\" (any negative value will do)]\n [5] &F [line feed]\n [6] @F [carriage return]\n [7] K4096F [teleprinter null[\n\n [Variables]\n [8] PF [pass number; step when toggling doors]\n [9] PF [door number, as address, 0-based]\n [10] PF [order referring to door 0]\n\n [Enter with acc = 0]\n [Part 1\u00a0: close all the doors]\n [11] T8@ [pass\u00a0:= 0 (used in part 2)]\n T9@ [door number\u00a0:= 0]\n A16@ [load 'T F' order]\n A@ [add base address]\n T10@ [store T order for door #0]\n [16] TF [clear acc; also serves as constant]\n A9@ [load door number]\n A10@ [make T order]\n T21@ [plant in code]\n A4@ [load value for \"closed\"]\n [21] TF [store in current door]\n A9@ [load door number]\n A2F [add 1]\n U9@ [update door number]\n S1@ [done all doors yet?]\n G16@ [if not, loop back]\n\n [Part 2\u00a0: 100 passes, toggling the doors]\n [27] TF [clear acc]\n A8@ [load pass number]\n A2F [add 1]\n T8@ [save updated pass number]\n S2F [make -1]\n U9@ [door number\u00a0:= -1]\n A8@ [add pass number to get first door toggled on this pass]\n S1@ [gone beyond end?]\n E50@ [if so, move on to part 3]\n [36] A1@ [restore acc after test]\n U9@ [store current door number]\n A10@ [make T order to load status]\n U44@ [plant T order for first door in pass]\n A2@ [convert to S order]\n T43@ [plant S order]\n A4@ [load value for \"closed\"]\n [43] SF [subtract status; toggles status]\n [44] TF [update status]\n A9@ [load door number just toggled]\n A8@ [add pass number to get next door in pass]\n S1@ [gone beyond end?]\n G36@ [no, loop to do next door]\n E27@ [yes, loop to do next pass]\n\n [Part 3\u00a0: Print list of open doors.\n Header has set teleprinter to figures.]\n [50] TF [clear acc]\n T9@ [door nr\u00a0:= 0]\n A10@ [T order for door 0]\n A3@ [convert to A order]\n T10@\n [55] TF\n A9@ [load door number]\n A10@ [make A order to load value]\n T59@ [plant in next order]\n [59] AF [acc\u00a0:= 0 if open, < 0 if closed]\n G69@ [skip if closed]\n A9@ [door number as address]\n A2F [add 1 for 1-based output]\n RD [shift 1 right, address --> integer]\n TF [store integer at 0 for printing]\n [65] A65@ [for return from subroutine]\n G56F [call subroutine to print door number]\n O6@ [followed by CRLF]\n O5@\n [69] TF [clear acc]\n A9@ [load door number]\n A2F [add 1]\n U9@ [update door number]\n S1@ [done all doors yet?]\n G55@ [if not, loop back]\n [75] O7@ [output null to flush teleprinter buffer]\n ZF [stop]\n E11Z [define relative start address]\n PF", "safe": true }, { "filename": "100 doors_222.txt", "content": "THE OPEN DOORS ARE\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n 100\n", "safe": true }, { "filename": "100 doors_223.txt", "content": "#import \n\nint main()\n square\u00a0:= 1, increment = 3\n\n for int door in 1 .. 100\n printf(\"door #%d\", door)\n\n if door == square\n puts(\" is open.\")\n square += increment\n increment += 2\n else\n puts(\" is closed.\")\n\n return 0", "safe": true }, { "filename": "100 doors_224.txt", "content": "import \"prelude.eg\"\n\nusing System\nusing List\n\ndata open, closed\n\ndef toggle =\n [ open N -> closed N | closed N -> open N ]\n\ndef doors =\n [ N -> map [ N -> closed N ] (fromto 1 N) ]\n\ndef toggleK =\n [ K nil -> nil\n | K (cons (D N) DD) -> \n let DOOR = if (N%K) == 0 then toggle (D N) else D N in\n cons DOOR (toggleK K DD) ]\n\ndef toggleEvery =\n [ nil DOORS -> DOORS\n | (cons K KK) DOORS -> toggleEvery KK (toggleK K DOORS) ]\n\ndef run =\n [ N -> toggleEvery (fromto 1 N) (doors N) ]\n\ndef main = run 100", "safe": true }, { "filename": "100 doors_225.txt", "content": "program OneHundredDoors\n\n function main()\n\n doors boolean[] = new boolean[100];\n n int = 100;\n\n for (i int from 1 to n)\n for (j int from i to n by i)\n doors[j] = !doors[j];\n end\n end\n \n for (i int from 1 to n)\n if (doors[i])\n SysLib.writeStdout( \"Door \" + i + \" is open\" );\n end\n end\n \n end\n\nend", "safe": true }, { "filename": "100 doors_226.txt", "content": "note\n\tdescription: \"100 Doors problem\"\n\tdate: \"08-JUL-2015\"\n\trevision: \"1.1\"\n\nclass\n\tAPPLICATION\n\ncreate\n\tmake\n\nfeature {NONE} -- Initialization\n\n\tmake\n\t\t\t-- Main application routine.\n\t\tdo\n\t\t\tinitialize_closed_doors\n\t\t\ttoggle_doors\n\t\t\toutput_door_states\n\t\tend\n\nfeature -- Access\n\n\tdoors: ARRAYED_LIST [DOOR]\n\t\t\t-- A set of doors (self-initialized to capacity of `max_door_count').\n\t\tattribute\n\t\t\tcreate Result.make (max_door_count)\n\t\tend\n\nfeature -- Basic Operations\n\n\tinitialize_closed_doors\n\t\t\t-- Initialize all `doors'.\n\t\tdo\n\t\t\tacross min_door_count |..| max_door_count as ic_address_list loop\n\t\t\t\tdoors.extend (create {DOOR}.make_closed (ic_address_list.item))\n\t\t\tend\n\t\tensure\n\t\t\thas_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end\n\t\tend\n\n\ttoggle_doors\n\t\t\t-- Toggle all `doors'.\n\t\tdo\n\t\t\tacross min_door_count |..| max_door_count as ic_addresses_list loop\n\t\t\t\tacross doors as ic_doors_list loop\n\t\t\t\t\tif is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then\n\t\t\t\t\t\tic_doors_list.item.toggle_door\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\toutput_door_states\n\t\t\t-- Output the state of all `doors'.\n\t\tdo\n\t\t\tdoors.do_all (agent door_state_out)\n\t\tend\n\nfeature -- Status Report\n\n\tis_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN\n\t\t\t-- Is the door at `a_door_address' needing to be toggled, when compared to `a_index_address'?\n\t\tdo\n\t\t\tResult\u00a0:= a_door_address \\\\ a_index_address = 0\n\t\tensure\n\t\t\tonly_modulus_zero: Result = (a_door_address \\\\ a_index_address = 0)\n\t\tend\n\nfeature -- Outputs\n\n\tdoor_state_out (a_door: DOOR)\n\t\t\t-- Output the state of `a_door'.\n\t\tdo\n\t\t\tprint (\"Door \" + a_door.address.out + \" is \")\n\t\t\tif a_door.is_open then\n\t\t\t\tprint (\"open.\")\n\t\t\telse\n\t\t\t\tprint (\"closed.\")\n\t\t\tend\n\t\t\tio.new_line\n\t\tend\n\nfeature {DOOR} -- Constants\n\n\tmin_door_count: INTEGER = 1\n\t\t\t-- Minimum number of doors.\n\n\tmax_door_count: INTEGER = 100\n\t\t\t-- Maximum number of doors.\n\nend", "safe": true }, { "filename": "100 doors_227.txt", "content": "note\n\tdescription: \"A door with an address and an open or closed state.\"\n\tdate: \"08-JUL-2015\"\n\trevision: \"1.1\"\n\nclass\n\tDOOR\n\ncreate\n\tmake_closed,\n\tmake\n\nfeature {NONE} -- initialization\n\n\tmake_closed (a_address: INTEGER)\n\t\t\t-- Initialize Current {DOOR} at `a_address' and state of `Is_closed'.\n\t\trequire\n\t\t\tpositive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count\n\t\tdo\n\t\t\tmake (a_address, Is_closed)\n\t\tensure\n\t\t\tclosed: is_open = Is_closed\n\t\tend\n\n\tmake (a_address: INTEGER; a_status: BOOLEAN)\n\t\t\t-- Initialize Current {DOOR} with `a_address' and `a_status', denoting position and `is_open' or `Is_closed'.\n\t\trequire\n\t\t\tpositive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count\n\t\tdo\n\t\t\taddress\u00a0:= a_address\n\t\t\tis_open\u00a0:= a_status\n\t\tensure\n\t\t\taddress_set: address = a_address\n\t\t\tstatus_set: is_open = a_status\n\t\tend\n\nfeature -- access\n\n\taddress: INTEGER\n\t\t\t-- `address' of Current {DOOR}.\n\n\tis_open: BOOLEAN assign set_open\n\t\t\t-- `is_open' (or not) status of Current {DOOR}.\n\nfeature -- Setters\n\n\tset_open (a_status: BOOLEAN)\n\t\t\t-- Set `status' with `a_status'\n\t\tdo\n\t\t\tis_open\u00a0:= a_status\n\t\tensure\n\t\t\topen_updated: is_open = a_status\n\t\tend\n\nfeature {APPLICATION} -- Basic Operations\n\n\ttoggle_door\n\t\t\t-- Toggle Current {DOOR} from `is_open' to not `is_open'.\n\t\tdo\n\t\t\tis_open\u00a0:= not is_open\n\t\tensure\n\t\t\ttoggled: is_open /= old is_open\n\t\tend\n\nfeature {NONE} -- Implementation: Constants\n\n\tIs_closed: BOOLEAN = False\n\t\t\t-- State of being not `is_open'.\n\n\tMin_door_count: INTEGER = 1\n\t\t\t-- Minimum door count.\n\ninvariant\n\tone_or_more: address >= 1\n\tconsistency: is_open implies not Is_closed\n\nend", "safe": true }, { "filename": "100 doors_228.txt", "content": "open generic\n\ntype Door = Open | Closed\n deriving Show\n\ngate [] _ = []\ngate (x::xs) (y::ys) \n | x == y = Open\u00a0:: gate xs ys\n | else = Closed\u00a0:: gate xs ys\n\nrun n = gate [1..n] [& k*k \\\\ k <- [1..]]", "safe": true }, { "filename": "100 doors_229.txt", "content": "open list\nrun n = takeWhile (false);\n for(int i\u00a0:= 0; i < 100; i++)\n {\n for(int j\u00a0:= i; j < 100; j\u00a0:= j + i + 1)\n {\n Doors[j]\u00a0:= Doors[j].Inverted\n }\n };\n \n for(int i\u00a0:= 0; i < 100; i++)\n {\n console.printLine(\"Door #\",i + 1,\"\u00a0:\",Doors[i].iif(\"Open\",\"Closed\"))\n };\n \n console.readChar()\n}", "safe": true }, { "filename": "100 doors_231.txt", "content": "defmodule HundredDoors do\n def doors(n \\\\ 100) do\n List.duplicate(false, n)\n end\n \n def toggle(doors, n) do\n List.update_at(doors, n, &(!&1))\n end\n \n def toggle_every(doors, n) do\n Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end )\n end\nend\n\n# unoptimized\nfinal_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end)\n\nopen_doors = Enum.with_index(final_state)\n |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)\n\nIO.puts \"All doors are closed except these: #{inspect open_doors}\"\n\n\n# optimized \nfinal_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end)\n\nopen_doors = Enum.with_index(final_state)\n |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)\n\nIO.puts \"All doors are closed except these: #{inspect open_doors}\"", "safe": true }, { "filename": "100 doors_232.txt", "content": "All doors are closed except these: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_233.txt", "content": "-- Unoptimized\nimport List exposing (indexedMap, foldl, repeat, range)\nimport Html exposing (text)\nimport Debug exposing (toString)\n\ntype Door = Open | Closed\n\ntoggle d = if d == Open then Closed else Open\n\ntoggleEvery\u00a0: Int -> List Door -> List Door\ntoggleEvery k doors = indexedMap \n (\\i door -> if modBy k (i+1) == 0 then toggle door else door)\n doors\n\nn = 100\n\nmain = \n text (toString (foldl toggleEvery (repeat n Closed) (range 1 n)))", "safe": true }, { "filename": "100 doors_234.txt", "content": "(defun create-doors ()\n \"Returns a list of closed doors\n\nEach door only has two status: open or closed.\nIf a door is closed it has the value 0, if it's open it has the value 1.\"\n (let ((return_value '(0))\n \u00a0;; There is already a door in the return_value, so k starts at 1\n \u00a0;; otherwise we would need to compare k against 99 and not 100 in\n \u00a0;; the while loop\n (k 1))\n (while (< k 100)\n (setq return_value (cons 0 return_value))\n (setq k (+ 1 k)))\n return_value))\n\n(defun toggle-single-door (doors)\n \"Toggle the stat of the door at the `car' position of the DOORS list\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\n\nReturns a list where the `car' of the list has it's value toggled (if open\nit becomes closed, if closed it becomes open).\"\n (if (= (car doors) 1)\n (cons 0 (cdr doors))\n (cons 1 (cdr doors))))\n\n(defun toggle-doors (doors step original-step)\n \"Step through all elements of the doors' list and toggle a door when step is 1\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\nSTEP is the number of doors we still need to transverse before we arrive\nat a door that has to be toggled.\nORIGINAL-STEP is the value of the argument step when this function is\ncalled for the first time.\n\nReturns a list of doors\"\n (cond ((null doors)\n '())\n ((= step 1)\n (cons (car (toggle-single-door doors))\n (toggle-doors (cdr doors) original-step original-step)))\n (t\n (cons (car doors)\n (toggle-doors (cdr doors) (- step 1) original-step)))))\n\n(defun main-program ()\n \"The main loop for the program\"\n (let ((doors_list (create-doors))\n (k 1)\n \u00a0;; We need to define max-specpdl-size and max-specpdl-size to big\n \u00a0;; numbers otherwise the loop reaches the max recursion depth and\n \u00a0;; throws an error.\n \u00a0;; If you want more information about these variables, press Ctrl\n \u00a0;; and h at the same time and then press v and then type the name\n \u00a0;; of the variable that you want to read the documentation.\n (max-specpdl-size 5000)\n (max-lisp-eval-depth 2000))\n (while (< k 101)\n (setq doors_list (toggle-doors doors_list k k))\n (setq k (+ 1 k)))\n doors_list))\n\n(defun print-doors (doors)\n \"This function prints the values of the doors into the current buffer.\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\n\"\n \u00a0;; As in the main-program function, we need to set the variable\n \u00a0;; max-lisp-eval-depth to a big number so it doesn't reach max recursion\n \u00a0;; depth.\n (let ((max-lisp-eval-depth 5000))\n (unless (null doors)\n (insert (int-to-string (car doors)))\n (print-doors (cdr doors)))))\n\n;; Returns a list with the final solution\n(main-program)\n\n;; Print the final solution on the buffer\n(print-doors (main-program))", "safe": true }, { "filename": "100 doors_235.txt", "content": "type Door:State\nenum do int CLOSED, OPEN end\ntype Door\nmodel\n int id\n Door:State state\n new by int \u2190id, Door:State \u2190state do end\n fun toggle \u2190 <|me.state \u2190 when(me.state \u00e6 Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED)\n fun asText \u2190 <|\"Door #\" + me.id + \" is \" + when(me.state \u00e6 Door:State.CLOSED, \"closed\", \"open\")\nend\ntype Main\n^|There are 100 doors in a row that are all initially closed.|^\nList doors \u2190 Door[].with(100, open;\ntoggle(open) -> closed.\n\ngo() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1).\ngo([], L, N, _I) when N =:= 101 -> lists:reverse(L);\ngo([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1);\ngo([H|T], L, N, I) ->\n H2 = case I rem N of\n 0 -> toggle(H);\n _ -> H\n end,\n go(T, [H2|L], N, I + 1).", "safe": true }, { "filename": "100 doors_238.txt", "content": "array_go() -> go(array:new([101, fixed, {default, closed}]), 1, 1).\n\ngo(Array, Big, Inc) when Big > 100, Inc =< 100 ->\n go(Array, Inc + 1, Inc + 1);\ngo(Array, Index, Inc) when Inc < 101 ->\n go(array:set(Index, toggle(Array, Index), Array), Index + Inc, Inc);\ngo(Array, _, _) -> array:sparse_to_orddict(Array).\n\ntoggle(Array, Index) -> toggle(array:get(Index, Array)).", "safe": true }, { "filename": "100 doors_239.txt", "content": " task_100_doors:array_go().\n[{1,open},\n {4,open},\n {9,open},\n {16,open},\n {25,open},\n {36,open},\n {49,open},\n {64,open},\n {81,open},\n {100,open}]\n", "safe": true }, { "filename": "100 doors_24.txt", "content": "Following doors are open:\n1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_240.txt", "content": "doors() ->\n F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end,\n Out = fun(X, true) -> io:format(\"Door ~p: open~n\",[X]);\n (X, false)-> io:format(\"Door ~p: close~n\",[X]) end,\n [Out(X,F(X)) || X <- lists:seq(1,100)].", "safe": true }, { "filename": "100 doors_241.txt", "content": "! \"100 Doors\" program for ERRE LANGUAGE\n! Author: Claudio Larini\n! Date: 21-Nov-2014\n!\n! PC Unoptimized version translated from a QB version\n\nPROGRAM 100DOORS\n\n!$INTEGER\n\nCONST N=100\n\nDIM DOOR[N]\n\nBEGIN\n\nFOR STRIDE=1 TO N DO\n FOR INDEX=STRIDE TO N STEP STRIDE DO\n DOOR[INDEX]=NOT(DOOR[INDEX])\n END FOR\nEND FOR\n\nPRINT(\"Open doors:\";)\nFOR INDEX=1 TO N DO\n IF DOOR[INDEX] THEN PRINT(INDEX;) END IF\nEND FOR\nPRINT\n\nEND PROGRAM", "safe": true }, { "filename": "100 doors_242.txt", "content": "begin new doors; new i; label doorLoop; label outDoors;\n doors <- list 100;\n i <- 0;\ndoorLoop: if [ i <- i + 1 ] <= length doors then begin\n new j; label flipLoop;\n j <- 0;\nflipLoop: if [ j <- J + i ] <= length doors then begin\n doors[ j ] <- isu doors[ j ] or not doors[ j ];\n goto flipLoop\n end else 0;\n goto doorLoop\n end else 0;\n i <- 0;\noutDoors: if [ i <- i + 1 ] <= length doors then begin\n if doors[ i ] then out i else 0;\n goto outDoors\n end else 0\nend $\n", "safe": true }, { "filename": "100 doors_243.txt", "content": ">function Doors () ...\n$ doors:=zeros(1,100);\n$ for i=1 to 100\n$ for j=i to 100 step i\n$ doors[j]=!doors[j];\n$ end;\n$ end;\n$ return doors\n$endfunction\n>nonzeros(Doors())\n [ 1 4 9 16 25 36 49 64 81 100 ]", "safe": true }, { "filename": "100 doors_244.txt", "content": "-- doors.ex\ninclude std/console.e\nsequence doors\ndoors = repeat( 0, 100 ) -- 1 to 100, initialised to false \n\nfor pass = 1 to 100 do\n\tfor door = pass to 100 by pass do\n\t\t--printf( 1, \"%d\", doors[door] )\n\t\t--printf( 1, \"%d\", not doors[door] )\n\t\tdoors[door] = not doors[door]\n\tend for\nend for\n\nsequence oc\n\nfor i = 1 to 100 do\n\tif doors[i] then\n\t\toc = \"open\"\n\telse\n\t\toc = \"closed\"\n\tend if\n \tprintf( 1, \"door %d is %s\\n\", { i, oc } )\nend for", "safe": true }, { "filename": "100 doors_245.txt", "content": "=IF($A2/C$1=INT($A2/C$1),IF(B2=0,1,IF(B2=1,0)),B2)", "safe": true }, { "filename": "100 doors_246.txt", "content": "=IF($A3/C$1=INT($A3/C$1),IF(B3=0,1,IF(B3=1,0)),B3)", "safe": true }, { "filename": "100 doors_247.txt", "content": "=IF($A2/D$1=INT($A2/D$1),IF(C2=0,1,IF(C2=1,0)),C2)", "safe": true }, { "filename": "100 doors_248.txt", "content": "type doorState=Open|Closed\nlet flip=function Open->Closed |_->Open\nlet Doors=Array.create 100 Closed\nfor n in 1..100 do {n-1..n..99}|>Seq.iter(fun n->Doors[n]<-flip Doors[n])\nDoors|>Array.iteri(fun n g->if g=Open then printf \"%d \" (n+1)); printfn \"\"", "safe": true }, { "filename": "100 doors_249.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_25.txt", "content": "package { \n import flash.display.Sprite; \n\n public class Doors extends Sprite {\n public function Doors() {\n\n // Initialize the array\n var doors:Array = new Array(100);\n for (var i:Number = 0; i < 100; i++) {\n doors[i] = false;\n\n // Do the work\n for (var pass:Number = 0; pass < 100; pass++) {\n for (var j:Number = pass; j < 100; j += (pass+1)) {\n doors[j] = !doors[j];\n }\n }\n trace(doors);\n }\n }\n}\n", "safe": true }, { "filename": "100 doors_250.txt", "content": "open System\nlet answer2 =\n let PerfectSquare n =\n let sqrt = int(Math.Sqrt(float n))\n n = sqrt * sqrt\n [| for i in 1..100 do yield PerfectSquare i |]", "safe": true }, { "filename": "100 doors_251.txt", "content": "[1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1)\u00a0% pass)=0 then not x else x) doors) (List.init 100 (fun _->false))", "safe": true }, { "filename": "100 doors_252.txt", "content": "USING: bit-arrays formatting fry kernel math math.ranges\nsequences\u00a0;\nIN: rosetta.doors\n\nCONSTANT: number-of-doors 100\n\n: multiples ( n -- range )\n 0 number-of-doors rot \u00a0;\n\n: toggle-multiples ( n doors -- )\n [ multiples ] dip '[ _ [ not ] change-nth ] each\u00a0;\n\n: toggle-all-multiples ( doors -- )\n [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each\u00a0;\n\n: print-doors ( doors -- )\n [\n swap \"open\" \"closed\"\u00a0? \"Door %d is %s\\n\" printf\n ] each-index\u00a0;\n\n: main ( -- )\n number-of-doors 1 + \n [ toggle-all-multiples ] [ print-doors ] bi\u00a0;\n\nmain", "safe": true }, { "filename": "100 doors_253.txt", "content": "USING:\n formatting\n math math.primes.factors math.ranges\n sequences\u00a0;\nIN: rosetta-doors2\n\n: main ( -- )\n 100 [1,b] [ divisors length odd? ] filter \"Open\u00a0%[%d,\u00a0%]\\n\" printf\u00a0;", "safe": true }, { "filename": "100 doors_254.txt", "content": "doors = arrayBuffer( 101, false )\n\nfor pass in [ 0\u00a0: doors.len() ]\n for door in [ 0\u00a0: doors.len()\u00a0: pass+1 ]\n doors[ door ] = not doors[ door ]\n end\nend\n\nfor door in [ 1\u00a0: doors.len() ] // Show Output\n > \"Door \", $door, \" is: \", ( doors[ door ] )\u00a0? \"open\"\u00a0: \"closed\"\nend", "safe": true }, { "filename": "100 doors_255.txt", "content": "for door in [ 1\u00a0: 101 ]: > \"Door \", $door, \" is: \", fract( door ** 0.5 )\u00a0? \"closed\"\u00a0: \"open\"", "safe": true }, { "filename": "100 doors_256.txt", "content": "100[$][0 1\u00f8:1-]# {initialize doors}\n%\n[s;[$101\\>][$$;~\\:s;+]#%]d: {function d, switch door state function}\n1s:[s;101\\>][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}\n1[$101\\>][$$.\" \";$[\"open\n\"]?~[\"closed\n\"]?1+]# {loop through doors, print door number and state}", "safe": true }, { "filename": "100 doors_257.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n...\n98 closed\n99 closed\n100 open", "safe": true }, { "filename": "100 doors_258.txt", "content": " states\u00a0:= (1..100).toList\n 100.times |i| {\n states = states.map |state| { state\u00a0% (i+1) == 0\u00a0? -state\u00a0: +state }\n }\n echo(\"Open doors are \" + states.findAll { it < 0 }.map { -it })", "safe": true }, { "filename": "100 doors_259.txt", "content": " echo(\"Open doors are \" + (1..100).toList.findAll { it.toFloat.pow(0.5f).toInt.pow(2) == it})", "safe": true }, { "filename": "100 doors_26.txt", "content": "Using #HASH-OFF, OPTION OICC =\"^\" , CICC =\"^\"\n", "safe": true }, { "filename": "100 doors_260.txt", "content": "#AppType Console\n\nDim doors[], n As Integer = 100\n\nFor Dim i = 1 To n\n\tFor Dim j = i To n Step i\n\t\tdoors[j] = Not doors[j]\n\tNext\nNext\n\nFor i = 1 To n\n\tIf doors[i] Then Print \"Door \", i, \" is open\"\nNext\n\nPause", "safe": true }, { "filename": "100 doors_261.txt", "content": "#APPTYPE CONSOLE\n\nDIM i = 0, j = 0, door = 1\n\nWHILE INCR(i) < 101\n IF i = door THEN\n PRINT \"Door \", door, \" open\"\n INCR(door, INCR((INCR(j) << 1)))\n END IF\nWEND\n\nPAUSE", "safe": true }, { "filename": "100 doors_262.txt", "content": "; macro for finite loop\n(= repeat (mac (i n . body)\n (list 'do\n (list 'let i 0)\n (list 'while (list '< i n)\n (list '= i (list '+ i 1))\n (cons 'do body)))))\n\n; function to get n-th element of list\n(= nth (fn (i lst)\n (while (< 0 i)\n (= i (- i 1))\n (= lst (cdr lst)))\n lst))\n\n; make list of 100 nils\n(repeat i 100 (= doors (cons nil doors)))\n\n; do algorithm iterations\n(repeat i 100\n (let pos (nth (- i 1) doors))\n (while pos\n (setcar pos (not (car pos)))\n (= pos (nth i pos))))\n\n(print doors)", "safe": true }, { "filename": "100 doors_263.txt", "content": "; do algorithm iterations sqrt(100) = 10 times\n(repeat i 10 (setcar (nth (- (* i i) 1) doors) 't))", "safe": true }, { "filename": "100 doors_264.txt", "content": "doors = malloc$ 100u\nfor uint [0u, sizeof$ doors) with l1 {\n put_byte$ + doors l1 as false byte\n}\nfunction void pass(step:uint) {\n location = step\n while <= location sizeof$ doors {\n ac = - + doors location 1u\n put_byte$ ac ~ deref_byte$ ac// true is represented as 255 (0xff)\n location = + location step\n }\n}\nfor uint (0u, sizeof$ doors] with l2 {//range exclusive of 0, inclusive of 100\n pass$ l2\n}\ncount = 1u\nfor ubyte as doors listubyte with isopen {// list for-each\n if as isopen bool {// cast byte to bool\n puts$ \"door \"\n putui$ count\n puts$ \" is open\\n\"\n }\u00a0;\n count = + count 1u\n}\nfree$ doors", "safe": true }, { "filename": "100 doors_265.txt", "content": "1001-p01.\n>0101-p02.\n>101-g001-g+:::aa*)?v101-p03.\n>02-g?v1}02-p02. >05.\n >0}02-p02.\n>~~~0101-p001-g:1+001-paa*)?v02.\n >07.\n>0101-p08.\n>101-g::02-g?v >1+:101-paa*=?;\n >n\" \"o^", "safe": true }, { "filename": "100 doors_266.txt", "content": "1.1 F N=1,100;S D(N)=0\n1.2 F M=1,100;F N=M,M,100;S D(N)=1-D(N)\n1.3 F N=1,100;D 2.0\n1.4 Q\n2.1 I (D(N)),,2.2;R\n2.2 T \"OPEN DOOR \",%3.0,N,!", "safe": true }, { "filename": "100 doors_267.txt", "content": "OPEN DOOR = 1\nOPEN DOOR = 4\nOPEN DOOR = 9\nOPEN DOOR = 16\nOPEN DOOR = 25\nOPEN DOOR = 36\nOPEN DOOR = 49\nOPEN DOOR = 64\nOPEN DOOR = 81\nOPEN DOOR = 100", "safe": true }, { "filename": "100 doors_268.txt", "content": ": toggle ( c-addr -- ) \\ toggle the byte at c-addr\n dup c@ 1 xor swap c!\u00a0;\n\n100 1+ ( 1-based indexing ) constant ndoors\ncreate doors ndoors allot\n\n: init ( -- ) doors ndoors erase\u00a0; \\ close all doors\n\n: pass ( n -- ) \\ toggle every nth door\n ndoors over do\n doors i + toggle\n dup ( n ) +loop drop\u00a0;\n\n: run ( -- ) ndoors 1 do i pass loop\u00a0;\n: display ( -- ) \\ display open doors\n ndoors 1 do doors i + c@ if i . then loop cr\u00a0;\n\ninit run display", "safe": true }, { "filename": "100 doors_269.txt", "content": ": squared ( n -- n' ) dup *\u00a0;\n: doors ( n -- )\n 1 begin 2dup squared >= while\n dup squared .\n 1+ repeat 2drop\u00a0;\n100 doors", "safe": true }, { "filename": "100 doors_27.txt", "content": "VAR sStatus: SHORT\nVAR sArray: SHORT\nVAR sCount: SHORT\nVAR sDoor: SHORT\nVAR sPass: SHORT\nVAR zIndex: STRING\nVAR zState: STRING\n//\nSET sStatus = GET_UNUSED_ARRAY_HANDLE(sArray)\nSET sStatus = INIT_SORTED_ARRAY(sArray, 0, 0, 1)\n//\nDO sCount = 1 TO 100\n DO sPass = 1 TO 100\n SET sDoor = sCount * sPass\n IF sDoor <= 100\n SET zIndex = REPEAT(\"0\", 3 - LENGTH(STR(sDoor))) + STR(sDoor)\n SET sStatus = READ_ARRAY_REC(\"=\", sArray, zIndex)\n SET zState = \"OPEN\"\n IF GET_STRING_SAY(sArray, 1) = \"OPEN\"\n SET zState = \"CLOSE\"\n ENDIF\n //\n SET sStatus = ADD_ARRAY_REC(sArray, zIndex)\n SET sStatus = PUT_STRING_SAY(sArray, 1, zState)\n ELSE\n BREAK\n ENDIF\n ENDDO\nENDDO\n//\nSET zIndex = \"\"\nSET sStatus = READ_ARRAY_REC(\">=\", sArray, zIndex)\nDO WHILE sStatus = 0\n >>Door: ^zIndex^ State: ^GET_STRING_SAY(sArray, 1)^\n SET sStatus = READ_ARRAY_REC(\"+\", sArray, zIndex)\nENDDO", "safe": true }, { "filename": "100 doors_270.txt", "content": "program doors\n implicit none\n integer, allocatable\u00a0:: door(:)\n character(6), parameter\u00a0:: s(0:1) = [character(6)\u00a0:: \"closed\", \"open\"]\n integer\u00a0:: i, n\n \n print \"(A)\", \"Number of doors?\"\n read *, n\n allocate (door(n))\n door = 1\n do i = 1, n\n door(i:n:i) = 1 - door(i:n:i)\n print \"(A,G0,2A)\", \"door \", i, \" is \", s(door(i))\n end do\nend program", "safe": true }, { "filename": "100 doors_271.txt", "content": "PROGRAM DOORS\n\n INTEGER, PARAMETER\u00a0:: n = 100 \u00a0! Number of doors\n INTEGER\u00a0:: i\n LOGICAL\u00a0:: door(n) = .TRUE. \u00a0! Initially closed\n \n DO i = 1, SQRT(REAL(n))\n door(i*i) = .FALSE.\n END DO \n \n DO i = 1, n\n WRITE(*,\"(A,I3,A)\", ADVANCE=\"NO\") \"Door \", i, \" is \"\n IF (door(i)) THEN\n WRITE(*,\"(A)\") \"closed\"\n ELSE\n WRITE(*,\"(A)\") \"open\"\n END IF\n END DO\n \nEND PROGRAM DOORS", "safe": true }, { "filename": "100 doors_272.txt", "content": "program OneHundredIsOpen;\n\nconst\n DoorCount = 100;\n\nvar\n IsOpen: array[1..DoorCount] of boolean;\n Door, Jump: integer;\n\nbegin\n // Close all doors\n for Door\u00a0:= 1 to DoorCount do\n IsOpen[Door]\u00a0:= False;\n // Iterations\n for Jump\u00a0:= 1 to DoorCount do\n begin\n Door\u00a0:= Jump;\n repeat\n IsOpen[Door]\u00a0:= not IsOpen[Door];\n Door\u00a0:= Door + Jump;\n until Door > DoorCount;\n end;\n // Show final status\n for Door\u00a0:= 1 to DoorCount do\n begin\n Write(Door, ' ');\n if IsOpen[Door] then\n WriteLn('open')\n else\n WriteLn('closed');\n end;\n // Wait for \n Readln;\nend.", "safe": true }, { "filename": "100 doors_273.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n, n1, door(1 To max_doors)\n\n' toggle, at start all doors are closed (0)\n' 0 = door closed, 1 = door open\nFor n = 1 To max_doors\n For n1 = n To max_doors Step n\n door(n1) = 1 - door(n1)\n Next\nNext\n\n' count the doors that are open (1)\nPrint \"doors that are open nr: \";\nFor n = 1 To max_doors\n If door(n) = 1 Then\n Print n; \" \";\n c = c + 1\n End If\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100 doors_274.txt", "content": "doors that are open nr: 1 4 9 16 25 36 49 64 81 100 \n\nThere are 10 doors open", "safe": true }, { "filename": "100 doors_275.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n, n1, door(1 To max_doors)\n\n' at start all doors are closed\n' simple add 1 each time we open or close a door\n' doors with odd numbers are open\n' doors with even numbers are closed\nFor n = 1 To max_doors\n For n1 = n To max_doors Step n\n door(n1) += 1\n Next\nNext\n\nPrint \"doors that are open nr: \";\nFor n = 1 To max_doors\n If door(n) And 1 Then\n Print n; \" \";\n c = c + 1\n End If\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100 doors_276.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n\n\nPrint \"doors that are open nr: \";\nFor n = 1 To 10\n Print n * n; \" \";\n c = c + 1\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100 doors_277.txt", "content": "' version 16-06-2021\n' portado desde Julia\n\nFor i As Integer = 1 To 10\n If (i Mod i^2) < 11 Then Print \"La puerta\"; i^2; \" esta abierta\" \nNext i\nSleep", "safe": true }, { "filename": "100 doors_278.txt", "content": "# Set doors to empty list\nset doors\n\n# Initialize doors arrays\nfor i in (seq 100)\n set doors[$i] 0\nend\n\nfor i in (seq 100)\n set j $i\n while test $j -le 100\n # Logical not on doors\n set doors[$j] (math\u00a0!$doors[$j])\n set j (math $j + $i)\n end\nend\n\n# Print every door\nfor i in (seq (count $doors))\n echo -n \"$i \"\n if test $doors[$i] -eq 0\n echo closed\n else\n echo open\n end\nend", "safe": true }, { "filename": "100 doors_279.txt", "content": "# Set doors to empty list\nset doors\n\nfor i in (seq 100)\n set doors[(math \"$i * $i\")] 1\n echo -n \"$i \"\n if test $doors[$i] -eq 1\n echo open\n else\n echo closed\n end\nend", "safe": true }, { "filename": "100 doors_28.txt", "content": "Door: 001 State: OPEN\nDoor: 002 State: CLOSE\nDoor: 003 State: CLOSE\nDoor: 004 State: OPEN\nDoor: 005 State: CLOSE\nDoor: 006 State: CLOSE\nDoor: 007 State: CLOSE\nDoor: 008 State: CLOSE\nDoor: 009 State: OPEN\nDoor: 010 State: CLOSE\nDoor: 011 State: CLOSE\nDoor: 012 State: CLOSE\nDoor: 013 State: CLOSE\nDoor: 014 State: CLOSE\nDoor: 015 State: CLOSE\nDoor: 016 State: OPEN\nDoor: 017 State: CLOSE\nDoor: 018 State: CLOSE\nDoor: 019 State: CLOSE\nDoor: 020 State: CLOSE\nDoor: 021 State: CLOSE\nDoor: 022 State: CLOSE\nDoor: 023 State: CLOSE\nDoor: 024 State: CLOSE\nDoor: 025 State: OPEN\nDoor: 026 State: CLOSE\nDoor: 027 State: CLOSE\nDoor: 028 State: CLOSE\nDoor: 029 State: CLOSE\nDoor: 030 State: CLOSE\nDoor: 031 State: CLOSE\nDoor: 032 State: CLOSE\nDoor: 033 State: CLOSE\nDoor: 034 State: CLOSE\nDoor: 035 State: CLOSE\nDoor: 036 State: OPEN\nDoor: 037 State: CLOSE\nDoor: 038 State: CLOSE\nDoor: 039 State: CLOSE\nDoor: 040 State: CLOSE\nDoor: 041 State: CLOSE\nDoor: 042 State: CLOSE\nDoor: 043 State: CLOSE\nDoor: 044 State: CLOSE\nDoor: 045 State: CLOSE\nDoor: 046 State: CLOSE\nDoor: 047 State: CLOSE\nDoor: 048 State: CLOSE\nDoor: 049 State: OPEN\nDoor: 050 State: CLOSE\nDoor: 051 State: CLOSE\nDoor: 052 State: CLOSE\nDoor: 053 State: CLOSE\nDoor: 054 State: CLOSE\nDoor: 055 State: CLOSE\nDoor: 056 State: CLOSE\nDoor: 057 State: CLOSE\nDoor: 058 State: CLOSE\nDoor: 059 State: CLOSE\nDoor: 060 State: CLOSE\nDoor: 061 State: CLOSE\nDoor: 062 State: CLOSE\nDoor: 063 State: CLOSE\nDoor: 064 State: OPEN\nDoor: 065 State: CLOSE\nDoor: 066 State: CLOSE\nDoor: 067 State: CLOSE\nDoor: 068 State: CLOSE\nDoor: 069 State: CLOSE\nDoor: 070 State: CLOSE\nDoor: 071 State: CLOSE\nDoor: 072 State: CLOSE\nDoor: 073 State: CLOSE\nDoor: 074 State: CLOSE\nDoor: 075 State: CLOSE\nDoor: 076 State: CLOSE\nDoor: 077 State: CLOSE\nDoor: 078 State: CLOSE\nDoor: 079 State: CLOSE\nDoor: 080 State: CLOSE\nDoor: 081 State: OPEN\nDoor: 082 State: CLOSE\nDoor: 083 State: CLOSE\nDoor: 084 State: CLOSE\nDoor: 085 State: CLOSE\nDoor: 086 State: CLOSE\nDoor: 087 State: CLOSE\nDoor: 088 State: CLOSE\nDoor: 089 State: CLOSE\nDoor: 090 State: CLOSE\nDoor: 091 State: CLOSE\nDoor: 092 State: CLOSE\nDoor: 093 State: CLOSE\nDoor: 094 State: CLOSE\nDoor: 095 State: CLOSE\nDoor: 096 State: CLOSE\nDoor: 097 State: CLOSE\nDoor: 098 State: CLOSE\nDoor: 099 State: CLOSE\nDoor: 100 State: OPEN\n", "safe": true }, { "filename": "100 doors_280.txt", "content": "doors = new array[[101], false]\nfor pass=1 to 100\n for door=pass to 100 step pass\n doors@door =\u00a0! doors@door\n\nprint[\"Open doors: \"]\nfor door=1 to 100\n if doors@door\n print[\"$door \"]", "safe": true }, { "filename": "100 doors_281.txt", "content": "define i = 0, d = 0\n\ndo\n\n\tlet i = i + 1\n\tlet d = i * i\n\tprint d\n\nloop d < 100\n\npause\nend", "safe": true }, { "filename": "100 doors_282.txt", "content": "for i <- 1..100\n r = foldl1( \\a, b -> a xor b, [(a|i) | a <- 1..100] )\n println( i + ' ' + (if r then 'open' else 'closed') )", "safe": true }, { "filename": "100 doors_283.txt", "content": "import math.sqrt\n\nfor i <- 1..100\n println( i + ' ' + (if sqrt(i) is Integer then 'open' else 'closed') )", "safe": true }, { "filename": "100 doors_284.txt", "content": "let main(n: i32): [n]bool =\n loop is_open = replicate n false for i < n do\n let js = map (*i+1) (iota n)\n let flips = map (\\j ->\n if j < n\n then unsafe !is_open[j]\n else true -- Doesn't matter.\n ) js\n in scatter is_open js flips", "safe": true }, { "filename": "100 doors_285.txt", "content": "include \"NSLog.incl\"\n\nNSInteger door, square = 1, increment = 3\n\nfor door = 1 to 100\n if ( door == square )\n NSLog( @\"Door %ld is open.\", door )\n square += increment\u00a0: increment += 2\n else\n NSLog( @\"Door %ld is closed.\", door )\n end if\nnext\n\nHandleEvents", "safe": true }, { "filename": "100 doors_286.txt", "content": "Door 1 is open.\nDoor 2 is closed.\nDoor 3 is closed.\nDoor 4 is open.\nDoor 5 is closed.\nDoor 6 is closed.\nDoor 7 is closed.\nDoor 8 is closed.\nDoor 9 is open.\nDoor 10 is closed.\nDoor 11 is closed.\nDoor 12 is closed.\nDoor 13 is closed.\nDoor 14 is closed.\nDoor 15 is closed.\nDoor 16 is open.\nDoor 17 is closed.\nDoor 18 is closed.\nDoor 19 is closed.\nDoor 20 is closed.\nDoor 21 is closed.\nDoor 22 is closed.\nDoor 23 is closed.\nDoor 24 is closed.\nDoor 25 is open.\nDoor 26 is closed.\nDoor 27 is closed.\nDoor 28 is closed.\nDoor 29 is closed.\nDoor 30 is closed.\nDoor 31 is closed.\nDoor 32 is closed.\nDoor 33 is closed.\nDoor 34 is closed.\nDoor 35 is closed.\nDoor 36 is open.\nDoor 37 is closed.\nDoor 38 is closed.\nDoor 39 is closed.\nDoor 40 is closed.\nDoor 41 is closed.\nDoor 42 is closed.\nDoor 43 is closed.\nDoor 44 is closed.\nDoor 45 is closed.\nDoor 46 is closed.\nDoor 47 is closed.\nDoor 48 is closed.\nDoor 49 is open.\nDoor 50 is closed.\nDoor 51 is closed.\nDoor 52 is closed.\nDoor 53 is closed.\nDoor 54 is closed.\nDoor 55 is closed.\nDoor 56 is closed.\nDoor 57 is closed.\nDoor 58 is closed.\nDoor 59 is closed.\nDoor 60 is closed.\nDoor 61 is closed.\nDoor 62 is closed.\nDoor 63 is closed.\nDoor 64 is open.\nDoor 65 is closed.\nDoor 66 is closed.\nDoor 67 is closed.\nDoor 68 is closed.\nDoor 69 is closed.\nDoor 70 is closed.\nDoor 71 is closed.\nDoor 72 is closed.\nDoor 73 is closed.\nDoor 74 is closed.\nDoor 75 is closed.\nDoor 76 is closed.\nDoor 77 is closed.\nDoor 78 is closed.\nDoor 79 is closed.\nDoor 80 is closed.\nDoor 81 is open.\nDoor 82 is closed.\nDoor 83 is closed.\nDoor 84 is closed.\nDoor 85 is closed.\nDoor 86 is closed.\nDoor 87 is closed.\nDoor 88 is closed.\nDoor 89 is closed.\nDoor 90 is closed.\nDoor 91 is closed.\nDoor 92 is closed.\nDoor 93 is closed.\nDoor 94 is closed.\nDoor 95 is closed.\nDoor 96 is closed.\nDoor 97 is closed.\nDoor 98 is closed.\nDoor 99 is closed.\nDoor 100 is open.\n", "safe": true }, { "filename": "100 doors_287.txt", "content": "READ x,y,z\nPRINT \"Open doors: \";x;\" \";\nCYCLE\n z=x+y\n PRINT z;\" \";\n x=z\n y=y+2\nREPEAT UNTIL z>=100\nDATA 1,3,0\nEND", "safe": true }, { "filename": "100 doors_288.txt", "content": "Public Sub Main()\nDim bDoor As New Boolean[101]\nDim siCount1, siCount2, siStart As Short\n\nFor siCount1 = 1 To 100\n Inc siStart\n For siCount2 = siStart To 100 Step siCount1\n bDoor[siCount2] = Not bDoor[siCount2]\n Next\nNext\n\nFor siCount1 = 1 To 100\n If bDoor[siCount1] Then Print siCount1;;\nNext\n\nEnd", "safe": true }, { "filename": "100 doors_289.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_29.txt", "content": "with Ada.Text_Io; use Ada.Text_Io;\n \n procedure Doors is\n type Door_State is (Closed, Open);\n type Door_List is array(Positive range 1..100) of Door_State;\n The_Doors : Door_List := (others => Closed);\n begin\n for I in 1..100 loop\n for J in The_Doors'range loop\n if J mod I = 0 then\n if The_Doors(J) = Closed then\n The_Doors(J) := Open;\n else\n The_Doors(J) := Closed;\n end if;\n end if;\n end loop;\n end loop;\n for I in The_Doors'range loop\n Put_Line(Integer'Image(I) & \" is \" & Door_State'Image(The_Doors(I)));\n end loop;\n end Doors;\n", "safe": true }, { "filename": "100 doors_290.txt", "content": "doors\u00a0:= function(n)\n local a,j,s;\n a\u00a0:= [ ];\n for j in [1 .. n] do\n a[j]\u00a0:= 0;\n od;\n for s in [1 .. n] do\n j\u00a0:= s;\n while j <= n do\n a[j]\u00a0:= 1 - a[j];\n j\u00a0:= j + s;\n od;\n od;\n return Filtered([1 .. n], j -> a[j] = 1);\nend;\n\ndoors(100);\n# [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]", "safe": true }, { "filename": "100 doors_291.txt", "content": "func Doors(door_count:int) -> void\u00a0:\n var doors\u00a0: Array\n doors.resize(door_count)\n\n # Note\u00a0: Initialization is not necessarily mandatory (by default values are false)\n # Intentionally left here\n for i in door_count\u00a0:\n doors[i] = false\n\n # do visits\n for i in door_count\u00a0:\n for j in range(i,door_count,i+1)\u00a0:\n doors[j] = not doors[j]\n \t\n # print results\n var results\u00a0: String = \"\"\n for i in door_count\u00a0:\n results += str(i+1) + \" \" if doors[i] else \"\"\n print(\"Doors open\u00a0: %s\"\u00a0% [results] )\n\n# calling the function from the _ready function\nfunc _ready() -> void\u00a0:\n Doors(100)", "safe": true }, { "filename": "100 doors_292.txt", "content": "Doors open\u00a0: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_293.txt", "content": "// 100 doors problem\n// Author: Sinuhe masan (2019)\ninit\n\n\t// 100 elements array of boolean type\n\tdoors:bool[100]\n \n\tfor var i = 1 to 100\n\t\tdoors[i] = false // set all doors closed\n \n \n\tfor var i = 1 to 100\n\t\tj:int = i\n\t\twhile j <= 100 do\n\t\t\tdoors[j] = not doors[j]\n\t\t\tj = j + i\n \n\tprint(\"Doors open: \")\n\tfor var i = 1 to 100\n\t\tif doors[i]\n\t\t\tstdout.printf (\"%d \", i)", "safe": true }, { "filename": "100 doors_294.txt", "content": "100` *=0=>d $$ create vector 1..100, create bit pattern d, marking all equal to 0\n:for (1..100[.s]){ $$ loop s from 1 to 100\n d^(100` %s *=0 )=>d;} $$ d = d xor (bit pattern of vector 1..100\u00a0% s)\nd $$ output d", "safe": true }, { "filename": "100 doors_295.txt", "content": "Result:\n10010000 10000001 00000000 10000000 00010000 00000000 10000000 00000001 00000000 00000000 10000000 00000000 0001", "safe": true }, { "filename": "100 doors_296.txt", "content": "var doors,a,i;\n//Sets up the array for all of the doors.\nfor (i = 1; i<=100; i += 1)\n {\n doors[i]=0;\n }\n\n//This first for loop goes through and passes the interval down to the next for loop.\nfor (i = 1; i <= 100; i += 1;)\n {\n //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..)\n for (a = 0; a <= 100; a += i;)\n {\n //Opens or closes a door.\n doors[a] = !doors[a];\n }\n }\nopen_doors = '';\n\n//This for loop goes through the array and checks for open doors.\n//If the door is open it adds it to the string then displays the string.\nfor (i = 1; i <= 100; i += 1;)\n {\n if (doors[i] == 1)\n {\n open_doors += \"Door Number \"+string(i)+\" is open#\";\n }\n }\nshow_message(open_doors);\ngame_end();", "safe": true }, { "filename": "100 doors_297.txt", "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n doors\u00a0:= [100]bool{}\n\n // the 100 passes called for in the task description\n for pass\u00a0:= 1; pass <= 100; pass++ {\n for door\u00a0:= pass-1; door < 100; door += pass {\n doors[door] = !doors[door]\n }\n }\n\n // one more pass to answer the question\n for i, v\u00a0:= range doors {\n if v {\n fmt.Print(\"1\")\n } else {\n fmt.Print(\"0\")\n }\n\n if i%10 == 9 {\n fmt.Print(\"\\n\")\n } else {\n fmt.Print(\" \")\n }\n\n }\n}", "safe": true }, { "filename": "100 doors_298.txt", "content": "1 0 0 1 0 0 0 0 1 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 0 0 0 0 1 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 1\n", "safe": true }, { "filename": "100 doors_299.txt", "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var door int = 1\n var incrementer = 0\n\n for current\u00a0:= 1; current <= 100; current++ {\n fmt.Printf(\"Door %d \", current)\n\n if current == door {\n fmt.Printf(\"Open\\n\")\n incrementer++\n door += 2*incrementer + 1\n } else {\n fmt.Printf(\"Closed\\n\")\n }\n }\n}", "safe": true }, { "filename": "100 doors_3.txt", "content": " 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_30.txt", "content": "with Ada.Text_Io; use Ada.Text_Io;\n with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;\n \n procedure Doors_Optimized is\n Num : Float;\n begin\n for I in 1..100 loop\n Num := Sqrt(Float(I));\n Put(Integer'Image(I) & \" is \");\n if Float'Floor(Num) = Num then\n Put_Line(\"Opened\");\n else\n Put_Line(\"Closed\");\n end if;\n end loop;\n end Doors_Optimized;\n", "safe": true }, { "filename": "100 doors_300.txt", "content": "// 100 (optimized) doors in Go\n\npackage main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n for i\u00a0:= 1; i <= 100; i++ {\n f\u00a0:= math.Sqrt(float64(i))\n if math.Mod(f, 1) == 0 {\n fmt.Print(\"O\")\n } else {\n fmt.Print(\"-\")\n }\n }\n fmt.Println()\n}", "safe": true }, { "filename": "100 doors_301.txt", "content": "O--O----O------O--------O----------O------------O--------------O----------------O------------------O\n", "safe": true }, { "filename": "100 doors_302.txt", "content": "100:c;[{0}c*]:d;\nc,{.c,>\\)%{.d<\\.d=1^\\)d>++:d;}/}/\n[c,{)\"door \"\\+\" is\"+}%d{{\"open\"}{\"closed\"}if}%]zip\n{\" \"*puts}/", "safe": true }, { "filename": "100 doors_303.txt", "content": "100,{)}%\n{:d.sqrt 2?=\n{\"open\"}{\"close\"}if\"door \"d+\" is \"+\\+puts}/", "safe": true }, { "filename": "100 doors_304.txt", "content": "[{\"close\"}100*]:d;\n10,{)2?(.d<\\[\"open\"]\\)d>++:d;}/\n[100,{)\"door \"\\+\" is\"+}%d]zip\n{\" \"*puts}/", "safe": true }, { "filename": "100 doors_305.txt", "content": "uses java.util.Arrays\n\nvar doors = new boolean[100]\nArrays.fill( doors, false )\n\nfor( pass in 1..100 ) {\n var counter = pass-1\n while( counter < 100 ) {\n doors[counter] = !doors[counter]\n counter += pass\n }\n}\n\nfor( door in doors index i ) {\n print( \"door ${i+1} is ${door\u00a0? 'open'\u00a0: 'closed'}\" )\n}", "safe": true }, { "filename": "100 doors_306.txt", "content": "var door = 1\nvar delta = 0\n\nfor( i in 1..100 ) {\n if( i == door ) {\n print( \"door ${i} is open\" )\n delta++\n door += 2*delta + 1\n } else {\n print( \"door ${i} is closed\" )\n }\n}", "safe": true }, { "filename": "100 doors_307.txt", "content": "doors = [false] * 100\n(0..99).each {\n it.step(100, it + 1) {\n doors[it] ^= true\n }\n}\n(0..99).each {\n println(\"Door #${it + 1} is ${doors[it]\u00a0? 'open'\u00a0: 'closed'}.\")\n}", "safe": true }, { "filename": "100 doors_308.txt", "content": "(1..100).each {\n println(\"Door #${it} is ${Math.sqrt(it).with{it==(int)it}\u00a0? 'open'\u00a0: 'closed'}.\")\n}", "safe": true }, { "filename": "100 doors_309.txt", "content": "doors = ['closed'] * 100\n(1..10).each { doors[it**2 - 1] = 'open' }\n(0..99).each {\n println(\"Door #${it + 1} is ${doors[it]}.\")\n}", "safe": true }, { "filename": "100 doors_31.txt", "content": "# find the first few squares via the unoptimised door flipping method\nscope\n\n local doorMax\u00a0:= 100;\n local door;\n create register door( doorMax );\n\n # set all doors to closed\n for i to doorMax do door[ i ]\u00a0:= false od;\n\n # repeatedly flip the doors\n for i to doorMax do\n for j from i to doorMax by i do door[ j ]\u00a0:= not door[ j ] od\n od;\n\n # display the results\n for i to doorMax do if door[ i ] then write( \" \", i ) fi od; print()\n\nepocs", "safe": true }, { "filename": "100 doors_310.txt", "content": "10 DIM A(100)\n20 FOR OFFSET = 1 TO 100\n30 FOR I = 0 TO 100 STEP OFFSET\n40 A(I) = A(I) + 1\n50 NEXT I\n60 NEXT OFFSET\n70 ' Print \"opened\" doors\n80 FOR I = 1 TO 100\n90 IF A(I) MOD 2 = 1 THEN PRINT I\n100 NEXT I", "safe": true }, { "filename": "100 doors_311.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100 doors_312.txt", "content": "#define ARRAY_ELEMENTS 100\nPROCEDURE Main()\n LOCAL aDoors\u00a0:= Array( ARRAY_ELEMENTS )\n LOCAL i, j\n\n AFill( aDoors, .F. )\n FOR i\u00a0:= 1 TO ARRAY_ELEMENTS\n FOR j\u00a0:= i TO ARRAY_ELEMENTS STEP i\n aDoors[ j ] =\u00a0! aDoors[ j ]\n NEXT\n NEXT\n AEval( aDoors, {|e, n| QQout( Padl(n,3) + \" is \" + Iif(aDoors[n], \"*open*\", \"closed\" ) + \"|\" ), Iif( n%5 == 0, Qout(), e:=NIL) } )\n RETURN", "safe": true }, { "filename": "100 doors_313.txt", "content": "#define ARRAY_ELEMENTS 100\nPROCEDURE Main()\n LOCAL aDoors\u00a0:= Array( ARRAY_ELEMENTS )\n\n AFill( aDoors, .F. )\n AEval( aDoors, {|e, n| aDoors[n]\u00a0:= e\u00a0:= Iif( Int(Sqrt(n))==Sqrt(n), .T., .F. ) } )\n AEval( aDoors, {|e, n| QQout( Padl(n,3) + \" is \" + Iif(aDoors[n], \"*open*\", \"closed\" ) + \"|\" ), Iif( n%5 == 0, Qout(), e:=NIL )} )\n RETURN", "safe": true }, { "filename": "100 doors_314.txt", "content": " 1 is *open*| 2 is closed| 3 is closed| 4 is *open*| 5 is closed| \n 6 is closed| 7 is closed| 8 is closed| 9 is *open*| 10 is closed| \n11 is closed| 12 is closed| 13 is closed| 14 is closed| 15 is closed| \n16 is *open*| 17 is closed| 18 is closed| 19 is closed| 20 is closed| \n21 is closed| 22 is closed| 23 is closed| 24 is closed| 25 is *open*| \n26 is closed| 27 is closed| 28 is closed| 29 is closed| 30 is closed| \n31 is closed| 32 is closed| 33 is closed| 34 is closed| 35 is closed| \n36 is *open*| 37 is closed| 38 is closed| 39 is closed| 40 is closed| \n41 is closed| 42 is closed| 43 is closed| 44 is closed| 45 is closed| \n46 is closed| 47 is closed| 48 is closed| 49 is *open*| 50 is closed| \n51 is closed| 52 is closed| 53 is closed| 54 is closed| 55 is closed| \n56 is closed| 57 is closed| 58 is closed| 59 is closed| 60 is closed| \n61 is closed| 62 is closed| 63 is closed| 64 is *open*| 65 is closed| \n66 is closed| 67 is closed| 68 is closed| 69 is closed| 70 is closed| \n71 is closed| 72 is closed| 73 is closed| 74 is closed| 75 is closed| \n76 is closed| 77 is closed| 78 is closed| 79 is closed| 80 is closed| \n81 is *open*| 82 is closed| 83 is closed| 84 is closed| 85 is closed| \n86 is closed| 87 is closed| 88 is closed| 89 is closed| 90 is closed| \n91 is closed| 92 is closed| 93 is closed| 94 is closed| 95 is closed| \n96 is closed| 97 is closed| 98 is closed| 99 is closed|100 is *open*|\n", "safe": true }, { "filename": "100 doors_315.txt", "content": "data Door\n = Open\n | Closed\n deriving (Eq, Show)\n\ntoggle\u00a0:: Door -> Door\ntoggle Open = Closed\ntoggle Closed = Open\n\ntoggleEvery\u00a0:: Int -> [Door] -> [Door]\ntoggleEvery k = zipWith toggleK [1 ..]\n where\n toggleK n door\n | n `mod` k == 0 = toggle door\n | otherwise = door\n\nrun\u00a0:: Int -> [Door]\nrun n = foldr toggleEvery (replicate n Closed) [1 .. n]\n\nmain\u00a0:: IO ()\nmain = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100)", "safe": true }, { "filename": "100 doors_316.txt", "content": "[(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]", "safe": true }, { "filename": "100 doors_317.txt", "content": "run n = findIndices odd $ foldr toggleEvery (replicate n 0) [0..n] where toggleEvery k = zipWith (+) $ cycle $ 1\u00a0: replicate k 0", "safe": true }, { "filename": "100 doors_318.txt", "content": "gate\u00a0:: Eq a => [a] -> [a] -> [Door]\ngate (x:xs) (y:ys) | x == y = Open \u00a0: gate xs ys\ngate (x:xs) ys = Closed\u00a0: gate xs ys\ngate [] _ = []\n\nrun n = gate [1..n] [k*k | k <- [1..]]", "safe": true }, { "filename": "100 doors_319.txt", "content": "run n = takeWhile (< n) [k*k | k <- [1..]]", "safe": true }, { "filename": "100 doors_32.txt", "content": "var doors = new int [100]\n\nforeach pass 100 {\n for (var door = pass\u00a0; door < 100\u00a0; door += pass+1) {\n doors[door] = !doors[door]\n }\n}\n\nvar d = 1\nforeach door doors {\n println (\"door \" + d++ + \" is \" + (door\u00a0? \"open\"\u00a0: \"closed\"))\n\n}", "safe": true }, { "filename": "100 doors_320.txt", "content": "class Main\n{\n static public function main()\n {\n findOpenDoors( 100 );\n }\n\n static function findOpenDoors( n\u00a0: Int )\n {\n var door = [];\n for( i in 0...n + 1 ){ door[ i ] = false; }\n for( i in 1...n + 1 ){\n var j = i;\n while( j <= n ){ \n door[ j ] =\u00a0! door[ j ];\n j += i;\n }\n }\n for( i in 1...n + 1 ){\n if( door[ i ] ){ Sys.print( ' $i' ); }\n }\n }\n}", "safe": true }, { "filename": "100 doors_321.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_322.txt", "content": "class RosettaDemo\n{\n static public function main()\n {\n findOpenLockers(100);\n }\n\n static function findOpenLockers(n\u00a0: Int)\n {\n var i = 1;\n\n while((i*i) <= n)\n {\n Sys.println(i*i);\n i++;\n }\n }\n}", "safe": true }, { "filename": "100 doors_323.txt", "content": "REAL\u00a0:: n=100, open=1, door(n)\n\ndoor = 1 - open\u00a0! = closed\nDO i = 1, n\n DO j = i, n, i\n door(j) = open - door(j)\n ENDDO\nENDDO\nDLG(Text=door, TItle=SUM(door)//\" doors open\")", "safe": true }, { "filename": "100 doors_324.txt", "content": "door = 1 - open\u00a0! = closed\nDO i = 1, n^0.5\n door(i*i) = open\nENDDO\nDLG(Text=door, TItle=SUM(door)//\" doors open\")", "safe": true }, { "filename": "100 doors_325.txt", "content": "U8 is_open[100];\nU8 pass = 0, door = 0;\n\n/* do the 100 passes */\nfor (pass = 0; pass < 100; ++pass)\n for (door = pass; door < 100; door += pass + 1)\n is_open[door] = !is_open[door];\n\n/* output the result */\nfor (door = 0; door < 100; ++door)\n if (is_open[door])\n Print(\"Door #%d is open.\\n\", door + 1);\n else\n Print(\"Door #%d is closed.\\n\", door + 1);", "safe": true }, { "filename": "100 doors_326.txt", "content": "|^\n=/ doors=(list\u00a0?) (reap 100\u00a0%.n)\n=/ passes=(list (list\u00a0?)) (turn (gulf 1 100) pass-n)\n|-\n?~ passes doors\n$(doors (toggle doors i.passes), passes t.passes)\n++ pass-n\n |= n=@ud\n (turn (gulf 1 100) |=(k=@ud =((mod k n) 0)))\n++ toggle\n |= [a=(list\u00a0?) b=(list\u00a0?)]\n =| c=(list\u00a0?)\n |-\n \u00a0?: |(?=(~ a)\u00a0?=(~ b)) (flop c)\n $(a t.a, b t.b, c [=((mix i.a i.b) 1) c])\n--", "safe": true }, { "filename": "100 doors_327.txt", "content": "#! /bin/sh\nexec huginn --no-argv -E \"${0}\"\n#! huginn\n\nimport Algorithms as algo;\n\nmain() {\n doorCount = 100;\n doors = [].resize( doorCount, false );\n\n for ( pass\u00a0: algo.range( doorCount ) ) {\n i = 0;\n step = pass + 1;\n while ( i < doorCount ) {\n doors[i] =\u00a0! doors[i];\n i += step;\n }\n }\n\n for ( i\u00a0: algo.range( doorCount ) ) {\n if ( doors[i] ) {\n print( \"door {} is open\\n\".format( i ) );\n }\n }\n return ( 0 );\n}", "safe": true }, { "filename": "100 doors_328.txt", "content": "(setv doors (* [False] 100))\n\n(for [pass (range (len doors))]\n (for [i (range pass (len doors) (inc pass))]\n (assoc doors i (not (get doors i)))))\n\n(for [i (range (len doors))]\n (print (.format \"Door {} is {}.\"\n (inc i)\n (if (get doors i) \"open\" \"closed\"))))", "safe": true }, { "filename": "100 doors_329.txt", "content": "software {\n\tvar doors = len(100)\n\t\n\tfor pass over [1, 100]\n\t\tvar door = pass - 1\n\t\tloop door < len(doors) {\n\t\t\tdoors[door] = doors[door]/0\n\t\t\tdoor += pass\n\t\t}\n\tend\n\t\n\tfor door,isopen in doors\n\t\tif isopen\n\t\t\tprint(\"Door \",door+1,\": open\")\n\t\tend\n\tend\n\tprint(\"All other doors are closed\")\n}", "safe": true }, { "filename": "100 doors_33.txt", "content": "begin\n \ncomment - 100 doors problem in ALGOL-60;\n \nboolean array doors[1:100];\ninteger i, j;\nboolean open, closed;\n \nopen\u00a0:= true;\nclosed\u00a0:= not true;\n \noutstring(1,\"100 Doors Problem\\n\");\n \ncomment - all doors are initially closed;\nfor i\u00a0:= 1 step 1 until 100 do\n doors[i]\u00a0:= closed;\n \ncomment\n cycle through at increasing intervals\n and flip each door encountered;\nfor i\u00a0:= 1 step 1 until 100 do\n for j\u00a0:= i step i until 100 do\n doors[j]\u00a0:= not doors[j];\n \ncomment - show which doors are open;\noutstring(1,\"The open doors are:\");\nfor i\u00a0:= 1 step 1 until 100 do\n if doors[i] then\n outinteger(1,i);\n \nend\n", "safe": true }, { "filename": "100 doors_330.txt", "content": "procedure main()\n door\u00a0:= table(0) # default value of entries is 0\n every pass\u00a0:= 1 to 100 do\n every door[i\u00a0:= pass to 100 by pass]\u00a0:= 1 - door[i]\n\n every write(\"Door \", i\u00a0:= 1 to 100, \" is \", if door[i] = 1 then \"open\" else \"closed\")\nend", "safe": true }, { "filename": "100 doors_331.txt", "content": "procedure main()\n every write(\"Door \", i\u00a0:= 1 to 100, \" is \", if integer(sqrt(i)) = sqrt(i) then \"open\" else \"closed\")\nend", "safe": true }, { "filename": "100 doors_332.txt", "content": "procedure main(args)\n dMap\u00a0:= table(\"closed\")\n every dMap[(1 to sqrt(100))^2]\u00a0:= \"open\"\n every write(\"Door \",i\u00a0:= 1 to 100,\" is \",dMap[i])\nend", "safe": true }, { "filename": "100 doors_333.txt", "content": "import Data.Vect\n\n-- Creates list from 0 to n (not including n) \nupTo\u00a0: (m\u00a0: Nat) -> Vect m (Fin m)\nupTo Z = []\nupTo (S n) = 0\u00a0:: (map FS (upTo n))\n\ndata DoorState = DoorOpen | DoorClosed\n\ntoggleDoor\u00a0: DoorState -> DoorState\ntoggleDoor DoorOpen = DoorClosed\ntoggleDoor DoorClosed = DoorOpen\n\nisOpen\u00a0: DoorState -> Bool\nisOpen DoorOpen = True\nisOpen DoorClosed = False\n\ninitialDoors\u00a0: Vect 100 DoorState\ninitialDoors = fromList $ map (\\_ => DoorClosed) [1..100]\n\niterate\u00a0: (n\u00a0: Fin m) -> Vect m DoorState -> Vect m DoorState\niterate n doors {m} = \n map (\\(idx, doorState) => \n if ((S (finToNat idx)) `mod` (S (finToNat n))) == Z \n then toggleDoor doorState \n else doorState) \n (zip (upTo m) doors)\n\n-- Returns all doors left open at the end\nsolveDoors\u00a0: List (Fin 100)\nsolveDoors = \n findIndices isOpen $ foldl (\\doors,val => iterate val doors) initialDoors (upTo 100)\n\nmain\u00a0: IO ()\nmain = print $ map (\\n => S (finToNat n)) solveDoors", "safe": true }, { "filename": "100 doors_334.txt", "content": "Hallway is a room.\n\nA toggle door is a kind of thing.\nA toggle door can be open or closed. It is usually closed.\nA toggle door has a number called the door number.\nUnderstand the door number property as referring to a toggle door.\nRule for printing the name of a toggle door: say \"door #[door number]\".\n\nThere are 100 toggle doors.\n\nWhen play begins (this is the initialize doors rule):\n\tlet the next door number be 1;\n\trepeat with D running through toggle doors:\n\t\tnow the door number of D is the next door number;\n\t\tincrement the next door number.\n\nTo toggle (D - open toggle door): now D is closed.\nTo toggle (D - closed toggle door): now D is open.\n\nWhen play begins (this is the solve puzzle rule):\n\tlet the door list be the list of toggle doors;\n\tlet the door count be the number of entries in the door list;\n\trepeat with iteration running from 1 to 100:\n\t\tlet N be the iteration;\n\t\twhile N is less than the door count:\n\t\t\ttoggle entry N in the door list;\n\t\t\tincrease N by the iteration;\n\tsay \"Doors left open: [list of open toggle doors].\";\n\tend the story.", "safe": true }, { "filename": "100 doors_335.txt", "content": "MAIN\n DEFINE\n i, pass SMALLINT,\n doors ARRAY[100] OF SMALLINT\n \n FOR i = 1 TO 100\n LET doors[i] = FALSE\n END FOR\n \n FOR pass = 1 TO 100\n FOR i = pass TO 100 STEP pass\n LET doors[i] = NOT doors[i]\n END FOR\n END FOR\n \n FOR i = 1 TO 100\n IF doors[i]\n THEN DISPLAY i USING \"Door <<& is open\"\n ELSE DISPLAY i USING \"Door <<& is closed\"\n END IF\n END FOR\nEND MAIN", "safe": true }, { "filename": "100 doors_336.txt", "content": "(var doors (times 100 false))\n\n(for i (range 1 101)\n i2 (range (dec i) 100 i)\n (var! doors (set-at [i2] (! (i2 doors))))\n (continue))\n\n(-> (xmap vec doors)\n (filter 1)\n (map (comp 0 inc))\n (join \", \")\n @(str \"open doors: \"))", "safe": true }, { "filename": "100 doors_337.txt", "content": "open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100 doors_338.txt", "content": "doors\u00a0:= List clone\n100 repeat(doors append(false))\nfor(i,1,100,\n for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not))\n)\ndoors foreach(i, x, if(x, \"Door #{i + 1} is open\" interpolate println))", "safe": true }, { "filename": "100 doors_339.txt", "content": "(Range 1 to(10) asList) foreach(v, \"Door #{v ** 2} is open.\" interpolate println)", "safe": true }, { "filename": "100 doors_34.txt", "content": "100 Doors Problem\nThe open doors are: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_340.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_341.txt", "content": "NDoors = Origin mimic\n\nNDoors Toggle = Origin mimic do(\n initialize = method(toggled?, @toggled? = toggled?)\n toggle! = method(@toggled? = !toggled?. self)\n)\n\nNDoors Doors = Origin mimic do(\n initialize = method(n,\n @n = n\n @doors = {} addKeysAndValues(1..n, (1..n) map(_, NDoors Toggle mimic(false)))\n )\n numsToToggle = method(n, for(x <- (1..@n), (x\u00a0% n) zero?, x))\n toggleThese = method(nums, nums each(x, @doors[x] = @doors at(x) toggle))\n show = method(@doors filter:dict(value toggled?) keys sort println)\n)\n\n; Test code\nx = NDoors Doors mimic(100)\n(1..100) each(n, x toggleThese(x numsToToggle(n)))\nx show", "safe": true }, { "filename": "100 doors_342.txt", "content": "theory Scratch\n imports Main\nbegin\n\nsection\u2039100 Doors\u203a\n\n datatype doorstate = Open | Closed\n \n fun toggle\u00a0:: \"doorstate \u21d2 doorstate\" where\n \"toggle Open = Closed\"\n | \"toggle Closed = Open\"\n \n fun walk\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"walk f _ _ [] = []\"\n | \"walk f every 0 (x#xs) = (f x) # walk f every every xs\"\n | \"walk f every (Suc n) (x#xs) = x # walk f every n xs\"\n \n text\u2039Example: \\<^const>\u2039toggle\u203a every second door. (second = 1, because of 0 indexing)\u203a\n lemma \"walk toggle 1 1 [Open, Open, Open, Open, Open, Open] =\n [Open, Closed, Open, Closed, Open, Closed]\" by code_simp\n \n text\u2039Example: \\<^const>\u2039toggle\u203a every third door.\u203a\n lemma \"walk toggle 2 2 [Open, Open, Open, Open, Open, Open] =\n [Open, Open, Closed, Open, Open, Closed]\" by code_simp\n \n text\u2039Walking each door is essentially the same as the common \\<^const>\u2039map\u203a function.\u203a\n lemma \"walk f 0 0 xs = map f xs\"\n by(induction xs) (simp)+\n \n lemma walk_beginning:\n \"walk f every n xs = (walk f every n (take (Suc n) xs)) @ (walk f every every (drop (Suc n) xs))\"\n by(induction f every n xs rule:walk.induct) (simp)+\n \n text\u2039A convenience definition to take the off-by-one into account and setting the starting position.\u203a\n definition visit_every\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"visit_every f every xs \u2261 walk f (every - 1) (every - 1) xs\"\n \n \n fun iterate\u00a0:: \"nat \u21d2 (nat \u21d2 'a \u21d2 'a) \u21d2 nat \u21d2 'a \u21d2 'a\" where\n \"iterate 0 _ _ a = a\"\n | \"iterate (Suc i) f n a = iterate i f (Suc n) (f n a)\"\n \n text\u2039The 100 doors problem.\u203a\n definition \"onehundred_doors \u2261 iterate 100 (visit_every toggle) 1 (replicate 100 Closed)\"\n \n lemma \"onehundred_doors =\n [Open, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Open, Closed, Closed, Closed, Closed, Closed,\n Closed, Open, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Open, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Open,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Open, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Open]\" by code_simp\n \n text\u2039Filtering for the open doors, we get the same result as the Haskell implementation.\u203a\n lemma\n \"[(i, door) \u2190 enumerate 1 onehundred_doors. door = Open] =\n [(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]\"\n by code_simp\n\nsection\u2039Equivalence to Haskell Implementation\u203a\ntext\u2039\nWe will now present an alternative implementation, which is similar to the Haskell implementation\non \ud83c\udf10\u2039https://rosettacode.org/wiki/100_doors#Haskell\u203a. We will prove, that the two behave the same;\nin general, not just for a fixed set of 100 doors.\n\u203a\n\n definition map_every_start\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"map_every_start f every start xs \u2261\n map (\u03bb(i, x). if i mod every = 0 then f x else x) (enumerate start xs)\"\n\n definition visit_every_alt\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"visit_every_alt f every xs \u2261 map_every_start f every 1 xs\"\n \n text\u2039Essentially, \\<^term>\u2039start\u203a and \\<^term>\u2039start mod every\u203a behave the same.\u203a\n lemma map_every_start_cycle:\n \"map_every_start f every (start + k*every) xs = map_every_start f every start xs\"\n proof(induction xs arbitrary: start)\n case Nil\n show \"map_every_start f every (start + k * every) [] = map_every_start f every start []\"\n by(simp add: map_every_start_def)\n next\n case (Cons x xs)\n from Cons.IH[of \"Suc start\"]\n show \"map_every_start f every (start + k * every) (x # xs) =\n map_every_start f every start (x # xs)\"\n by(simp add: map_every_start_def)\n qed\n corollary map_every_start_cycle_zero:\n \"map_every_start f every every xs = map_every_start f every 0 xs\"\n using map_every_start_cycle[where k=1 and start=0, simplified] by blast\n \n lemma map_every_start_fst_zero:\n \"map_every_start f every 0 (x # xs) = f x # map_every_start f every (Suc 0) xs\"\n by(simp add: map_every_start_def)\n \n text\u2039\n The first \\<^term>\u2039n\u203a elements are not processed by \\<^term>\u2039f\u203a,\n as long as \\<^term>\u2039n\u203a is less than the \\<^term>\u2039every\u203a cycle.\n \u00a0\u203a\n lemma map_every_start_skip_first: \"Suc n < every \u27f9\n map_every_start f every (every - (Suc n)) (x # xs) = \n x # map_every_start f every (every - n) xs\"\n by(simp add: map_every_start_def Suc_diff_Suc)\n\n lemma map_every_start_append:\n \"map_every_start f n s (ds1 @ ds2) =\n map_every_start f n s ds1 @ map_every_start f n (s + length ds1) ds2\"\n by(simp add: map_every_start_def enumerate_append_eq)\n\n text\u2039\n The \\<^const>\u2039walk\u203a function and \\<^const>\u2039map_every_start\u203a behave the same,\n as long as the starting \\<^term>\u2039n\u203a is less than the \\<^term>\u2039every\u203a cycle,\n because \\<^const>\u2039walk\u203a allows pushing the start arbitrarily far and\n \\<^const>\u2039map_every_start\u203a only allows deferring the start within\n the \\<^term>\u2039every\u203a cycle.\n This generalization is needed to strengthen the induction hypothesis\n for the proof.\n \u00a0\u203a\n lemma walk_eq_map_every_start:\n \"n \u2264 every \u27f9 walk f every n xs = map_every_start f (Suc every) (Suc every - n) xs\"\n proof(induction xs arbitrary: n)\n case Nil\n show \"walk f every n [] = map_every_start f (Suc every) (Suc every - n) []\"\n by(simp add: map_every_start_def)\n next\n case (Cons x xs)\n then show \"walk f every n (x # xs) = map_every_start f (Suc every) (Suc every - n) (x # xs)\"\n proof(cases n)\n case 0\n with Cons.IH show ?thesis \n by(simp add: map_every_start_cycle_zero map_every_start_fst_zero)\n next\n case (Suc n2)\n with Cons.prems map_every_start_skip_first[of n2 \"Suc every\"] have\n \"map_every_start f (Suc every) (Suc every - Suc n2) (x # xs) =\n x # map_every_start f (Suc every) (Suc every - n2) xs\"\n by fastforce\n with Suc Cons show ?thesis\n by(simp)\n qed\n qed\n \n corollary walk_eq_visit_every_alt:\n \"walk f every every xs = visit_every_alt f (Suc every) xs\"\n unfolding visit_every_alt_def\n using walk_eq_map_every_start by fastforce\n\n text\u2039\n Despite their very different implementations, our alternative visit function behaves the same\n as our original visit function.\n Text the theorem includes \\<^term>\u2039Suc every\u203a to express that we exclude \\<^term>\u2039every = 0\u203a.\n \u00a0\u203a\n theorem visit_every_eq_visit_every_alt:\n \"visit_every f (Suc every) xs = visit_every_alt f (Suc every) xs\"\n unfolding visit_every_def\n using walk_eq_visit_every_alt by fastforce\n\n text\u2039Also, the \\<^const>\u2039iterate\u203a function we implemented above can be implemented by a simple \\<^const>\u2039fold\u203a.\u203a\n lemma fold_upt_helper: assumes n_geq_1: \"Suc 0 \u2264 n\"\n shows \"fold f [Suc s..:i.100\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n ~:/ 0=|/~ >:i.100 NB. alternative\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n (*/\"1)2|>:_ q:>:i.100 NB. alternative", "safe": true }, { "filename": "100 doors_344.txt", "content": " (e. *:) 1+i.100\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n 1 (<:*:i.10)} 100$0 NB. alternative\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...", "safe": true }, { "filename": "100 doors_345.txt", "content": " 'these doors are open: ',\": I. (i.101) e. *: 1+i.10\nthese doors are open: 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_346.txt", "content": "(def doors (seq [_ :range [0 100]] false))\n\n(loop [pass :range [0 100]\n door :range [pass 100 (inc pass)]]\n (put doors door (not (doors door))))\n\n(print \"open doors: \"\u00a0;(seq [i :range [0 100] :when (doors i)] (string (inc i) \" \")))", "safe": true }, { "filename": "100 doors_347.txt", "content": "open doors: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_348.txt", "content": "class HundredDoors {\n public static void main(String[] args) {\n boolean[] doors = new boolean[101];\n\n for (int i = 1; i < doors.length; i++) {\n for (int j = i; j < doors.length; j += i) {\n doors[j] = !doors[j];\n }\n }\n\n for (int i = 1; i < doors.length; i++) {\n if (doors[i]) {\n System.out.printf(\"Door %d is open.%n\", i);\n }\n }\n }\n}", "safe": true }, { "filename": "100 doors_349.txt", "content": "import java.util.BitSet;\n\npublic class HundredDoors {\n public static void main(String[] args) {\n final int n = 100;\n var a = new BitSet(n);\n for (int i = 1; i <= n; i++) {\n for (int j = i - 1; j < n; j += i) {\n a.flip(j);\n }\n }\n a.stream().map(i -> i + 1).forEachOrdered(System.out::println);\n }\n}", "safe": true }, { "filename": "100 doors_35.txt", "content": "PROC doors = (INT limit)VOID:\n(\n MODE DOORSTATE = BOOL;\n BOOL closed = FALSE;\n BOOL open = NOT closed;\n MODE DOORLIST = [limit]DOORSTATE;\n\n DOORLIST the doors;\n FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD;\n\n FOR i FROM LWB the doors TO UPB the doors DO\n FOR j FROM LWB the doors BY i TO UPB the doors DO\n the doors[j]\u00a0:= NOT the doors[j]\n OD\n OD;\n FOR i FROM LWB the doors TO UPB the doors DO\n print((whole(i,-12),\" is \",(the doors[i]|\"opened\"|\"closed\"),newline))\n OD\n);\ndoors(100)\n", "safe": true }, { "filename": "100 doors_350.txt", "content": "class HundredDoors {\n public static void main(String[] args) {\n for (int i = 1; i <= 10; i++)\n System.out.printf(\"Door %d is open.%n\", i * i);\n }\n}", "safe": true }, { "filename": "100 doors_351.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_352.txt", "content": "import java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\nclass HundredDoors {\n public static void main(String args[]) {\n String openDoors = IntStream.rangeClosed(1, 100)\n .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i)\n .mapToObj(Integer::toString)\n .collect(Collectors.joining(\", \"));\n System.out.printf(\"Open doors: %s%n\", openDoors);\n }\n}", "safe": true }, { "filename": "100 doors_353.txt", "content": "Open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100 doors_354.txt", "content": "var doors=[];\nfor (var i=0;i<100;i++)\n doors[i]=false;\nfor (var i=1;i<=100;i++)\n for (var i2=i-1;i2<100;i2+=i)\n doors[i2]=!doors[i2];\nfor (var i=1;i<=100;i++)\n console.log(\"Door %d is %s\",i,doors[i-1]?\"open\":\"closed\")", "safe": true }, { "filename": "100 doors_355.txt", "content": "(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\u00a0% m\u00a0? x[1]\u00a0: !x[1]];\n });\n }, zip(\n lstRange,\n replicate(n, false)\n ));\n };\n function zip(xs, ys) {\n return xs.length === ys.length\u00a0? (\n xs.map(function (x, i) {\n return [x, ys[i]];\n })\n )\u00a0: 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\u00a0? n - m\u00a0: 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);", "safe": true }, { "filename": "100 doors_356.txt", "content": "for (var door = 1; door <= 100; door++) {\n var sqrt = Math.sqrt(door);\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door %d is open\", door);\n }\n}", "safe": true }, { "filename": "100 doors_357.txt", "content": "for(var door=1;i<10/*Math.sqrt(100)*/;i++){\n console.log(\"Door %d is open\",i*i);\n}", "safe": true }, { "filename": "100 doors_358.txt", "content": "(function (n) {\n \"use strict\";\n return range(1, 100)\n .filter(function (x) {\n return integerFactors(x)\n .length\u00a0% 2;\n });\n function integerFactors(n) {\n var rRoot = Math.sqrt(n),\n intRoot = Math.floor(rRoot),\n lows = range(1, intRoot)\n .filter(function (x) {\n return (n\u00a0% x) === 0;\n });\n return lows.concat(lows.map(function (x) {\n return n / x;\n })\n .reverse()\n .slice((rRoot === intRoot) | 0));\n }\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp\u00a0? n - m\u00a0: 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})(100);", "safe": true }, { "filename": "100 doors_359.txt", "content": "(function (n) {\n \"use strict\";\n return perfectSquaresUpTo(100);\n function perfectSquaresUpTo(n) {\n return range(1, Math.floor(Math.sqrt(n)))\n .map(function (x) {\n return x * x;\n });\n }\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp\u00a0? n - m\u00a0: 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})(100);", "safe": true }, { "filename": "100 doors_36.txt", "content": "PROC doors optimised = ( INT limit )VOID:\n FOR i TO limit DO\n REAL num\u00a0:= sqrt(i);\n print((whole(i,0),\" is \",(ENTIER num = num |\"opened\"|\"closed\"),newline))\n OD\n;\ndoors optimised(100)\n", "safe": true }, { "filename": "100 doors_360.txt", "content": "Array.apply(null, { length: 100 })\n .map((v, i) => i + 1)\n .forEach(door => { \n var sqrt = Math.sqrt(door); \n\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door %d is open\", door);\n } \n });", "safe": true }, { "filename": "100 doors_361.txt", "content": "// Array comprehension style\n[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { \n var door = i + 1\n var sqrt = Math.sqrt(door); \n\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door \" + door + \" is open\");\n } \n});", "safe": true }, { "filename": "100 doors_362.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100 doors_363.txt", "content": "(function (n) {\n \n \n // ONLY PERFECT SQUARES HAVE AN ODD NUMBER OF INTEGER FACTORS\n // (Leaving the door open at the end of the process) \n \n return perfectSquaresUpTo(n);\n \n \n // perfectSquaresUpTo\u00a0:: Int -> [Int]\n function perfectSquaresUpTo(n) {\n return range(1, Math.floor(Math.sqrt(n)))\n .map(x => x * x);\n }\n \n \n // GENERIC\n \n // range(intFrom, intTo, optional intStep)\n // Int -> Int -> Maybe Int -> [Int]\n function range(m, n, step) {\n let d = (step || 1) * (n >= m\u00a0? 1\u00a0: -1);\n \n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, (_, i) => m + (i * d));\n }\n \n})(100);", "safe": true }, { "filename": "100 doors_364.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_365.txt", "content": "\"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\u00a0? closed\u00a0: 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\u00a0? 'opened'\u00a0: '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.\";", "safe": true }, { "filename": "100 doors_366.txt", "content": "# Solution for n doors:\ndef doors(n):\n\n def print:\n . as $doors\n | range(1; length+1)\n | if $doors[.] then \"Door \\(.) is open\" else empty end;\n\n [range(n+1)|null] as $doors\n | reduce range(1; n+1) as $run\n ( $doors; reduce range($run; n+1; $run ) as $door\n ( .; .[$door] = (.[$door] | not) ) )\n | print\u00a0;", "safe": true }, { "filename": "100 doors_367.txt", "content": "# Solution for 100 doors:\ndef solution:\n range(1;11) | \"Door \\(. * .) is open\";", "safe": true }, { "filename": "100 doors_368.txt", "content": "doors = falses(100)\nfor a in 1:100, b in a:a:100\n doors[b] = !doors[b]\nend\nfor a = 1:100\n println(\"Door $a is \" * (doors[a]\u00a0? \"open.\"\u00a0: \"closed.\")) \nend", "safe": true }, { "filename": "100 doors_369.txt", "content": "for i in 1:10 println(\"Door $(i^2) is open.\") end", "safe": true }, { "filename": "100 doors_37.txt", "content": "begin\n % find the first few squares via the unoptimised door flipping method \u00a0%\n \n integer doorMax;\n doorMax\u00a0:= 100;\n \n begin\n % need to start a new block so the array can have variable bounds \u00a0%\n \n % array of doors - door( i ) is true if open, false if closed \u00a0%\n logical array door( 1\u00a0:: doorMax );\n \n % set all doors to closed \u00a0%\n for i\u00a0:= 1 until doorMax do door( i )\u00a0:= false;\n \n % repeatedly flip the doors \u00a0%\n for i\u00a0:= 1 until doorMax\n do begin\n for j\u00a0:= i step i until doorMax\n do begin\n door( j )\u00a0:= not door( j )\n end\n end;\n \n % display the results \u00a0%\n i_w\u00a0:= 1; % set integer field width \u00a0%\n s_w\u00a0:= 1; % and separator width \u00a0%\n for i\u00a0:= 1 until doorMax do if door( i ) then writeon( i )\n \n end\n \nend.\n", "safe": true }, { "filename": "100 doors_370.txt", "content": " doors:{`closed`open![;2]@#:'1_=,/&:'0=t!\\:/:t:!101}", "safe": true }, { "filename": "100 doors_371.txt", "content": " (1+!10)^2\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_372.txt", "content": " {(1+!_ x^%2)^2}100\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_373.txt", "content": "include ..\\Utilitys.tlhy\n\n%n 100 !n\n0 $n repeat\n\n$n [dup sqrt int dup * over\n== ( [1 swap set] [drop] ) if] for\n\n$n [ ( \"The door \" over \" is \" ) lprint get ( [\"OPEN\"] [\"closed\"] ) if print nl] for\n\n( \"Time elapsed: \" msec \" seconds\" ) lprint nl\n\npstack\n\" \" input", "safe": true }, { "filename": "100 doors_374.txt", "content": "flip::{,/{(1-*x),1_x}'x:#y}\ni::0;(100{i::i+1;flip(i;x)}:*100:^0)?1", "safe": true }, { "filename": "100 doors_375.txt", "content": "(1+!9)^2", "safe": true }, { "filename": "100 doors_376.txt", "content": "type state\n Open\n Closed\n\nfun toggle(self: state): state\n match self\n Open -> Closed\n Closed -> Open\n\ninline extern unsafe-assign\u00a0: forall ( v\u00a0: vector, i\u00a0: ssize_t, x\u00a0: a ) -> total ()\n c \"kk_vector_unsafe_assign\"\n\nfun main()\n val doors = vector(100, Closed)\n for(0,99) fn(pass)\n var door\u00a0:= pass\n while { door < 99 }\n doors.unsafe-assign(door.ssize_t, doors[door].toggle)\n door\u00a0:= door + (pass+1)\n doors.foreach-indexed fn(idx, it)\n match it\n Open -> println(\"door \" ++ (idx + 1).show ++ \" is open\")\n Closed -> println(\"door \" ++ (idx + 1).show ++ \" is closed\")", "safe": true }, { "filename": "100 doors_377.txt", "content": "fun main()\n val doors = list(0,99,1,fn(i) Closed)\n val transformed = list(1,99).foldl(doors) fn(drs, pass)\n drs.map-indexed fn(i, door)\n if ((i + 1)\u00a0% pass) == 0 then door.toggle else door\n transformed.foreach-indexed fn(idx, it)\n match it\n Open -> println(\"door \" ++ (idx + 1).show ++ \" is open\")\n Closed -> println(\"door \" ++ (idx + 1).show ++ \" is closed\")", "safe": true }, { "filename": "100 doors_378.txt", "content": "fun oneHundredDoors(): List {\n val doors = BooleanArray(100) { false }\n\n repeat(doors.size) { i ->\n for (j in i until doors.size step (i + 1)) {\n doors[j] = !doors[j]\n }\n }\n\n return doors\n .foldIndexed(emptyList()) { i, acc, door ->\n if (door) acc + (i + 1) else acc\n }\n}", "safe": true }, { "filename": "100 doors_379.txt", "content": "range InitialDoor from 1 to 100 step 1\n| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)\n| mvexpand DoorVisited=DoorsVisited to typeof(int)\n| summarize VisitCount=count() by DoorVisited\n| project Door=DoorVisited, IsOpen=(VisitCount\u00a0% 2) == 1", "safe": true }, { "filename": "100 doors_38.txt", "content": " 1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100 doors_380.txt", "content": "1) unoptimized version\n\n{def doors\n {A.new\n {S.map {lambda {} false} {S.serie 1 100}}}}\n-> doors\n\n{def toggle\n {lambda {:i :a}\n {let { {_ {A.set! :i {not {A.get :i :a}} :a} }}}}}\n-> toggle\n\n{S.map {lambda {:b} \n {S.map {lambda {:i} {toggle :i {doors}}} \n {S.serie :b 99 {+ :b 1}}}}\n {S.serie 0 99}} \n->\n\n{S.replace \\s by space in \n {S.map {lambda {:i} {if {A.get :i {doors}} then {+ :i 1} else}} \n {S.serie 0 99}}}\n\n-> 1 4 9 16 25 36 49 64 81 100\n\n2.2) optimized version\n\n{S.replace \\s by space in \n {S.map {lambda {:i}\n {let { {:root {sqrt :i}} } \n {if {= :root {round :root}} \n then {* :root :root}\n else}}}\n {S.serie 1 100}}}\n\n-> 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_381.txt", "content": "&doors = fn.arrayGenerateFrom(fn.inc, 100)\nfp.mapper = ($i) -> {\n\t$n\n\t$open = 0\n\trepeat($[n], 100) {\n\t\t$open $= $i\u00a0% +|$n?!$open:$open\n\t}\n\t\n\treturn $open\n}\nfn.arrayMap(&doors, fp.mapper)\n\nfn.print(Open doors:)\n$i\nrepeat($[i], @&doors) {\n\tif(&doors[$i]) {\n\t\tfn.printf(\\s%03d, parser.op(+|$i))\n\t}\n}\nfn.println()", "safe": true }, { "filename": "100 doors_382.txt", "content": "Open doors: 001 004 009 016 025 036 049 064 081 100\n", "safe": true }, { "filename": "100 doors_383.txt", "content": "var doors = [false] * 100\n\nfor i of doors {\n for j = i; j <= len(doors); j += i {\n doors[j] = not doors[j]\n }\n}\n\nwriteln for[=[]] i of doors { if doors[i]: _for = more(_for, i) }", "safe": true }, { "filename": "100 doors_384.txt", "content": "writeln foldfrom(fn a, b, c: if(b: a~[c]; a), [], doors, series(1..len(doors)))", "safe": true }, { "filename": "100 doors_385.txt", "content": "writeln map(fn{^2}, 1..10)", "safe": true }, { "filename": "100 doors_386.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_387.txt", "content": "loop(100) => {^\n\tlocal(root = math_sqrt(loop_count))\n\tlocal(state = (#root == math_ceil(#root)\u00a0? 'open' | 'closed'))\n\t#state\u00a0!= 'closed'\u00a0? 'Door ' + loop_count + ': ' + #state + '
'\n^}", "safe": true }, { "filename": "100 doors_388.txt", "content": "Door 1: open\nDoor 4: open\nDoor 9: open\nDoor 16: open\nDoor 25: open\nDoor 36: open\nDoor 49: open\nDoor 64: open\nDoor 81: open\nDoor 100: open", "safe": true }, { "filename": "100 doors_389.txt", "content": "use 'format importAllSigils.\n\ndoors\u00a0:= Object clone.\ndoors missing\u00a0:= { False. }.\ndoors check\u00a0:= {\n self slot ($1 ordinal).\n}.\ndoors toggle\u00a0:= {\n self slot ($1 ordinal) = self slot ($1 ordinal) not.\n}.\n1 upto 101 do {\n takes '[i].\n local 'j = i.\n while { j <= 100. } do {\n doors toggle (j).\n j = j + i.\n }.\n}.\n$stdout printf: ~fmt \"The open doors are: ~A\", 1 upto 101 filter { doors check. } to (Array).", "safe": true }, { "filename": "100 doors_39.txt", "content": "BEGIN\n\nINTEGER ARRAY DOORS[1:100];\nINTEGER I, J, OPEN, CLOSED;\n\nOPEN\u00a0:= 1;\nCLOSED\u00a0:= 0;\n\n% ALL DOORS ARE INITIALLY CLOSED\u00a0%\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n DOORS[I]\u00a0:= CLOSED;\n END;\n\n% PASS THROUGH AT INCREASING INTERVALS AND FLIP\u00a0%\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n FOR J\u00a0:= I STEP I UNTIL 100 DO\n BEGIN\n DOORS[J]\u00a0:= 1 - DOORS[J];\n END;\n END;\n\n% SHOW RESULTS\u00a0%\nWRITE(\"THE OPEN DOORS ARE:\");\nWRITE(\"\");\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n IF DOORS[I] = OPEN THEN\n WRITEON(I);\n END;\n\nEND", "safe": true }, { "filename": "100 doors_390.txt", "content": "to doors\n\t;Problem 100 Doors \n\t;Lhogho\n\n\tfor \"p [1 100] \n\t[\n\t\tmake :p \"false\n\t]\n\n\tfor \"a [1 100 1]\n\t[\n\t\tfor \"b [:a 100 :a]\n\t\t[\n\t\t\tif :b < 101 \n\t\t\t[\n\t\t\t\tmake :b not thing :b\n\t\t\t]\n\t\t]\n\t]\n\n\tfor \"c [1 100]\n\t[\n\t\tif thing :c \n\t\t[ \n\t\t\t(print \"door :c \"is \"open) \n\t\t]\n\t] \nend\n\ndoors", "safe": true }, { "filename": "100 doors_391.txt", "content": "dim doors(100)\nfor pass = 1 to 100\n for door = pass to 100 step pass\n doors(door) = not(doors(door))\n next door\nnext pass\nprint \"open doors \";\nfor door = 1 to 100\n if doors(door) then print door;\" \";\nnext door", "safe": true }, { "filename": "100 doors_392.txt", "content": "var doors = List.fill(100, false)\n\nfor i in 0...99:\n for j in i...99 by i + 1:\n doors[j] = !doors[j]\n\n# The type must be specified since the list starts off empty.\nvar open_doors: List[Integer] = []\n\ndoors.each_index{|i|\n if doors[i]:\n open_doors.push(i + 1)\n}\n\nprint($\"Open doors: ^(open_doors)\")", "safe": true }, { "filename": "100 doors_393.txt", "content": "Open doors: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_394.txt", "content": "on mouseUp \n repeat with tStep = 1 to 100\n repeat with tDoor = tStep to 100 step tStep\n put not tDoors[tDoor] into tDoors[tDoor]\n end repeat\n if tDoors[tStep] then put \"Door \" & tStep & \" is open\" & cr after tList\n end repeat\n set the text of field \"Doors\" to tList\nend mouseUp", "safe": true }, { "filename": "100 doors_395.txt", "content": "to doors\n;Problem 100 Doors \n;FMSLogo\n;lrcvs 2010\n\nmake \"door (vector 100 1) \nfor [p 1 100][setitem :p :door 0] \n \nfor [a 1 100 1][for [b :a 100 :a][make \"x item :b :door \n\t ifelse :x = 0 [setitem :b :door 1][setitem :b :door 0] ] ] \n \nfor [c 1 100][make \"y item :c :door \n\t ifelse :y = 0 [pr (list :c \"Close)] [pr (list :c \"Open)] ] \nend", "safe": true }, { "filename": "100 doors_396.txt", "content": "HAI 1.3\n\nI HAS A doors ITZ A BUKKIT\nIM IN YR hallway UPPIN YR door TIL BOTH SAEM door AN 100\n doors HAS A SRS door ITZ FAIL BTW, INISHULIZE ALL TEH DOORZ AS CLOZD\nIM OUTTA YR hallway\n\nIM IN YR hallway UPPIN YR pass TIL BOTH SAEM pass AN 100\n I HAS A door ITZ pass\n IM IN YR passer\n doors'Z SRS door R NOT doors'Z SRS door\n door R SUM OF door AN SUM OF pass AN 1\n DIFFRINT door AN SMALLR OF door AN 99, O RLY?\n YA RLY, GTFO\n OIC\n IM OUTTA YR passer\nIM OUTTA YR hallway\n\nIM IN YR printer UPPIN YR door TIL BOTH SAEM door AN 100\n VISIBLE \"Door #\" SUM OF door AN 1 \" is \"!\n doors'Z SRS door, O RLY?\n YA RLY, VISIBLE \"open.\"\n NO WAI, VISIBLE \"closed.\"\n OIC\nIM OUTTA YR printer\n\nKTHXBYE", "safe": true }, { "filename": "100 doors_397.txt", "content": "local is_open = {}\n\nfor pass = 1,100 do\n for door = pass,100,pass do\n is_open[door] = not is_open[door]\n end\nend\n\nfor i,v in next,is_open do\n print ('Door '..i..':',v and 'open' or 'close')\nend", "safe": true }, { "filename": "100 doors_398.txt", "content": "Module Doors100 {\n Dim Doors(1 to 100)\n For i=1 to 100\n For j=i to 100 step i\n Doors(j)~\n Next j\n Next i\n DispAll()\n ' optimization\n Dim Doors(1 to 100)=False\n For i=1 to 10\n Doors(i**2)=True\n Next i\n Print\n DispAll()\n Sub DispAll()\n Local i\n For i=1 to 100\n if Doors(i) then print i,\n Next i\n Print\n End Sub\n}\nDoors100", "safe": true }, { "filename": "100 doors_399.txt", "content": "define(`_set', `define(`$1[$2]', `$3')')dnl\ndefine(`_get', `defn(`$1[$2]')')dnl\ndefine(`for',`ifelse($#,0,``$0'',`ifelse(eval($2<=$3),1,\n`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl\ndefine(`opposite',`_set(`door',$1,ifelse(_get(`door',$1),`closed',`open',`closed'))')dnl\ndefine(`upper',`100')dnl\nfor(`x',`1',upper,`1',`_set(`door',x,`closed')')dnl\nfor(`x',`1',upper,`1',`for(`y',x,upper,x,`opposite(y)')')dnl\nfor(`x',`1',upper,`1',`door x is _get(`door',x)\n')dnl", "safe": true }, { "filename": "100 doors_4.txt", "content": "@echo off\nset doors=%@repeat[C,100]\ndo step = 1 to 100\n do door = %step to 100 by %step\n set doors=%@left[%@eval[%door-1],%doors]%@if[%@instr[%@eval[%door-1],1,%doors]==C,O,C]%@right[%@eval[100-%door],%doors]\n enddo\nenddo", "safe": true }, { "filename": "100 doors_40.txt", "content": "THE OPEN DOORS ARE:\n 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_400.txt", "content": " .TITLE DOORS\n .MCALL .TTYOUT,.EXIT\nNDOORS = ^D100\nDOORS::\n \u00a0; CLOSE ALL DOORS\n MOV #DOORBF+1,R0\nCLOSE: CLR (R0)+\n CMP R0,#BUFTOP\n BLT CLOSE\n\n \u00a0; VISIT DOORS\n MOV #1,R1 \u00a0; R1 = PASS\nPASS: MOV R1,R2 \u00a0; R2 = DOOR\nDOOR: COMB DOORBF(R2) \u00a0; VISIT DOOR\n ADD R1,R2\n CMP R2,#NDOORS \u00a0; NEXT DOOR\n BLE DOOR\n INC R1\n CMP R1,R2 \u00a0; NEXT PASS\n BLE PASS\n\n \u00a0; DISPLAY DOORS AS ASCII 0 OR 1\n MOV #DOORBF+1,R1\nDISP: MOVB (R1)+,R0\n BICB #^C1,R0\n BISB #^D48,R0\n .TTYOUT\n CMP R1,#BUFTOP\n BLT DISP\n\n .EXIT\nDOORBF: .BLKB NDOORS+1\nBUFTOP = .\n .END DOORS", "safe": true }, { "filename": "100 doors_401.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100 doors_402.txt", "content": " NORMAL MODE IS INTEGER\n DIMENSION OPEN(100)\n PRINT COMMENT $ $\n \n R MAKE SURE ALL DOORS ARE CLOSED AT BEGINNING\n THROUGH CLOSE, FOR DOOR=1, 1, DOOR.G.100\nCLOSE OPEN(DOOR) = 0\n\n R MAKE 100 PASSES\n THROUGH TOGGLE, FOR PASS=1, 1, PASS.G.100\n THROUGH TOGGLE, FOR DOOR=PASS, PASS, DOOR.G.100\nTOGGLE OPEN(DOOR) = 1 - OPEN(DOOR) \n\n R PRINT THE DOORS THAT ARE OPEN\n THROUGH SHOW, FOR DOOR=1, 1, DOOR.G.100\nSHOW WHENEVER OPEN(DOOR).E.1, PRINT FORMAT ISOPEN, DOOR\n \n VECTOR VALUES ISOPEN = $5HDOOR ,I3,S1,8HIS OPEN.*$ \n END OF PROGRAM", "safe": true }, { "filename": "100 doors_403.txt", "content": "DOOR 1 IS OPEN.\nDOOR 4 IS OPEN.\nDOOR 9 IS OPEN.\nDOOR 16 IS OPEN.\nDOOR 25 IS OPEN.\nDOOR 36 IS OPEN.\nDOOR 49 IS OPEN.\nDOOR 64 IS OPEN.\nDOOR 81 IS OPEN.\nDOOR 100 IS OPEN.", "safe": true }, { "filename": "100 doors_404.txt", "content": ".DEFAULT_GOAL:=100\ndigit=1 2 3 4 5 6 7 8 9\ndoors:=$(digit) $(foreach i,$(digit),$(foreach j,0 $(digit),$i$j)) 100\n$(doors):;@: $(if $(filter %1 %3 %5 %7 %9,$(words $^)),$(info $@))\n$(foreach i,$(doors),$(eval $i: $(word $i,0 $(doors))))\n0 $(addprefix pass,$(doors)):\npass:=X\ndep=$(eval count+=$(pass))$(eval $(words $(count)):pass$(words $(pass)))\nloop=$(foreach inner,$(doors),$(if $(word 101,$(count)),,$(dep)))\n$(foreach outer,$(doors),$(eval pass+=X)$(eval count:=)$(loop))", "safe": true }, { "filename": "100 doors_405.txt", "content": "NDoors\u00a0:= proc( N\u00a0:: posint )\n # Initialise, using 0 to represent \"closed\"\n local pass, door, doors\u00a0:= Array( 1 .. N, 'datatype' = 'integer'[ 1 ] );\n # Now do N passes\n for pass from 1 to N do\n for door from pass by pass while door <= N do\n doors[ door ]\u00a0:= 1 - doors[ door ]\n end do\n end do;\n # Output\n for door from 1 to N do\n printf( \"Door %d is %s.\\n\", door, `if`( doors[ door ] = 0, \"closed\", \"open\" ) )\n end do;\n # Since this is a printing routine, return nothing.\n NULL\nend proc:", "safe": true }, { "filename": "100 doors_406.txt", "content": "> NDoors( 100 );", "safe": true }, { "filename": "100 doors_407.txt", "content": "> seq( i^2, i = 1 .. isqrt( 100 ) );\n 1, 4, 9, 16, 25, 36, 49, 64, 81, 100", "safe": true }, { "filename": "100 doors_408.txt", "content": "> [seq]( 1 .. 10 )^~2;\n [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_409.txt", "content": "n=100;\ntmp=ConstantArray[-1,n];\nDo[tmp[[i;;;;i]]*=-1;,{i,n}];\nDo[Print[\"door \",i,\" is \",If[tmp[[i]]==-1,\"closed\",\"open\"]],{i,1,Length[tmp]}]", "safe": true }, { "filename": "100 doors_41.txt", "content": "PROC main()\n DEF t[100]: ARRAY,\n pass, door\n FOR door\u00a0:= 0 TO 99 DO t[door]\u00a0:= FALSE\n FOR pass\u00a0:= 0 TO 99\n door\u00a0:= pass\n WHILE door <= 99\n t[door]\u00a0:= Not(t[door])\n door\u00a0:= door + pass + 1\n ENDWHILE\n ENDFOR\n FOR door\u00a0:= 0 TO 99 DO WriteF('\\d is \\s\\n', door+1,\n IF t[door] THEN 'open' ELSE 'closed')\nENDPROC", "safe": true }, { "filename": "100 doors_410.txt", "content": "f[n_] = \"Closed\"; \nDo[Do[If[f[n] == \"Closed\", f[n] = \"Open\", f[n] = \"Closed\"], {n, k, 100, k}], {k, 1, 100}]; \nTable[f[n], {n, 1, 100}]", "safe": true }, { "filename": "100 doors_411.txt", "content": "Fold[\n ReplacePart[#1, (i_ /; Mod[i, #2] == 0)\u00a0:> (-#1[[i]])] &,\n ConstantArray[-1, {100}],\n Range[100]\n] /. {1 -> \"Open\", -1 -> \"Closed\"}", "safe": true }, { "filename": "100 doors_412.txt", "content": "Do[Print[\"door \",i,\" is \",If[IntegerQ[Sqrt[i]],\"open\",\"closed\"]],{i,100}]", "safe": true }, { "filename": "100 doors_413.txt", "content": "n=100;\na=Range[1,Sqrt[n]]^2\nDo[Print[\"door \",i,\" is \",If[MemberQ[a,i],\"open\",\"closed\"]],{i,100}]", "safe": true }, { "filename": "100 doors_414.txt", "content": "n=100\nnn=1\na=0\nFor[i=1,i<=n,i++,\n If[i==nn,\n Print[\"door \",i,\" is open\"];\n a++;\n nn+=2a+1;\n ,\n Print[\"door \",i,\" is closed\"];\n ];\n]", "safe": true }, { "filename": "100 doors_415.txt", "content": "Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]]", "safe": true }, { "filename": "100 doors_416.txt", "content": "Range[Sqrt[100]]^2", "safe": true }, { "filename": "100 doors_417.txt", "content": "a = false(1,100);\nfor b=1:100\n for i = b:b:100\n a(i) = ~a(i);\n end\nend\na", "safe": true }, { "filename": "100 doors_418.txt", "content": "for x=1:100;\n if sqrt(x) == floor(sqrt(x))\n a(i)=1;\n end\nend\na", "safe": true }, { "filename": "100 doors_419.txt", "content": "doors = zeros(1,100); // 0: closed 1: open\nfor i = 1:100\n doors(i:i:100) = 1-doors(i:i:100)\nend\ndoors", "safe": true }, { "filename": "100 doors_42.txt", "content": "doors\u2190{100\u2374((\u2375-1)\u23740),1}\n\u2260\u233f\u2283doors\u00a8 \u2373100\n", "safe": true }, { "filename": "100 doors_420.txt", "content": "a = zeros(100,1);\nfor counter = 1:sqrt(100);\n a(counter^2) = 1;\nend\na", "safe": true }, { "filename": "100 doors_421.txt", "content": "function [doors,opened,closed] = hundredDoors()\n\n %Initialize the doors, make them booleans for easy vectorization\n doors = logical( (1:1:100) );\n \n %Go through the flipping process, ignore the 1 case because the doors\n %array is already initialized to all open\n for initialPosition = (2:100)\n doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) );\n end\n \n opened = find(doors); %Stores the numbers of the open doors\n closed = find( not(doors) ); %Stores the numbers of the closed doors\n \nend", "safe": true }, { "filename": "100 doors_422.txt", "content": "doors((1:10).^2) = 1;\n\ndoors", "safe": true }, { "filename": "100 doors_423.txt", "content": "doors(n)\u00a0:= block([v], local(v),\n v: makelist(true, n),\n for i: 2 thru n do\n for j: i step i thru n do v[j]: not v[j],\n sublist_indices(v, 'identity));", "safe": true }, { "filename": "100 doors_424.txt", "content": "doors(100);\n/* [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] */", "safe": true }, { "filename": "100 doors_425.txt", "content": "doorsOpen = for i in 1 to 100 collect false\n\nfor pass in 1 to 100 do\n(\n for door in pass to 100 by pass do\n (\n doorsOpen[door] = not doorsOpen[door]\n )\n)\n\nfor i in 1 to doorsOpen.count do\n(\n format (\"Door\u00a0% is open?:\u00a0%\\n\") i doorsOpen[i]\n)", "safe": true }, { "filename": "100 doors_426.txt", "content": "for i in 1 to 100 do\n(\n root = pow i 0.5\n format (\"Door\u00a0% is open?:\u00a0%\\n\") i (root == (root as integer))\n)", "safe": true }, { "filename": "100 doors_427.txt", "content": ":- module doors.\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n:- implementation.\n:- import_module bitmap, bool, list, string, int.\n\n:- func doors = bitmap.\ndoors = bitmap.init(100, no).\n\n:- pred walk(int, bitmap, bitmap).\n:- mode walk(in, bitmap_di, bitmap_uo) is det.\nwalk(Pass, !Doors)\u00a0:-\n walk(Pass, Pass, !Doors).\n\n:- pred walk(int, int, bitmap, bitmap).\n:- mode walk(in, in, bitmap_di, bitmap_uo) is det.\nwalk(At, By, !Doors)\u00a0:-\n ( if bitmap.in_range(!.Doors, At - 1) then\n bitmap.unsafe_flip(At - 1, !Doors),\n walk(At + By, By, !Doors)\n else\n true\n ).\n\n:- pred report(bitmap, int, io, io).\n:- mode report(bitmap_di, in, di, uo) is det.\nreport(Doors, N, !IO)\u00a0:-\n ( if is_set(Doors, N - 1) then\n State = \"open\"\n else\n State = \"closed\"\n ),\n io.format(\"door #%d is %s\\n\",\n [i(N), s(State)], !IO).\n\nmain(!IO)\u00a0:-\n list.foldl(walk, 1 .. 100, doors, Doors),\n list.foldl(report(Doors), 1 .. 100, !IO).", "safe": true }, { "filename": "100 doors_428.txt", "content": "boolean doors[];\nfor i = 1 upto 100: doors[i]\u00a0:= false; endfor\nfor i = 1 upto 100:\n for j = 1 step i until 100:\n doors[j]\u00a0:= not doors[j];\n endfor\nendfor\nfor i = 1 upto 100:\n message decimal(i) & \" \" & if doors[i]: \"open\" else: \"close\" fi;\nendfor\nend", "safe": true }, { "filename": "100 doors_429.txt", "content": "For offset = 1 To 100\n For i = 0 To 100 Step offset\n a[i] = a[i] + 1\n EndFor\nEndFor\n' Print \"opened\" doors\nFor i = 1 To 100\n If math.Remainder(a[i], 2) = 1 Then \n TextWindow.WriteLine(i)\n EndIf \nEndFor", "safe": true }, { "filename": "100 doors_43.txt", "content": "2|+/[1]0=D\u2218.|D\u2190\u2373100\n", "safe": true }, { "filename": "100 doors_430.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100 doors_431.txt", "content": "d = {}\nfor p in range(1, 100)\n for t in range(p, 100, p)\n if d.hasIndex(t) then d.remove t else d.push t\n end for\nend for\n\nprint d.indexes.sort", "safe": true }, { "filename": "100 doors_432.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100 doors_433.txt", "content": "d = [false] * 101\nopen = []\nfor p in range(1, 100)\n for t in range(p, 100, p)\n d[t] = not d[t]\n end for\n if d[p] then open.push p\nend for\n\nprint open", "safe": true }, { "filename": "100 doors_434.txt", "content": ".data\n doors: .space 100\n num_str: .asciiz \"Number \"\n comma_gap: .asciiz \" is \"\n newline: .asciiz \"\\n\"\n\n.text\nmain:\n# Clear all the cells to zero\n li $t1, 100\n la $t2, doors\nclear_loop:\n sb $0, ($t2)\n add $t2, $t2, 1\n sub $t1, $t1, 1\n bnez $t1, clear_loop\n\n# Now start the loops\n li $t0, 1 # This will the the step size\n li $t4, 1 # just an arbitrary 1\nloop1:\n move $t1, $t0 # Counter\n la $t2, doors # Current pointer\n add $t2, $t2, $t0\n addi $t2, $t2, -1\nloop2:\n lb $t3, ($t2)\n sub $t3, $t4, $t3\n sb $t3, ($t2)\n add $t1, $t1, $t0\n add $t2, $t2, $t0\n ble $t1, 100, loop2\n\n addi $t0, $t0, 1\n ble $t0, 100, loop1\n\n # Now display everything\n la $t0, doors\n li $t1, 1\nloop3:\n li $v0, 4\n la $a0, num_str\n syscall\n \n li $v0, 1\n move $a0, $t1\n syscall\n\n li $v0, 4\n la $a0, comma_gap\n syscall\n\n li $v0, 1\n lb $a0, ($t0)\n syscall\n\n li $v0, 4,\n la $a0, newline\n syscall\n\n addi $t0, $t0, 1\n addi $t1, $t1, 1\n bne $t1, 101 loop3", "safe": true }, { "filename": "100 doors_435.txt", "content": "import java.util.ArrayList\n\nclass Door\n\t:state\n\n\tdef initialize\n\t\t@state=false\n\tend\n \n\tdef closed?;\u00a0!@state; end\n\tdef open?; @state; end\n\n\tdef close; @state=false; end\n\tdef open; @state=true; end\n \n\tdef toggle\n\t\tif closed?\n\t\t\topen\n\t\telse\n\t\t\tclose\n\t\tend\n\tend\n \n\tdef toString; Boolean.toString(@state); end\nend\n \ndoors=ArrayList.new\n1.upto(100) do\n doors.add(Door.new)\nend \n\n1.upto(100) do |multiplier|\n index = 0\n doors.each do |door|\n Door(door).toggle if (index+1)%multiplier == 0\n index += 1\n end\nend\n\ni = 0\ndoors.each do |door| \n puts \"Door #{i+1} is #{door}.\"\n i+=1\nend", "safe": true }, { "filename": "100 doors_436.txt", "content": "main\u00a0:: [sys_message]\nmain = [Stdout (show (openDoors 100)), \n Stdout \"\\n\"] \n\nopenDoors\u00a0:: num->[num]\nopenDoors doors =\n map snd (filter fst (zip2 (doorStates doors) [1..]))\n\ndoorStates\u00a0:: num->[bool]\ndoorStates doors =\n take doors (foldr (zipWith (~=)) (repeat False) (map pass [1..doors]))\n\npass\u00a0:: num->[bool]\npass n = tl (concat (repeat (take n (True:repeat False))))\n\nzipWith f x y = map f' (zip2 x y)\n where f' (x,y) = f x y", "safe": true }, { "filename": "100 doors_437.txt", "content": "[1,4,9,16,25,36,49,64,81,100]", "safe": true }, { "filename": "100 doors_438.txt", "content": "var %d = $str(0 $+ $chr(32),100), %m = 1\nwhile (%m <= 100) {\n var %n = 1\n while ($calc(%n * %m) <= 100) {\n var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32)\n inc %n\n }\n inc %m\n}\necho -ag All Doors (Boolean): %d\nvar %n = 1\nwhile (%n <= $findtok(%d,1,0,32)) {\n var %t = %t $findtok(%d,1,%n,32)\n inc %n\n}\necho -ag Open Door Numbers: %t", "safe": true }, { "filename": "100 doors_439.txt", "content": "MCSKIP \"WITH\" NL\n\"\" 100 doors\nMCINS\u00a0%.\nMCSKIP MT,<>\n\"\" Doors represented by P1-P100, 0 is closed\nMCPVAR 100\n\"\" Set P variables to 0\nMCDEF ZEROPS WITHS NL AS \nZEROPS\n\"\" Generate door state\nMCDEF STATE WITHS () AS MCGO L0\n%L1.open>\n\"\" Main macro - no arguments\n\"\" T1 is pass number\n\"\" T2 is door number\nMCDEF DOORS WITHS NL\nAS \n\"\" Do it\nDOORS", "safe": true }, { "filename": "100 doors_44.txt", "content": "\u2260\u233f0=(\u2373100)\u2218.|\u2373100\n", "safe": true }, { "filename": "100 doors_440.txt", "content": "MODULE Doors;\nIMPORT InOut;\n\nTYPE State = (Closed, Open);\nTYPE List = ARRAY [1 .. 100] OF State;\n\nVAR\n Doors: List;\n I, J: CARDINAL;\n\nBEGIN\n FOR I\u00a0:= 1 TO 100 DO\n FOR J\u00a0:= 1 TO 100 DO\n IF J MOD I = 0 THEN\n IF Doors[J] = Closed THEN\n Doors[J]\u00a0:= Open\n ELSE\n Doors[J]\u00a0:= Closed\n END\n END\n END\n END;\n\n FOR I\u00a0:= 1 TO 100 DO\n InOut.WriteCard(I, 3);\n InOut.WriteString(' is ');\n\n IF Doors[I] = Closed THEN\n InOut.WriteString('Closed.')\n ELSE\n InOut.WriteString('Open.')\n END;\n\n InOut.WriteLn\n END\nEND Doors.", "safe": true }, { "filename": "100 doors_441.txt", "content": "MODULE DoorsOpt;\nIMPORT InOut;\n\nTYPE State = (Closed, Open);\nTYPE List = ARRAY [1 .. 100] OF State;\n\nVAR\n Doors: List;\n I: CARDINAL;\n\nBEGIN\n FOR I\u00a0:= 1 TO 10 DO\n Doors[I*I]\u00a0:= Open\n END;\n\n FOR I\u00a0:= 1 TO 100 DO\n InOut.WriteCard(I, 3);\n InOut.WriteString(' is ');\n IF Doors[I] = Closed THEN\n InOut.WriteString('Closed.')\n ELSE\n InOut.WriteString('Open.')\n END;\n InOut.WriteLn\n END\nEND DoorsOpt.", "safe": true }, { "filename": "100 doors_442.txt", "content": "MODULE Doors EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nTYPE State = {Closed, Open};\nTYPE List = ARRAY [1..100] OF State;\n\nVAR doors\u00a0:= List{State.Closed, ..};\n\nBEGIN\n FOR i\u00a0:= 1 TO 100 DO\n FOR j\u00a0:= FIRST(doors) TO LAST(doors) DO\n IF j MOD i = 0 THEN\n IF doors[j] = State.Closed THEN\n doors[j]\u00a0:= State.Open;\n ELSE\n doors[j]\u00a0:= State.Closed;\n END;\n END;\n END;\n END;\n\n FOR i\u00a0:= FIRST(doors) TO LAST(doors) DO\n IO.Put(Fmt.Int(i) & \" is \");\n IF doors[i] = State.Closed THEN\n IO.Put(\"Closed.\\n\");\n ELSE\n IO.Put(\"Open.\\n\");\n END;\n END;\nEND Doors.", "safe": true }, { "filename": "100 doors_443.txt", "content": "MODULE DoorsOpt EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nTYPE State = {Closed, Open};\nTYPE List = ARRAY [1..100] OF State;\n\nVAR doors\u00a0:= List{State.Closed, ..};\n\nBEGIN\n FOR i\u00a0:= 1 TO 10 DO\n doors[i * i]\u00a0:= State.Open;\n END;\n\n FOR i\u00a0:= FIRST(doors) TO LAST(doors) DO\n IO.Put(Fmt.Int(i) & \" is \");\n IF doors[i] = State.Closed THEN\n IO.Put(\"Closed.\\n\");\n ELSE\n IO.Put(\"Open.\\n\");\n END;\n END;\nEND DoorsOpt.", "safe": true }, { "filename": "100 doors_444.txt", "content": "101 var l .\n\nfor l 0 endfor\narr\n\n0 var i .\nfor l\n i 1 + var i var j .\n j l < var pass .\n while pass\n get j not insert j .\n j i + var j\n l < var pass . \n endwhile\nendfor\nprint /# show all doors #/\n\n/# show only open doors #/\n|| print .\n0 var i .\nfor l\n get i\n if\u00a0: i out | | out . . endif .\n i 1 + var i .\nendfor\n\ninput . /# pause until ENTER key pressed #/", "safe": true }, { "filename": "100 doors_445.txt", "content": "is_open = make(100);\nfor pass in [1..100]\n for door in [pass..100]\n if (door\u00a0% pass)\n continue;\n endif\n is_open[door] = !is_open[door];\n endfor\nendfor\n\n\"output the result\";\nfor door in [1..100]\n player:tell(\"door #\", door, \" is \", (is_open[door]\u00a0? \"open\"\u00a0: \"closed\"), \".\");\nendfor", "safe": true }, { "filename": "100 doors_446.txt", "content": "is_open = [false for door = 1,100]\n \nfor pass = 1,100 \n for door = pass,100,pass\n is_open[door] = not is_open[door]\n \nfor i,v in ipairs is_open\n print \"Door #{i}: \" .. if v then 'open' else 'closed'", "safe": true }, { "filename": "100 doors_447.txt", "content": "doors\tnew door,pass\n\tFor door=1:1:100 Set door(door)=0\n\tFor pass=1:1:100 For door=pass:pass:100 Set door(door)='door(door)\n\tFor door=1:1:100 If door(door) Write\u00a0!,\"Door\",$j(door,4),\" is open\"\n\tWrite\u00a0!,\"All other doors are closed.\"\n\tQuit\nDo doors\nDoor 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open\nAll other doors are closed.", "safe": true }, { "filename": "100 doors_448.txt", "content": "use std\n\nconst main = {\n\tvar isopen\t: bool[100]\n\n\tstd.slfill(isopen[:], false)\n\tfor var i = 0; i < isopen.len; i++\n\t\tfor var j = i; j < isopen.len; j += i + 1\n\t\t\tisopen[j] = !isopen[j]\n\t\t;;\n\t;;\n\n\tfor var i = 0; i < isopen.len; i++\n\t\tif isopen[i]\n\t\t\tstd.put(\"door {} is open\\n\", i + 1)\n\t\t;;\n\t;;\n}", "safe": true }, { "filename": "100 doors_449.txt", "content": "door 1 is open\ndoor 4 is open\ndoor 9 is open\ndoor 16 is open\ndoor 25 is open\ndoor 36 is open\ndoor 49 is open\ndoor 64 is open\ndoor 81 is open\ndoor 100 is open\n", "safe": true }, { "filename": "100 doors_45.txt", "content": "1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1", "safe": true }, { "filename": "100 doors_450.txt", "content": "DROP PROCEDURE IF EXISTS one_hundred_doors;\n\nDELIMITER |\n\nCREATE PROCEDURE one_hundred_doors (n INT)\nBEGIN\n DROP TEMPORARY TABLE IF EXISTS doors; \n CREATE TEMPORARY TABLE doors (\n id INTEGER NOT NULL,\n open BOOLEAN DEFAULT FALSE,\n PRIMARY KEY (id)\n );\n\n SET @i = 1;\n create_doors: LOOP\n INSERT INTO doors (id, open) values (@i, FALSE);\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE create_doors;\n END IF;\n END LOOP create_doors;\n\n SET @i = 1;\n toggle_doors: LOOP\n UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0;\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE toggle_doors;\n END IF;\n END LOOP toggle_doors;\n\n SELECT id FROM doors WHERE open;\nEND|\n\nDELIMITER\u00a0;\n\nCALL one_hundred_doors(100);", "safe": true }, { "filename": "100 doors_451.txt", "content": "+-----+\n| id |\n+-----+\n| 1 |\n| 4 |\n| 9 |\n| 16 |\n| 25 |\n| 36 |\n| 49 |\n| 64 |\n| 81 |\n| 100 |\n+-----+\n10 rows in set (0.02 sec)\n", "safe": true }, { "filename": "100 doors_452.txt", "content": "// allocate a boolean array with all closed doors (false)\n// we need 101 since there will technically be a door 0\ndoors = {false} * 101\n \n// loop through all the step lengths (1-100)\nfor step in range(1, 100)\n\t// loop through all the doors, stepping by step\n\tfor door in range(0, len(doors) - 1, step)\n\t\t// change the state of the current door\n\t\tdoors[door] = !doors[door]\n\tend for\nend for\n \n// loop through and print the doors that are open, skipping door 0\nfor i in range(1, len(doors) - 1)\n\t// if the door is open, display it\n\tif doors[i]\n\t\tprintln \"Door \" + i + \" is open.\"\n\tend if\nend for", "safe": true }, { "filename": "100 doors_453.txt", "content": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nTrue = Rexx(1 == 1)\nFalse = Rexx(\\True)\n\ndoors = False\n\nloop i_ = 1 to 100\n loop j_ = 1 to 100\n if 0 = (j_ // i_) then doors[j_] = \\doors[j_]\n end j_\n end i_\n\nloop d_ = 1 to 100\n if doors[d_] then state = 'open'\n else state = 'closed'\n\n say 'Door Nr.' Rexx(d_).right(4) 'is' state\n end d_", "safe": true }, { "filename": "100 doors_454.txt", "content": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nTrue = (1 == 1)\nFalse = \\True\n\ndoors = boolean[100]\n\nloop i_ = 0 to 9\n doors[(i_ + 1) * (i_ + 1) - 1] = True;\n end i_\n\nloop i_ = 0 to 99\n if doors[i_] then state = 'open'\n else state = 'closed'\n\n say 'Door Nr.' Rexx(i_ + 1).right(4) 'is' state\n end i_", "safe": true }, { "filename": "100 doors_455.txt", "content": "/* NetRexx */\noptions replace format comments java crossref savelog symbols binary\n\nresultstring = ''\n\nloop i_ = 1 to 10\n resultstring = resultstring || 'Door Nr.' Rexx(i_ * i_).right(4) 'is open\\n'\n end i_\n\nsay resultstring", "safe": true }, { "filename": "100 doors_456.txt", "content": "/* NetRexx */\n\nloop i = 1 to 10\n say 'Door Nr.' i * i 'is open.'\n end i", "safe": true }, { "filename": "100 doors_457.txt", "content": "(define (status door-num)\n (let ((x (int (sqrt door-num))))\n (if\n (= (* x x) door-num) (string \"Door \" door-num \" Open\")\n (string \"Door \" door-num \" Closed\"))))\n\n(dolist (n (map status (sequence 1 100)))\n (println n))", "safe": true }, { "filename": "100 doors_458.txt", "content": "(set 'Doors (array 100)) \u00a0;; Default value: nil (Closed)\n\n(for (x 0 99)\n (for (y x 99 (+ 1 x))\n (setf (Doors y) (not (Doors y)))))\n\n(for (x 0 99) \u00a0;; Display open doors\n (if (Doors x)\n (println (+ x 1) \"\u00a0: Open\")))", "safe": true }, { "filename": "100 doors_459.txt", "content": "1\u00a0: Open\n4\u00a0: Open\n9\u00a0: Open\n16\u00a0: Open\n25\u00a0: Open\n36\u00a0: Open\n49\u00a0: Open\n64\u00a0: Open\n81\u00a0: Open\n100\u00a0: Open\n", "safe": true }, { "filename": "100 doors_46.txt", "content": "\u2378\u2260\u233f0=(\u2373100)\u2218.|\u2373100\n", "safe": true }, { "filename": "100 doors_460.txt", "content": " n:=100;reduce xor (count n eachright mod count n eachall<1)\nlooloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo\n\nlooooooooooooooooool", "safe": true }, { "filename": "100 doors_461.txt", "content": " true findall (n:=100;reduce xor (count n eachright mod count n eachall<1))+1\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_462.txt", "content": " count 10 power 2\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_463.txt", "content": "from strutils import `%`\n\nconst numDoors = 100\nvar doors: array[1..numDoors, bool]\n\nfor pass in 1..numDoors:\n for door in countup(pass, numDoors, pass):\n doors[door] = not doors[door]\n\nfor door in 1..numDoors:\n echo \"Door $1 is $2.\"\u00a0% [$door, if doors[door]: \"open\" else: \"closed\"]", "safe": true }, { "filename": "100 doors_464.txt", "content": "from strutils import `%`\n\nconst numDoors = 100\nvar doors {.compileTime.}: array[1..numDoors, bool]\n\nproc calcDoors(): string =\n for pass in 1..numDoors:\n for door in countup(pass, numDoors, pass):\n doors[door] = not doors[door] \n for door in 1..numDoors:\n result.add(\"Door $1 is $2.\\n\"\u00a0% [$door, if doors[door]: \"open\" else: \"closed\"])\n\nconst outputString: string = calcDoors()\n\necho outputString", "safe": true }, { "filename": "100 doors_465.txt", "content": "MODULE Doors;\n IMPORT Out;\n \n PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *)\n CONST N = 100; len = N + 1;\n VAR i, j: INTEGER;\n closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *)\n BEGIN\n FOR i\u00a0:= 1 TO N DO closed[i]\u00a0:= TRUE END;\n FOR i\u00a0:= 1 TO N DO\n j\u00a0:= 1;\n WHILE j < len DO\n IF j MOD i = 0 THEN closed[j]\u00a0:= ~closed[j] END; INC(j) (* ~ = NOT *)\n END\n END;\n (* Print a state diagram of all doors *)\n FOR i\u00a0:= 1 TO N DO \n IF (i - 1) MOD 10 = 0 THEN Out.Ln END;\n IF closed[i] THEN Out.String(\"- \") ELSE Out.String(\"+ \") END\n END; Out.Ln;\n (* Print the numbers of the open doors *)\n FOR i\u00a0:= 1 TO N DO \n IF ~closed[i] THEN Out.Int(i, 0); Out.Char(\" \") END\n END; Out.Ln\n END Do;\n\nEND Doors.\n", "safe": true }, { "filename": "100 doors_466.txt", "content": "+ \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 + \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n+ \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 + \n1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100 doors_467.txt", "content": "bundle Default {\n class Doors {\n function\u00a0: Main(args\u00a0: String[]) ~ Nil {\n doors\u00a0:= Bool->New[100];\n \n for(pass\u00a0:= 0; pass < 10; pass += 1;) {\n doors[(pass + 1) * (pass + 1) - 1]\u00a0:= true;\n };\n \n for(i\u00a0:= 0; i < 100; i += 1;) { \n IO.Console->GetInstance()->Print(\"Door #\")->Print(i + 1)->Print(\" is \");\n if(doors[i]) {\n \"open.\"->PrintLine();\n }\n else {\n \"closed.\"->PrintLine();\n };\n };\n }\n }\n}", "safe": true }, { "filename": "100 doors_468.txt", "content": "@import Foundation;\n\nint main(int argc, const char * argv[]) {\n @autoreleasepool {\n \n // Create a mutable array\n NSMutableArray *doorArray = [@[] mutableCopy];\n \n // Fill the doorArray with 100 closed doors\n for (NSInteger i = 0; i < 100; ++i) {\n doorArray[i] = @NO;\n }\n \n // Do the 100 passes\n for (NSInteger pass = 0; pass < 100; ++pass) {\n for (NSInteger door = pass; door < 100; door += pass+1) {\n doorArray[door] = [doorArray[door] isEqual: @YES]\u00a0? @NO\u00a0: @YES;\n }\n }\n \n // Print the results\n [doorArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if ([obj isEqual: @YES]) {\n NSLog(@\"Door number %lu is open\", idx + 1);\n }\n }];\n }\n}", "safe": true }, { "filename": "100 doors_469.txt", "content": "@import Foundation;\n\n#pragma mark - Classes\n////////////////////////////////////////////////////\n// Model class header - A we are using a category to add a method to MSMutableArray\n@interface NSMutableArray (DoorModelExtension)\n\n- (void)setNumberOfDoors:(NSUInteger)doors;\n\n@end\n\n// Model class implementation\n@implementation NSMutableArray (DoorModelExtension)\n\n- (void)setNumberOfDoors:(NSUInteger)doors {\n // Fill the doorArray with 100 closed doors\n for (NSInteger i = 0; i < doors; ++i) {\n self[i] = @NO;\n }\n}\n@end\n////////////////////////////////////////////////////\n\n// View class header - A simple class to handle printing our values\n@interface DoorViewClass\u00a0: NSObject\n\n- (void)printResultsOfDoorTask:(NSMutableArray *)doors;\n\n@end\n\n// View class implementation\n@implementation DoorViewClass\n\n- (void)printResultsOfDoorTask:(NSMutableArray *)doors {\n\n // Print the results, using an enumeration block for easy index tracking\n [doors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if ([obj isEqual: @YES]) {\n NSLog(@\"Door number %lu is open\", idx + 1);\n }\n }];\n}\n\n@end\n////////////////////////////////////////////////////\n\n#pragma mark - main\n// With our classes set we can use them from our controller, in this case main\nint main(int argc, const char * argv[]) {\n \n // Init our classes\n NSMutableArray *doorArray = [NSMutableArray array];\n DoorViewClass *doorView = [DoorViewClass new];\n \n // Use our class category to add the doors\n [doorArray setNumberOfDoors:100];\n \n // Do the 100 passes\n for (NSUInteger pass = 0; pass < 100; ++pass) {\n for (NSUInteger door = pass; door < 100; door += pass+1) {\n doorArray[door] = [doorArray[door] isEqual: @YES]\u00a0? @NO\u00a0: @YES;\n }\n }\n \n // Print the results\n [doorView printResultsOfDoorTask:doorArray];\n \n}", "safe": true }, { "filename": "100 doors_47.txt", "content": "1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_470.txt", "content": "let max_doors = 100\n\nlet show_doors =\n Array.iteri (fun i x -> Printf.printf \"Door %d is %s\\n\" (i+1)\n (if x then \"open\" else \"closed\"))\n\nlet flip_doors doors =\n for i = 1 to max_doors do\n let rec flip idx =\n if idx < max_doors then begin\n doors.(idx) <- not doors.(idx);\n flip (idx + i)\n end\n in flip (i - 1)\n done;\n doors\n\nlet () =\n show_doors (flip_doors (Array.make max_doors false))", "safe": true }, { "filename": "100 doors_471.txt", "content": "let optimised_flip_doors doors =\n for i = 1 to int_of_float (sqrt (float_of_int max_doors)) do\n doors.(i*i - 1) <- true\n done;\n doors\n\nlet () =\n show_doors (optimised_flip_doors (Array.make max_doors false))", "safe": true }, { "filename": "100 doors_472.txt", "content": "type door = Open | Closed (* human readable code *)\n\nlet flipdoor = function Open -> Closed | Closed -> Open\n\nlet string_of_door = \n function Open -> \"is open.\" | Closed -> \"is closed.\"\n\nlet printdoors ls =\n let f i d = Printf.printf \"Door %i %s\\n\" (i + 1) (string_of_door d)\n in List.iteri f ls\n\nlet outerlim = 100\nlet innerlim = 100\n\nlet rec outer cnt accu =\n let rec inner i door = match i > innerlim with (* define inner loop *)\n | true -> door \n | false -> inner (i + 1) (if (cnt mod i) = 0 then flipdoor door else door)\n in (* define and do outer loop *)\n match cnt > outerlim with\n | true -> List.rev accu\n | false -> outer (cnt + 1) (inner 1 Closed\u00a0:: accu) (* generate new entries with inner *)\n\nlet () = printdoors (outer 1 [])", "safe": true }, { "filename": "100 doors_473.txt", "content": "doors = false(100,1);\nfor i = 1:100\n for j = i:i:100\n doors(j) = !doors(j);\n endfor\nendfor\nfor i = 1:100\n if ( doors(i) )\n s = \"open\";\n else\n s = \"closed\";\n endif\n printf(\"%d %s\\n\", i, s);\nendfor", "safe": true }, { "filename": "100 doors_474.txt", "content": "package main\n\nimport \"core:fmt\"\n\nmain\u00a0:: proc() {\n using fmt\n \n Door_State\u00a0:: enum {Closed, Open}\n \n doors\u00a0:= [?]Door_State { 0..<100 = .Closed }\n \n for i in 1..=100 {\n for j\u00a0:= i-1; j < 100; j += i {\n if doors[j] == .Closed {\n doors[j] = .Open\n } else {\n doors[j] = .Closed\n }\n }\n }\n for state, i in doors {\n println(\"Door: \",int(i+1),\" -> \",state)\n }\n}", "safe": true }, { "filename": "100 doors_475.txt", "content": "package main\n\nimport \"core:fmt\"\nimport \"core:math\"\n\nmain\u00a0:: proc() {\n using fmt\n \n Door_State\u00a0:: enum {Closed, Open}\n \n doors\u00a0:= [?]Door_State { 0..<100 = .Closed }\n \n for i in 1..=100 {\n res\u00a0:= math.sqrt_f64( f64(i) )\n if math.mod_f64( res, 1) == 0 {\n doors[i-1] = .Open\n } else {\n doors[i-1] = .Closed\n }\n println(\"Door: \", i, \" -> \", doors[i-1])\n }\n}", "safe": true }, { "filename": "100 doors_476.txt", "content": ": doors\n| i j l |\n 100 false Array newWith dup ->l\n 100 loop: i [ \n i 100 i step: j [ l put ( j , j l at not ) ] \n ] \n;", "safe": true }, { "filename": "100 doors_477.txt", "content": "(define (flip doors every)\n (map (lambda (door num)\n (mod (+ door (if (eq? (mod num every) 0) 1 0)) 2))\n doors\n (iota (length doors) 1)))\n\n(define doors\n (let loop ((doors (repeat 0 100)) (n 1))\n (if (eq? n 100)\n doors\n (loop (flip doors n) (+ n 1)))))\n\n(print \"100th doors: \" doors)", "safe": true }, { "filename": "100 doors_478.txt", "content": "100th doors: (1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)\n", "safe": true }, { "filename": "100 doors_479.txt", "content": "process\n local switch doors size 100\u00a0; all initialised ('1st pass' to false)\n\n repeat over doors\n repeat for integer door from #item to 100 by #item\n do when doors[door] = false\n activate doors[door]\u00a0; illustrating alternative to set ... to\n else\n set doors[door] to false\n done\n again\n again\n\n repeat over doors\n do when doors = true\n put #error '%d(#item)%n'\n done\n again", "safe": true }, { "filename": "100 doors_48.txt", "content": "set is_open to {}\nrepeat 100 times\n set end of is_open to false\nend\nrepeat with pass from 1 to 100\n repeat with door from pass to 100 by pass\n set item door of is_open to not item door of is_open\n end\nend\nset open_doors to {}\nrepeat with door from 1 to 100\n if item door of is_open then\n set end of open_doors to door\n end\nend\nset text item delimiters to \", \"\ndisplay dialog \"Open doors: \" & open_doors\n", "safe": true }, { "filename": "100 doors_480.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100 doors_481.txt", "content": "process\n local integer door initial {1}\n local integer step initial {3}\n\n repeat\n output \"Door %d(door) is open%n\"\n increment door by step\n increment step by 2\n exit when door > 100\n again", "safe": true }, { "filename": "100 doors_482.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open\n", "safe": true }, { "filename": "100 doors_483.txt", "content": "$Door dict def\n1 1 100 {Door exch false put} for\n$Toggle {dup Door exch get not Door up put} def\n$EveryNthDoor {dup 100 {Toggle} for} def\n$Run {1 1 100 {EveryNthDoor} for} def\n$ShowDoor {dup `Door no. ' exch cvs cat ` is ' cat\n exch Door exch get {`open.\\n'}{`shut.\\n'} ifelse cat\n print flush} def\nRun 1 1 100 {ShowDoor} for", "safe": true }, { "filename": "100 doors_484.txt", "content": "Door no. 1 is open.\nDoor no. 2 is shut.\nDoor no. 3 is shut.\nDoor no. 4 is open.\nDoor no. 5 is shut.\nDoor no. 6 is shut.\nDoor no. 7 is shut.\nDoor no. 8 is shut.\nDoor no. 9 is open.\nDoor no. 10 is shut.\nDoor no. 11 is shut.\nDoor no. 12 is shut.\nDoor no. 13 is shut.\nDoor no. 14 is shut.\nDoor no. 15 is shut.\nDoor no. 16 is open.\nDoor no. 17 is shut.\nDoor no. 18 is shut.\nDoor no. 19 is shut.\nDoor no. 20 is shut.\nDoor no. 21 is shut.\nDoor no. 22 is shut.\nDoor no. 23 is shut.\nDoor no. 24 is shut.\nDoor no. 25 is open.\nDoor no. 26 is shut.\nDoor no. 27 is shut.\nDoor no. 28 is shut.\nDoor no. 29 is shut.\nDoor no. 30 is shut.\nDoor no. 31 is shut.\nDoor no. 32 is shut.\nDoor no. 33 is shut.\nDoor no. 34 is shut.\nDoor no. 35 is shut.\nDoor no. 36 is open.\nDoor no. 37 is shut.\nDoor no. 38 is shut.\nDoor no. 39 is shut.\nDoor no. 40 is shut.\nDoor no. 41 is shut.\nDoor no. 42 is shut.\nDoor no. 43 is shut.\nDoor no. 44 is shut.\nDoor no. 45 is shut.\nDoor no. 46 is shut.\nDoor no. 47 is shut.\nDoor no. 48 is shut.\nDoor no. 49 is open.\nDoor no. 50 is shut.\nDoor no. 51 is shut.\nDoor no. 52 is shut.\nDoor no. 53 is shut.\nDoor no. 54 is shut.\nDoor no. 55 is shut.\nDoor no. 56 is shut.\nDoor no. 57 is shut.\nDoor no. 58 is shut.\nDoor no. 59 is shut.\nDoor no. 60 is shut.\nDoor no. 61 is shut.\nDoor no. 62 is shut.\nDoor no. 63 is shut.\nDoor no. 64 is open.\nDoor no. 65 is shut.\nDoor no. 66 is shut.\nDoor no. 67 is shut.\nDoor no. 68 is shut.\nDoor no. 69 is shut.\nDoor no. 70 is shut.\nDoor no. 71 is shut.\nDoor no. 72 is shut.\nDoor no. 73 is shut.\nDoor no. 74 is shut.\nDoor no. 75 is shut.\nDoor no. 76 is shut.\nDoor no. 77 is shut.\nDoor no. 78 is shut.\nDoor no. 79 is shut.\nDoor no. 80 is shut.\nDoor no. 81 is open.\nDoor no. 82 is shut.\nDoor no. 83 is shut.\nDoor no. 84 is shut.\nDoor no. 85 is shut.\nDoor no. 86 is shut.\nDoor no. 87 is shut.\nDoor no. 88 is shut.\nDoor no. 89 is shut.\nDoor no. 90 is shut.\nDoor no. 91 is shut.\nDoor no. 92 is shut.\nDoor no. 93 is shut.\nDoor no. 94 is shut.\nDoor no. 95 is shut.\nDoor no. 96 is shut.\nDoor no. 97 is shut.\nDoor no. 98 is shut.\nDoor no. 99 is shut.\nDoor no. 100 is open.", "safe": true }, { "filename": "100 doors_485.txt", "content": "doors = .array~new(100) -- array containing all of the doors\ndo i = 1 to doors~size -- initialize with a collection of closed doors\n doors[i] = .door~new(i)\nend\n\ndo inc = 1 to doors~size\n do d = inc to doors~size by inc\n doors[d]~toggle\n end\nend\nsay \"The open doors after 100 passes:\"\ndo door over doors\n if door~isopen then say door\nend\n\n::class door -- simple class to represent a door\n::method init -- initialize an instance of a door\n expose id state -- instance variables of a door\n use strict arg id -- set the id\n state = .false -- initial state is closed\n\n::method toggle -- toggle the state of the door\n expose state\n state = \\state\n\n::method isopen -- test if the door is open\n expose state\n return state\n\n::method string -- return a string value for a door\n expose state id\n if state then return \"Door\" id \"is open\"\n else return \"Door\" id \"is closed\"\n\n::method state -- return door state as a descriptive string\n expose state\n if state then return \"open\"\n else return \"closed\"", "safe": true }, { "filename": "100 doors_486.txt", "content": "DEFINE VARIABLE lopen AS LOGICAL NO-UNDO EXTENT 100.\nDEFINE VARIABLE idoor AS INTEGER NO-UNDO.\nDEFINE VARIABLE ipass AS INTEGER NO-UNDO.\nDEFINE VARIABLE cresult AS CHARACTER NO-UNDO.\n\nDO ipass = 1 TO 100:\n idoor = 0.\n DO WHILE idoor <= 100:\n idoor = idoor + ipass.\n IF idoor <= 100 THEN\n lopen[ idoor ] = NOT lopen[ idoor ].\n END.\nEND.\n\nDO idoor = 1 TO 100:\n cresult = cresult + STRING( lopen[ idoor ], \"1 /0 \" ).\n IF idoor MODULO 10 = 0 THEN\n cresult = cresult + \"~r\":U.\nEND.\n\nMESSAGE cresult VIEW-AS ALERT-BOX.", "safe": true }, { "filename": "100 doors_487.txt", "content": "def doors 100\nint door[doors],i ,j, c\nstring cr,tab,pr\n'\nfor i=1 to doors\n for j=i to doors step i\n door[j]=1-door[j]\n if door[j] then c++ else c--\n next\nnext\n'\ncr=chr(13) chr(10)\npr=\"Doors Open: \" c cr cr \n'\nfor i=1 to doors\n if door[i] then pr+=i cr\nnext\nprint pr\n", "safe": true }, { "filename": "100 doors_488.txt", "content": "declare\n NumDoors = 100\n NumPasses = 100\n\n fun {NewDoor} closed end\n\n fun {Toggle Door}\n case Door of closed then open\n [] open then closed\n end\n end\n\n fun {Pass Doors I}\n {List.mapInd Doors\n fun {$ Index Door}\n if Index mod I == 0 then {Toggle Door}\n else Door\n end\n end}\n end\n \n Doors0 = {MakeList NumDoors}\n {ForAll Doors0 NewDoor}\n\n DoorsN = {FoldL {List.number 1 NumPasses 1} Pass Doors0}\nin\n \u00a0%% print open doors\n {List.forAllInd DoorsN\n proc {$ Index Door}\n if Door == open then\n\t {System.showInfo \"Door \"#Index#\" is open.\"}\n end\n end\n }", "safe": true }, { "filename": "100 doors_489.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.\n", "safe": true }, { "filename": "100 doors_49.txt", "content": "on _100doors()\n script o\n property doors : {}\n end script\n repeat 100 times\n set end of o's doors to false -- false = \"not open\".\n end repeat\n repeat with pass from 1 to 100\n if (not item pass of o's doors) then set item pass of o's doors to pass\n repeat with d from (pass + pass) to 100 by pass\n set item d of o's doors to (not item d of o's doors)\n end repeat\n end repeat\n \n return o's doors's integers\nend _100doors\n\non join(lst, delim)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delim\n set txt to lst as text\n set AppleScript's text item delimiters to astid\n return txt\nend join\n\nreturn \"Open doors:\n\" & join(_100doors(), \", \")\n", "safe": true }, { "filename": "100 doors_490.txt", "content": "v=vector(d=100);/*set 100 closed doors*/\nfor(i=1,d,forstep(j=i,d,i,v[j]=1-v[j]));\nfor(i=1,d,if(v[i],print(\"Door \",i,\" is open.\")))", "safe": true }, { "filename": "100 doors_491.txt", "content": "for(n=1,sqrt(100),print(\"Door \",n^2,\" is open.\"))", "safe": true }, { "filename": "100 doors_492.txt", "content": "doors =vector(100);\nprint(\"open doors are\u00a0: \");\nfor(i=1,100,for(j=i,100,doors[j]=!doors[j];j +=i-1))\nfor(k=1,100,if(doors[k]==1,print1(\" \",k)))", "safe": true }, { "filename": "100 doors_493.txt", "content": "Open doors are:\n 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_494.txt", "content": "Program OneHundredDoors;\n\nvar\n doors\u00a0: Array[1..100] of Boolean;\n i, j\t\u00a0: Integer;\n \nbegin\n for i\u00a0:= 1 to 100 do\n doors[i]\u00a0:= False;\n for i\u00a0:= 1 to 100 do begin\n j\u00a0:= i;\n while j <= 100 do begin\n\t doors[j]\u00a0:= not doors[j];\n\t j\u00a0:= j + i\n end\n end;\n for i\u00a0:= 1 to 100 do begin\n Write(i, ' ');\n if doors[i] then\n\t WriteLn('open')\n else\n\t WriteLn('closed');\n end\nend.", "safe": true }, { "filename": "100 doors_495.txt", "content": "program OneHundredDoors;\n\n{$APPTYPE CONSOLE}\n\nuses\n math, sysutils;\n\nvar\n AOpendoors \u00a0: String;\n ACloseDoors\u00a0: String;\n i\t \u00a0: Integer;\n\nbegin\n for i\u00a0:= 1 to 100 do\n begin\n if (sqrt(i) = floor(sqrt(i))) then\n AOpenDoors\u00a0:= AOpenDoors + IntToStr(i) + ';'\n else\n ACloseDoors\u00a0:= ACloseDoors + IntToStr(i) +';';\n end;\n\n WriteLn('Open doors: ' + AOpenDoors);\n WriteLn('Close doors: ' + ACloseDoors);\nend.", "safe": true }, { "filename": "100 doors_496.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_497.txt", "content": ";100 doors example program for x86 DOS\n;Compiles with Pebble to 95 bytes com executable\n\nprogram examples\\100doors\n\ndata\n\n\tint i[0]\n\tint d[0]\n\nbegin\n\n\tlabel loop\n\n\t\t+1 [i]\n\t\t[d] = [i] * [i]\n\t\techo [d]\n\t\tcrlf\n\n\tif [d] < 100 then loop\n\n\tpause\n\tkill\n\nend", "safe": true }, { "filename": "100 doors_498.txt", "content": "my @doors;\nfor my $pass (1 .. 100) {\n for (1 .. 100) {\n if (0 == $_\u00a0% $pass) {\n $doors[$_] = not $doors[$_];\n };\n };\n};\n\nprint \"Door $_ is \", $doors[$_]\u00a0? \"open\"\u00a0: \"closed\", \"\\n\" for 1 .. 100;", "safe": true }, { "filename": "100 doors_499.txt", "content": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy @doors = (1) x 100;\nfor my $N (1 .. 100) {\n $doors[$_]=1-$doors[$_] for map { $_*$N - 1 } 1 .. int(100/$N);\n}\nprint join(\"\\n\", map { \"Door $_ is Open\" } grep {\u00a0! $doors[$_-1] } 1 .. 100), \"\\n\";\nprint \"The rest are closed\\n\";", "safe": true }, { "filename": "100 doors_5.txt", "content": "%@left[n,string] ^: Return n leftmost chars in string\n%@right[n,string] ^: Return n rightmost chars in string\n%@if[condition,true-val,false-val] ^: Evaluate condition; return true-val if true, false-val if false\n", "safe": true }, { "filename": "100 doors_50.txt", "content": "\"Open doors:\n1, 4, 9, 16, 25, 36, 49, 64, 81, 100\"\n", "safe": true }, { "filename": "100 doors_500.txt", "content": "print \"Door $_ is open\\n\" for map $_**2, 1 .. 10;", "safe": true }, { "filename": "100 doors_501.txt", "content": "print \"Door $_ is \", qw\"closed open\"[int sqrt == sqrt], \"\\n\" for 1..100;", "safe": true }, { "filename": "100 doors_502.txt", "content": "while( ++$i <= 100 )\n{\n $root = sqrt($i);\n if ( int( $root ) == $root )\n {\n print \"Door $i is open\\n\";\n }\n else\n {\n print \"Door $i is closed\\n\";\n }\n}", "safe": true }, { "filename": "100 doors_503.txt", "content": "use perl5i::2;\n\npackage doors {\n\n use perl5i::2;\n use Const::Fast;\n\n const my $OPEN => 1;\n const my $CLOSED => 0;\n\n # ----------------------------------------\n # Constructor: door->new( @args );\n # input: N - how many doors?\n # returns: door object\n #\n method new($class: @args ) {\n my $self = bless {}, $class;\n $self->_init( @args );\n return $self;\n }\n\n # ----------------------------------------\n # class initializer.\n # input: how many doors?\n # sets N, creates N+1 doors ( door zero is not used ).\n #\n method _init( $N ) {\n $self->{N} = $N;\n $self->{doors} = [ ($CLOSED) x ($N+1) ];\n }\n\n # ----------------------------------------\n # $self->toggle( $door_number );\n # input: number of door to toggle.\n # OPEN a CLOSED door; CLOSE an OPEN door.\n #\n method toggle( $which ) {\n $self->{doors}[$which] = ( $self->{doors}[$which] == $OPEN\n \u00a0? $CLOSED\n \u00a0: $OPEN\n \t\t );\n }\n\n # ----------------------------------------\n # $self->toggle_n( $cycle );\n # input: number.\n # Toggle doors 0, $cycle, 2 * $cycle, 3 * $cycle, .. $self->{N}\n #\n method toggle_n( $n ) {\n $self->toggle($_)\n for map { $n * $_ }\n ( 1 .. int( $self->{N} / $n) );\n\n }\n\n # ----------------------------------------\n # $self->toggle_all();\n # Toggle every door, then every other door, every third door, ...\n #\n method toggle_all() {\n $self->toggle_n( $_ ) for ( 1 .. $self->{N} );\n }\n\n\n # ----------------------------------------\n # $self->print_open();\n # Print list of which doors are open.\n #\n method print_open() {\n say join ', ', grep { $self->{doors}[$_] == $OPEN } ( 1 ... $self->{N} );\n }\n}\n\n# ----------------------------------------------------------------------\n# Main Thread\n#\nmy $doors = doors->new(100);\n$doors->toggle_all();\n$doors->print_open();", "safe": true }, { "filename": "100 doors_504.txt", "content": "sequence doors = repeat(false,100)\n \nfor i=1 to 100 do\n for j=i to 100 by i do\n doors[j] = not doors[j]\n end for\nend for\n \nfor i=1 to 100 do\n if doors[i] == true then\n printf(1,\"Door #%d is open.\\n\", i)\n end if\nend for\n", "safe": true }, { "filename": "100 doors_505.txt", "content": "Door #1 is open.\nDoor #4 is open.\nDoor #9 is open.\nDoor #16 is open.\nDoor #25 is open.\nDoor #36 is open.\nDoor #49 is open.\nDoor #64 is open.\nDoor #81 is open.\nDoor #100 is open.\n", "safe": true }, { "filename": "100 doors_506.txt", "content": "function doors(integer n)\n-- returns the perfect squares<=n\ninteger door = 1, step = 1\nsequence res = {}\n while door<=n do\n res &= door\n step += 2\n door += step\n end while\n return res\nend function\n \n?doors(100)\n", "safe": true }, { "filename": "100 doors_507.txt", "content": "{1,4,9,16,25,36,49,64,81,100}\n", "safe": true }, { "filename": "100 doors_508.txt", "content": "101 var l \n0 l repeat \n\nl for\n var s\n s l s 3 tolist\n for\n var i\n i get not i set\n endfor\nendfor\n\nl for\n var i\n i get\n if\n i print \" \" print\n endif\nendfor", "safe": true }, { "filename": "100 doors_509.txt", "content": "100 var n /# Number of doors #/\n0 n repeat /# Make the doors #/\n\nn for\n dup\n sqrt int\n dup * over == if 1 swap set else drop endif\nendfor\n\nn for\n \"The door \" print dup print \" is \" print\n get if \"OPEN.\" else \"closed.\" endif print nl\nendfor", "safe": true }, { "filename": "100 doors_51.txt", "content": "-- FINAL DOOR STATES ---------------------------------------------------------\n\n-- finalDoors\u00a0:: Int -> [(Int, Bool)]\non finalDoors(n)\n \n -- toggledCorridor\u00a0:: [(Int, Bool)] -> (Int, Bool) -> Int -> [(Int, Bool)]\n script toggledCorridor\n on |\u03bb|(a, _, k)\n \n -- perhapsToggled\u00a0:: Bool -> Int -> Bool\n script perhapsToggled\n on |\u03bb|(x, i)\n if i mod k = 0 then\n {i, not item 2 of x}\n else\n {i, item 2 of x}\n end if\n end |\u03bb|\n end script\n \n map(perhapsToggled, a)\n end |\u03bb|\n end script\n \n set xs to enumFromTo(1, n)\n \n foldl(toggledCorridor, \u00ac\n zip(xs, replicate(n, {false})), xs)\nend finalDoors\n\n-- TEST ----------------------------------------------------------------------\non run\n -- isOpenAtEnd\u00a0:: (Int, Bool) -> Bool\n script isOpenAtEnd\n on |\u03bb|(door)\n (item 2 of door)\n end |\u03bb|\n end script\n \n -- doorNumber\u00a0:: (Int, Bool) -> Int\n script doorNumber\n on |\u03bb|(door)\n (item 1 of door)\n end |\u03bb|\n end script\n \n map(doorNumber, filter(isOpenAtEnd, finalDoors(100)))\n \n --> {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\nend run\n\n\n-- GENERIC FUNCTIONS ---------------------------------------------------------\n\n-- enumFromTo\u00a0:: Int -> Int -> [Int]\non enumFromTo(m, n)\n if n < m then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- filter\u00a0:: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |\u03bb|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- foldl\u00a0:: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |\u03bb|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- map\u00a0:: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |\u03bb|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- min\u00a0:: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n-- Lift 2nd class handler function into 1st class script wrapper \n-- mReturn\u00a0:: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |\u03bb| : f\n end script\n end if\nend mReturn\n\n-- replicate\u00a0:: Int -> a -> [a]\non replicate(n, a)\n set out to {}\n if n < 1 then return out\n set dbl to {a}\n \n repeat while (n > 1)\n if (n mod 2) > 0 then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n-- zip\u00a0:: [a] -> [b] -> [(a, b)]\non zip(xs, ys)\n set lng to min(length of xs, length of ys)\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to {item i of xs, item i of ys}\n end repeat\n return lst\nend zip\n", "safe": true }, { "filename": "100 doors_510.txt", "content": "100 sqrt for dup * print \" \" print endfor", "safe": true }, { "filename": "100 doors_511.txt", "content": "module doors;\n\nextern printf;\n\n@Integer main [\n\t@Array<@Boolean> doors = new @Array<@Boolean>.init(100);\n\tvar i = 1;\n\twhile (i <= 100) {\n\t\tvar j = i-1;\n\t\twhile (j < 100) {\n\t\t\tdoors.set(j, doors.get(j)::not);\n\t\t\tj = j + i;\n\t\t}\n\t\ti = i::inc;\n\t}\n\ti = 0;\n\twhile (i < 100) {\n\t\tprintf(\"%i %s\\n\", i+1, iif(doors.get(i), \"open\", \"closed\"));\n\t\ti = i::inc;\n\t}\n\treturn 0;\n]", "safe": true }, { "filename": "100 doors_512.txt", "content": "module var;\n\nextern printf;\n\n@Integer main [\n\tvar door = 1;\n\tvar incrementer = 0;\n\tvar current = 1;\n while (current <= 100)\n {\n\t\tprintf(\"Door %i \", current);\n\t\tif (current == door)\n\t\t{\n\t\t\tprintf(\"open\\n\");\n\t\t\tincrementer = incrementer::inc;\n\t\t\tdoor = door + 2 * incrementer + 1;\n\t\t}\n\t\telse\n\t\t\tprintf(\"closed\\n\");\n\t\t\n\t\tcurrent = current + 1;\n \n }\n\t\n\treturn 0;\n]", "safe": true }, { "filename": "100 doors_513.txt", "content": "", "safe": true }, { "filename": "100 doors_514.txt", "content": "", "safe": true }, { "filename": "100 doors_515.txt", "content": "doors(N) => \n Doors = new_array(N),\n foreach(I in 1..N) Doors[I]\u00a0:= 0 end,\n foreach(I in 1..N)\n foreach(J in I..I..N)\n Doors[J]\u00a0:= 1^Doors[J]\n end,\n if N <= 10 then\n print_open(Doors)\n end\n end,\n println(Doors),\n print_open(Doors),\n nl.\n\nprint_open(Doors) => println([I\u00a0: I in 1..Doors.length, Doors[I] == 1]).", "safe": true }, { "filename": "100 doors_516.txt", "content": "doors_opt(N) =>\n foreach(I in 1..N)\n Root = sqrt(I),\n println([I, cond(Root == 1.0*round(Root), open, closed)])\n end,\n nl.", "safe": true }, { "filename": "100 doors_517.txt", "content": "doors_opt2(N) => \n println([I**2\u00a0: I in 1..N, I**2 <= N]).", "safe": true }, { "filename": "100 doors_518.txt", "content": "(let Doors (need 100)\n (for I 100\n (for (D (nth Doors I) D (cdr (nth D I)))\n (set D (not (car D))) ) )\n (println Doors) )", "safe": true }, { "filename": "100 doors_519.txt", "content": "(let Doors (need 100)\n (for I (sqrt 100)\n (set (nth Doors (* I I)) T) )\n (println Doors) )", "safe": true }, { "filename": "100 doors_52.txt", "content": "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\n", "safe": true }, { "filename": "100 doors_520.txt", "content": "(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL N\nIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)", "safe": true }, { "filename": "100 doors_521.txt", "content": "(let Doors (need 100)\n (for I (sqrt 100)\n (set (nth Doors (* I I)) T) )\n (make\n (for (N . D) Doors\n (when D (link N)) ) ) )", "safe": true }, { "filename": "100 doors_522.txt", "content": "(1 4 9 16 25 36 49 64 81 100)", "safe": true }, { "filename": "100 doors_523.txt", "content": "array onehundreddoors()\n{\n array doors = allocate(100);\n foreach(doors; int i;)\n for(int j=i; j<100; j+=i+1)\n doors[j] = !doors[j];\n return doors;\n}", "safe": true }, { "filename": "100 doors_524.txt", "content": "array doors = map(enumerate(100,1,1), lambda(int x)\n { \n return sqrt((float)x)%1 == 0.0; \n });", "safe": true }, { "filename": "100 doors_525.txt", "content": "write(\"%{%d %d %d %d %d %d %d %d %d %d\\n%}\\n\", doors/10)", "safe": true }, { "filename": "100 doors_526.txt", "content": "1 0 0 1 0 0 0 0 1 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 0 0 0 0 1 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 1\n", "safe": true }, { "filename": "100 doors_527.txt", "content": "declare door(100) bit (1) aligned;\ndeclare closed bit (1) static initial ('0'b),\n open bit (1) static initial ('1'b);\ndeclare (i, inc) fixed binary;\n\ndoor = closed;\ninc = 1;\ndo until (inc >= 100);\n do i = inc to 100 by inc;\n door(i) = ^door(i); /* close door if open; open it if closed. */\n end;\n inc = inc+1;\nend;\n\ndo i = 1 to 100;\n put skip edit ('Door ', trim(i), ' is ') (a);\n if door(i) then put edit (' open.') (a);\n else put edit (' closed.') (a);\nend;", "safe": true }, { "filename": "100 doors_528.txt", "content": "/* Solution to the 100 doors problem in PLI-80 */\n\nhundred_doors:\n procedure options (main);\n\n %replace\n open_door by '1'b,\n closed_door by '0'b,\n numdoors by 100;\n\n dcl\n doors(1:numdoors) bit(1),\n (i, j) fixed bin(15);\n\n /* all doors are initially closed */\n do i = 1 to numdoors;\n doors(i) = closed_door;\n end;\n\n /* cycle through at increasing intervals and flip doors */\n do i = 1 to numdoors;\n j = i;\n do while (j <= numdoors);\n doors(j) = ^doors(j);\n j = j + i;\n end;\n end;\n\n /* show results - open doors should all be perfect squares */\n put skip list ('The open doors are:');\n do i = 1 to numdoors;\n if doors(i) = open_door then\n put edit (i) (F(4));\n end;\n\nend hundred_doors;", "safe": true }, { "filename": "100 doors_529.txt", "content": "The open doors are: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_53.txt", "content": "map(factorCountMod2, enumFromTo(1, 100))\n\non factorCountMod2(n)\n {n, (length of integerFactors(n)) mod 2 = 1}\nend factorCountMod2\n", "safe": true }, { "filename": "100 doors_530.txt", "content": "100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */\n\n /* BDOS SYSTEM CALL */\n BDOS: PROCEDURE( FN, ARG );\n DECLARE FN BYTE, ARG ADDRESS;\n GO TO 5;\n END BDOS;\n\n /* PRINTS A BYTE AS A CHARACTER */\n PRINT$CHAR: PROCEDURE( CH );\n DECLARE CH BYTE;\n CALL BDOS( 2, CH );\n END PRINT$CHAR;\n\n /* PRINTS A BYTE AS A NUMBER */\n PRINT$BYTE: PROCEDURE( N );\n DECLARE N BYTE;\n DECLARE ( V, D3, D2 ) BYTE;\n V = N;\n D3 = V MOD 10;\n IF ( V\u00a0:= V / 10 ) <> 0 THEN DO;\n D2 = V MOD 10;\n IF ( V\u00a0:= V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );\n CALL PRINT$CHAR( '0' + D2 );\n END;\n CALL PRINT$CHAR( '0' + D3 );\n END PRINT$BYTE;\n\n DECLARE DOOR$DCL LITERALLY '101';\n DECLARE FALSE LITERALLY '0';\n DECLARE CR LITERALLY '0DH';\n DECLARE LF LITERALLY '0AH';\n\n /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */\n DECLARE DOOR( DOOR$DCL ) BYTE;\n DECLARE ( I, J ) BYTE;\n\n /* SET ALL DOORS TO CLOSED */\n DO I = 0 TO LAST( DOOR ); DOOR( I ) = FALSE; END;\n /* REPEATEDLY FLIP THE DOORS */\n DO I = 1 TO LAST( DOOR );\n DO J = I TO LAST( DOOR ) BY I;\n DOOR( J ) = NOT DOOR( J );\n END;\n END;\n /* DISPLAY THE RESULTS */\n DO I = 1 TO LAST( DOOR );\n IF DOOR( I ) THEN DO;\n CALL PRINT$CHAR( ' ' );\n CALL PRINT$BYTE( I );\n END;\n END;\n CALL PRINT$CHAR( CR );\n CALL PRINT$CHAR( LF );\nEOF", "safe": true }, { "filename": "100 doors_531.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_532.txt", "content": "DECLARE\n TYPE doorsarray IS VARRAY(100) OF BOOLEAN;\n doors doorsarray\u00a0:= doorsarray();\nBEGIN\n\ndoors.EXTEND(100); --ACCOMMODATE 100 DOORS\n\nFOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE\n LOOP\n doors(i)\u00a0:= FALSE; \n END LOOP;\n\nFOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE\n LOOP\n FOR k IN 1 .. 100\n LOOP\n IF MOD(k,j)=0 THEN \n doors(k)\u00a0:= NOT doors(k); \n END IF;\n END LOOP;\n END LOOP;\n \nFOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION\n LOOP\n DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE' \n THEN 'OPEN' \n ELSE 'CLOSED' \n END);\n END LOOP;\n\nEND;", "safe": true }, { "filename": "100 doors_533.txt", "content": "To create some doors given a count:\n Loop.\n If a counter is past the count, exit.\n Allocate memory for a door.\n Clear the door's flag.\n Append the door to the doors.\n Repeat.\n\nA flag thing is a thing with a flag.\nA door is a flag thing.\n\nTo go through some doors given a number and some passes:\n Put 0 into a counter.\n Loop.\n Add the number to the counter.\n If the counter is greater than the passes, exit.\n Pick a door from the doors given the number.\n Invert the door's flag.\n Repeat.\n\nTo output the states of some doors:\n Loop.\n Bump a counter.\n Get a door from the doors.\n If the door is nil, exit.\n If the door's flag is set, \n Write \"Door \" then the counter then \" is open\" to the output; \n Repeat.\n Write \"Door \" then the counter then \" is closed\" to the output.\n Repeat.\n\nTo pass doors given a count and some passes:\n Create some doors given the count.\n Loop.\n If a counter is past the passes, break.\n Go through the doors given the counter and the passes.\n Repeat.\n Output the states of the doors.\n Destroy the doors.\n\nA pass is a number.\n\nTo pick a door from some doors given a number:\n Loop.\n If a counter is past the number, exit.\n Get the door from the doors.\n If the door is nil, exit.\n Repeat.\n\nTo run:\n Start up.\n Pass doors given 100 and 100 passes.\n Wait for the escape key.\n Shut down.", "safe": true }, { "filename": "100 doors_534.txt", "content": "Door 1 is open\nDoor 2 is closed\nDoor 3 is closed\nDoor 4 is open\nDoor 5 is closed\nDoor 6 is closed\nDoor 7 is closed\nDoor 8 is closed\nDoor 9 is open\nDoor 10 is closed\nDoor 11 is closed\nDoor 12 is closed\nDoor 13 is closed\nDoor 14 is closed\nDoor 15 is closed\nDoor 16 is open\nDoor 17 is closed\nDoor 18 is closed\nDoor 19 is closed\nDoor 20 is closed\nDoor 21 is closed\nDoor 22 is closed\nDoor 23 is closed\nDoor 24 is closed\nDoor 25 is open\nDoor 26 is closed\nDoor 27 is closed\nDoor 28 is closed\nDoor 29 is closed\nDoor 30 is closed\nDoor 31 is closed\nDoor 32 is closed\nDoor 33 is closed\nDoor 34 is closed\nDoor 35 is closed\nDoor 36 is open\nDoor 37 is closed\nDoor 38 is closed\nDoor 39 is closed\nDoor 40 is closed\nDoor 41 is closed\nDoor 42 is closed\nDoor 43 is closed\nDoor 44 is closed\nDoor 45 is closed\nDoor 46 is closed\nDoor 47 is closed\nDoor 48 is closed\nDoor 49 is open\nDoor 50 is closed\nDoor 51 is closed\nDoor 52 is closed\nDoor 53 is closed\nDoor 54 is closed\nDoor 55 is closed\nDoor 56 is closed\nDoor 57 is closed\nDoor 58 is closed\nDoor 59 is closed\nDoor 60 is closed\nDoor 61 is closed\nDoor 62 is closed\nDoor 63 is closed\nDoor 64 is open\nDoor 65 is closed\nDoor 66 is closed\nDoor 67 is closed\nDoor 68 is closed\nDoor 69 is closed\nDoor 70 is closed\nDoor 71 is closed\nDoor 72 is closed\nDoor 73 is closed\nDoor 74 is closed\nDoor 75 is closed\nDoor 76 is closed\nDoor 77 is closed\nDoor 78 is closed\nDoor 79 is closed\nDoor 80 is closed\nDoor 81 is open\nDoor 82 is closed\nDoor 83 is closed\nDoor 84 is closed\nDoor 85 is closed\nDoor 86 is closed\nDoor 87 is closed\nDoor 88 is closed\nDoor 89 is closed\nDoor 90 is closed\nDoor 91 is closed\nDoor 92 is closed\nDoor 93 is closed\nDoor 94 is closed\nDoor 95 is closed\nDoor 96 is closed\nDoor 97 is closed\nDoor 98 is closed\nDoor 99 is closed\nDoor 100 is open\n", "safe": true }, { "filename": "100 doors_535.txt", "content": "output =\n range(1, 100)\n |> map(visit(100))\n |> println\n\n----------------------------------------------------------\n\ntoggle(state) =\n if state == Closed then Open else Closed\n\n----------------------------------------------------------\n-- Door state on iteration i is recursively\n-- defined in terms of previous door state\n\nvisit(i, index) = cond {\n case (i == 0) Closed\n case (index\u00a0% i == 0) toggle(lastState)\n else lastState\n} where lastState = visit(i - 1, index)", "safe": true }, { "filename": "100 doors_536.txt", "content": "[Open, Closed, Closed, Open, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open]", "safe": true }, { "filename": "100 doors_537.txt", "content": "/* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */\ndoors_100H: procedure options (main);\n\n/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */\n/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */\n /* PL/I */\n %replace dcldoors by 100;\n /* PL/M */ /*\n DECLARE DCLDOORS LITERALLY '101';\n /* */\n\n/* PL/I DEFINITIONS */\n%include 'pg.inc';\n/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*\n DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';\n DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';\n DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';\n DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';\n DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';\n BDOSF: PROCEDURE( FN, ARG )BYTE;\n DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; \n BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;\n PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;\n PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;\n PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;\n PRNUMBER: PROCEDURE( N );\n DECLARE N ADDRESS;\n DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;\n N$STR( W\u00a0:= LAST( N$STR ) ) = '$';\n N$STR( W\u00a0:= W - 1 ) = '0' + ( ( V\u00a0:= N ) MOD 10 );\n DO WHILE( ( V\u00a0:= V / 10 ) > 0 );\n N$STR( W\u00a0:= W - 1 ) = '0' + ( V MOD 10 );\n END; \n CALL BDOS( 9, .N$STR( W ) );\n END PRNUMBER;\n MODF: PROCEDURE( A, B )ADDRESS;\n DECLARE ( A, B ) ADDRESS;\n RETURN A MOD B;\n END MODF;\n/* END LANGUAGE DEFINITIONS */\n\n /* TASK */\n\n /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */\n DECLARE DOOR( DCLDOORS ) BIT;\n DECLARE ( I, J, MAXDOOR ) FIXED BINARY;\n\n MAXDOOR = HBOUND( DOOR ,1\n );\n\n /* SET ALL DOORS TO CLOSED */\n DO I = 0 TO MAXDOOR; DOOR( I ) = FALSE; END;\n /* REPEATEDLY FLIP THE DOORS */\n DO I = 1 TO MAXDOOR;\n DO J = I TO MAXDOOR BY I;\n DOOR( J ) = NOT( DOOR( J ) );\n END;\n END;\n /* DISPLAY THE RESULTS */\n DO I = 1 TO MAXDOOR;\n IF DOOR( I ) THEN DO;\n CALL PRCHAR( ' ' );\n CALL PRNUMBER( I );\n END;\n END;\n CALL PRNL;\n\nEOF: end doors_100H;", "safe": true }, { "filename": "100 doors_538.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_539.txt", "content": "actor Toggler\n let doors:Array[Bool]\n let env: Env\n new create(count:USize,_env:Env) =>\n var i:USize=0\n doors=Array[Bool](count)\n env=_env\n while doors.size() < count do\n doors.push(false)\n end\n be togglin(interval\u00a0: USize)=>\n var i:USize=0\n try\n while i < doors.size() do\n doors.update(i,not doors(i)?)?\n i=i+interval\n end\n else\n env.out.print(\"Errored while togglin'!\")\n end\n be printn(onlyOpen:Bool)=>\n try\n for i in doors.keys() do\n if onlyOpen and not doors(i)? then\n continue\n end\n env.out.print(\"Door \" + i.string() + \" is \" +\n if doors(i)? then\n \"Open\"\n else\n \"closed\"\n end)\n end\n else\n env.out.print(\"Error!\")\n end\n true\n\nactor OptimizedToggler\n let doors:Array[Bool]\n let env:Env\n new create(count:USize,_env:Env)=>\n env=_env\n doors=Array[Bool](count)\n while doors.size()\n var i:USize=0\n if alreadydone then\n return\n end\n try\n doors.update(0,true)?\n doors.update(1,true)?\n while i < doors.size() do\n i=i+1\n let z=i*i\n let x=z*z\n if z > doors.size() then\n break\n else\n doors.update(z,true)?\n end\n if x < doors.size() then\n doors.update(x,true)?\n end\n end\n end\n be printn(onlyOpen:Bool)=>\n try\n for i in doors.keys() do\n if onlyOpen and not doors(i)? then\n continue\n end\n env.out.print(\"Door \" + i.string() + \" is \" +\n if doors(i)? then\n \"Open\"\n else\n \"closed\"\n end)\n end\n else\n env.out.print(\"Error!\")\n end\n true\nactor Main\n new create(env:Env)=>\n var count: USize =100\n try\n let index=env.args.find(\"-n\",0,0,{(l,r)=>l==r})?\n try\n match env.args(index+1)?.read_int[USize]()?\n | (let x:USize, _)=>count=x\n end\n else\n env.out.print(\"You either neglected to provide an argument after -n or that argument was not an integer greater than zero.\")\n return\n end\n end\n if env.args.contains(\"optimized\",{(l,r)=>r==l}) then\n let toggler=OptimizedToggler(count,env)\n var i:USize = 1\n toggler.togglin()\n toggler.printn(env.args.contains(\"onlyopen\", {(l,r)=>l==r}))\n else\n let toggler=Toggler(count,env)\n var i:USize = 1\n while i < count do\n toggler.togglin(i)\n i=i+1\n end\n toggler.printn(env.args.contains(\"onlyopen\", {(l,r)=>l==r}))\n end", "safe": true }, { "filename": "100 doors_54.txt", "content": "-- perfectSquaresUpTo\u00a0:: Int -> [Int]\non perfectSquaresUpTo(n)\n script squared\n -- (Int -> Int)\n on |\u03bb|(x)\n x * x\n end |\u03bb|\n end script\n \n set realRoot to n ^ (1 / 2)\n set intRoot to realRoot as integer\n set blnNotPerfectSquare to not (intRoot = realRoot)\n \n map(squared, enumFromTo(1, intRoot - (blnNotPerfectSquare as integer)))\nend perfectSquaresUpTo\n\non run\n \n perfectSquaresUpTo(100)\n \nend run\n", "safe": true }, { "filename": "100 doors_540.txt", "content": "lvars i;\nlvars doors = {% for i from 1 to 100 do false endfor\u00a0%};\nfor i from 1 to 100 do\n for j from i by i to 100 do\n not(doors(j)) -> doors(j);\n endfor;\nendfor;\n;;; Print state\nfor i from 1 to 100 do\n printf('Door ' >< i >< ' is ' ><\n if doors(i) then 'open' else 'closed' endif, '%s\\n');\nendfor;", "safe": true }, { "filename": "100 doors_541.txt", "content": "for i to 100 do\n lvars root = sqrt(i);\n i; if root = round(root) then ' open' ><; else ' closed' ><; endif; =>\nendfor;", "safe": true }, { "filename": "100 doors_542.txt", "content": "/doors [ 100 { false } repeat ] def\n\n1 1 100 { dup 1 sub exch 99 {\n dup doors exch get not doors 3 1 roll put\n} for } for\ndoors pstack", "safe": true }, { "filename": "100 doors_543.txt", "content": "[true false false true false false false false true false ...<90 doors later>... true]", "safe": true }, { "filename": "100 doors_544.txt", "content": "square=1, i=3\n1 to 100(door):\n if (door == square):\n (\"door\", door, \"is open\") say\n square += i\n i += 2.\n.", "safe": true }, { "filename": "100 doors_545.txt", "content": "$doors = @(0..99)\nfor($i=0; $i -lt 100; $i++) {\n $doors[$i] = 0 # start with all doors closed\n}\nfor($i=0; $i -lt 100; $i++) {\n $step = $i + 1\n for($j=$i; $j -lt 100; $j = $j + $step) {\n $doors[$j] = $doors[$j] -bxor 1\n }\n}\nforeach($doornum in 1..100) {\n if($doors[($doornum-1)] -eq $true) {\"$doornum open\"}\n else {\"$doornum closed\"}\n}", "safe": true }, { "filename": "100 doors_546.txt", "content": "function Get-DoorState($NumberOfDoors)\n{\n begin \n {\n $Doors = @()\n $Multiple = 1\n }\n\n process\n {\n for ($i = 1; $i -le $NumberOfDoors; $i++)\n {\n $Door = [pscustomobject]@{\n Name = $i\n Open = $false\n }\n\n $Doors += $Door \n }\n\n While ($Multiple -le $NumberOfDoors)\n {\n\t Foreach ($Door in $Doors)\n\t {\n\t if ($Door.name\u00a0% $Multiple -eq 0)\n {\n\t If ($Door.open -eq $False){$Door.open = $True}\n\t Else {$Door.open = $False}\n\t }\n\t }\n\t\t\t\n $Multiple++\n }\n }\n\n end {$Doors}\n}", "safe": true }, { "filename": "100 doors_547.txt", "content": "$doors = 1..100 | ForEach-Object {0}\n1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_\u00a0% $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { \"door opened\" } else { \"door closed\" } }", "safe": true }, { "filename": "100 doors_548.txt", "content": "$doors = 1..100 | ForEach-Object {0}\n$visited = 1..100\n1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_\u00a0% $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { \"door opened\" } else { \"door closed\" } }", "safe": true }, { "filename": "100 doors_549.txt", "content": "1..100|foreach-object {$pipe += \"toggle $_ |\"} -begin {$pipe=\"\"}\nfilter toggle($pass) {$_.door = $_.door -xor\u00a0!($_.index\u00a0% $pass);$_}\ninvoke-expression \"1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host\"", "safe": true }, { "filename": "100 doors_55.txt", "content": "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\n", "safe": true }, { "filename": "100 doors_550.txt", "content": "Workflow Calc-Doors {\n Foreach \u2013parallel ($number in 1..100) {\n \"Door \" + $number.ToString(\"0000\") + \": \" + @{$true=\"Closed\";$false=\"Open\"}[([Math]::pow($number, 0.5)%1) -ne 0]\n }\n}\nCalc-Doors | sort", "safe": true }, { "filename": "100 doors_551.txt", "content": "1..10|%{\"Door \"+ $_*$_ + \" is open\"}", "safe": true }, { "filename": "100 doors_552.txt", "content": "boolean[] doors = new boolean[100];\n\nvoid setup() {\n for (int i = 0; i < 100; i++) {\n doors[i] = false;\n }\n for (int i = 1; i < 100; i++) {\n for (int j = 0; j < 100; j += i) {\n doors[j] = !doors[j];\n }\n }\n println(\"Open:\");\n for (int i = 1; i < 100; i++) {\n if (doors[i]) {\n println(i);\n }\n }\n exit();\n}", "safe": true }, { "filename": "100 doors_553.txt", "content": "Open:\n1\n4\n9\n16\n25\n36\n49\n64\n81", "safe": true }, { "filename": "100 doors_554.txt", "content": "setup <- function() {\n for(door in doors(100, 100)) {\n stdout$print(paste(door, \"\"))\n }\n}\n\ndoors <- function(ndoors=100,passes=100) {\n doors <- rep(FALSE,ndoors)\n for (ii in seq(1,passes)) {\n mask <- seq(0,ndoors,ii)\n doors[mask] <- !doors[mask] \n }\n return (which(doors == TRUE))\n}", "safe": true }, { "filename": "100 doors_555.txt", "content": "1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_556.txt", "content": "enableextensions \nenabledelayedexpansion\neditvar /newvar /value=0 /title=closed\neditvar /newvar /value=1 /title=open\neditvar /newvar /range=1-100 /increment=1 /from=2\neditvar /newvar /value=2 /title=next\n:doors\nfor /alloccurrences (!next!-!102!) do editvar /modify /value=-open-\neditvar /modify /value=-next-=+1\nif -next- /hasvalue=100 goto :cont else goto :doors\n:cont\nprintline !1!-!102!\nstoptask", "safe": true }, { "filename": "100 doors_557.txt", "content": "main\u00a0:-\n forall(between(1,100,Door), ignore(display(Door))).\n\n% show output if door is open after the 100th pass\ndisplay(Door)\u00a0:-\n status(Door, 100, open),\n format(\"Door ~d is open~n\", [Door]).\n\n% true if Door has Status after Pass is done\nstatus(Door, Pass, Status)\u00a0:-\n Pass > 0,\n Remainder is Door mod Pass,\n toggle(Remainder, OldStatus, Status),\n OldPass is Pass - 1,\n status(Door, OldPass, OldStatus).\nstatus(_Door, 0, closed).\n\ntoggle(Remainder, Status, Status)\u00a0:-\n Remainder > 0.\ntoggle(0, open, closed).\ntoggle(0, closed, open).", "safe": true }, { "filename": "100 doors_558.txt", "content": "doors_unoptimized(N)\u00a0:-\n\tlength(L, N),\n\tmaplist(init, L),\n\tdoors(N, N, L, L1),\n\taffiche(N, L1).\n\ninit(close).\n\ndoors(Max, 1, L, L1)\u00a0:-\n\t!,\n inverse(1, 1, Max, L, L1).\n\ndoors(Max, N, L, L1)\u00a0:-\n\tN1 is N - 1,\n\tdoors(Max, N1, L, L2),\n\tinverse(N, 1, Max, L2, L1).\n\n\ninverse(N, Max, Max, [V], [V1])\u00a0:-\n\t!,\n\t0 =:= Max mod N -> inverse(V, V1); V1 = V.\n\ninverse(N, M, Max, [V|T], [V1|T1])\u00a0:-\n\tM1 is M+1,\n\tinverse(N, M1, Max, T, T1),\n\t( 0 =:= M mod N -> inverse(V, V1); V1 = V).\n\n\ninverse(open, close).\ninverse(close, open).\n\naffiche(N, L)\u00a0:-\n\tforall(between(1, N, I),\n\t ( nth1(I, L, open) -> format('Door ~w is open.~n', [I]); true)).", "safe": true }, { "filename": "100 doors_559.txt", "content": "doors(Num, Passes)\u00a0:-\n forall(( everyNth(1,Passes,1,Pass)\n , forall((everyNth(Pass,Num,Pass,Door), toggle(Door)))\n ))\n , show(Num)\n .\n\n\ntoggle(Door)\u00a0:-\n Opened = opened(Door)\n , ( clause(Opened,_) -> retract(Opened)\n \u00a0; asserta(Opened)\n ).\n\n\nshow(Num)\u00a0:-\n forall(( between(1,Num,Door)\n , (opened(Door) -> State = opened\u00a0; State = closed)\n , write(Door), write(' '), write(State), nl\n )).\n\n\n% utils\nforall(X)\u00a0:- findall(_, X, _).\n\neveryNth(From,To,Step,X)\u00a0:-\n From =< To\n , ( X = From\u00a0; From1 is From + Step, everyNth(From1,To,Step,X) )\n .\n\nmain\u00a0:- doors(100,100), halt.", "safe": true }, { "filename": "100 doors_56.txt", "content": "openshut(n):\n for x in [1..n]\n x%n==0\n\npass(n):\n if n==100\n openshut(n)\n else\n openshut(n) xor pass(n+1)\n\n100doors():\n pass(1) -> io", "safe": true }, { "filename": "100 doors_560.txt", "content": "doors_optimized(N)\u00a0:-\n\tMax is floor(sqrt(N)),\n\tforall(between(1, Max, I),\n\t ( J is I*I,format('Door ~w is open.~n',[J]))).", "safe": true }, { "filename": "100 doors_561.txt", "content": ";;; find the first few squares via the unoptimised door flipping method\nPROGRAM hundredDoors\nINCLUDE LIBRARY\nCON INT doorMax = 100\nBYTE door [ doorMax + 1 ]\u00a0; door( i ) is true if open, false if closed\nWORD i\nBYTE j\nBEGIN\nFOR i = 0 TO doorMax \u00a0; set all doors to closed\n door[ i ] = false\nFOR i = 1 TO doorMax \u00a0; repeatedly flip the doors\n j = i:<\n WHILE j <= doorMax\n door[ j ] = not door[ j ]\n j = j + i:<\nFOR i = 1 TO doorMax \u00a0; display the results\n IF door[ i ]\n OUTPUT \" #W\", i\nOUTPUT \"#C\"\nEND", "safe": true }, { "filename": "100 doors_562.txt", "content": "using system;\n\n// initialize doors as pairs: number, status where 0 means open\nlet doors = zip (1..100) (repeat 1);\n\ntoogle (x,y) = x,~y;\n\ntoogleEvery n d = map (tooglep n) d with\n tooglep n d@((x,_)) = toogle d if ~(x mod n);\n = d otherwise; end;\n\n// show description of given doors\nstatus (n,x) = (str n) + (case x of\n 1 = \" close\";\n 0 = \" open\"; end);\n\nlet result = foldl (\\a n -> toogleEvery n a) doors (1..100);\n\n// pretty print the result (only open doors)\nshowResult = do (puts.status) final when\n final = filter open result with\n open (_,x) = ~x;\n end; end;", "safe": true }, { "filename": "100 doors_563.txt", "content": " \n> showResult;\n1 open\n4 open\n9 open\n16 open\n25 open\n...\n", "safe": true }, { "filename": "100 doors_564.txt", "content": "100Doors.pd\n\n#N canvas 241 375 414 447 10;\n#X obj 63 256 expr doors[$f1] = doors[$f1] ^ 1;\n#X msg 83 118 \\; doors const 0;\n#X msg 44 66 bang;\n#X obj 44 92 t b b b;\n#X obj 43 28 table doors 101;\n#X obj 44 360 sel 0;\n#X obj 44 336 expr if (doors[$f1] == 1 \\, $f1 \\, 0);\n#X obj 63 204 t b f f;\n#X text 81 66 run;\n#X obj 71 384 print -n;\n#X text 132 310 print results (open doors);\n#X obj 63 179 loop 1 100 1;\n#X obj 63 231 loop 1 100 1;\n#X obj 44 310 loop 1 100 1;\n#X text 148 28 create array;\n#X text 151 180 100 passes;\n#X text 179 123 set values to 0;\n#X connect 2 0 3 0;\n#X connect 3 0 13 0;\n#X connect 3 1 11 0;\n#X connect 3 2 1 0;\n#X connect 5 1 9 0;\n#X connect 6 0 5 0;\n#X connect 7 0 12 0;\n#X connect 7 1 12 1;\n#X connect 7 2 12 3;\n#X connect 11 0 7 0;\n#X connect 12 0 0 0;\n#X connect 13 0 6 0;\n\nloop.pd\n\n#N canvas 656 375 427 447 10;\n#X obj 62 179 until;\n#X obj 102 200 f;\n#X obj 62 89 inlet;\n#X obj 303 158 f \\$3;\n#X obj 270 339 outlet;\n#X obj 223 89 inlet;\n#X obj 138 89 inlet;\n#X obj 324 89 inlet;\n#X obj 117 158 f \\$1;\n#X text 323 68 step;\n#X obj 202 158 f \\$2;\n#X obj 62 118 t b b b b;\n#X obj 270 315 spigot;\n#X obj 89 314 sel 0;\n#X obj 137 206 +;\n#X obj 102 237 expr $f1 \\; if ($f3 > 0 \\, if ($f1 > $f2 \\, 0 \\, 1)\n\\, if ($f3 < 0 \\, if ($f1 < $f2 \\, 0 \\, 1) \\, 0)), f 34;\n#X text 63 68 run;\n#X text 136 68 start;\n#X text 227 68 end;\n#X text 58 31 loop (abstraction);\n#X connect 0 0 1 0;\n#X connect 1 0 14 0;\n#X connect 1 0 15 0;\n#X connect 2 0 11 0;\n#X connect 3 0 14 1;\n#X connect 3 0 15 2;\n#X connect 5 0 10 1;\n#X connect 6 0 8 1;\n#X connect 7 0 3 1;\n#X connect 8 0 1 1;\n#X connect 10 0 15 1;\n#X connect 11 0 0 0;\n#X connect 11 1 8 0;\n#X connect 11 2 10 0;\n#X connect 11 3 3 0;\n#X connect 12 0 4 0;\n#X connect 13 0 0 1;\n#X connect 14 0 1 1;\n#X connect 15 0 12 0;\n#X connect 15 1 12 1;\n#X connect 15 1 13 0;", "safe": true }, { "filename": "100 doors_565.txt", "content": "Dim doors.i(100)\n \nFor x = 1 To 100\n y = x\n While y <= 100\n doors(y) = 1 - doors(y)\n y + x\n Wend\nNext\n \nOpenConsole()\nPrintN(\"Following Doors are open:\")\nFor x = 1 To 100\n If doors(x)\n Print(Str(x) + \", \")\n EndIf\nNext\nInput()", "safe": true }, { "filename": "100 doors_566.txt", "content": "OpenConsole()\nPrintN(\"Following Doors are open:\")\nFor i = 1 To 100\n root.f = Sqr(i)\n If root = Int(root)\n \tPrint (Str(i) + \", \")\n EndIf\nNext \nInput()", "safe": true }, { "filename": "100 doors_567.txt", "content": "Following Doors are open:\n1, 4, 9, 16, 25, 36, 49, 64, 81, 100,", "safe": true }, { "filename": "100 doors_568.txt", "content": "data Door:\n | open\n | closed\nend\n \nfun flip-door(d\u00a0:: Door) -> Door:\n cases(Door) d:\n | open => closed\n | closed => open\n end\nend\n \n\nfun flip-doors(doors\u00a0:: List) -> List:\n doc:```Given a list of door positions, repeatedly switch the positions of\n every nth door for every nth pass, and return the final list of door\n positions```\n for fold(flipped-doors from doors, n from range(1, doors.length() + 1)):\n for map_n(m from 1, d from flipped-doors):\n if num-modulo(m, n) == 0:\n flip-door(d)\n else:\n d\n end\n end\n end\nwhere:\n flip-doors([list: closed, closed, closed]) is\n [list: open, closed, closed]\n\n flip-doors([list: closed, closed, closed, closed]) is\n [list: open, closed, closed, open]\n\n flip-doors([list: closed, closed, closed, closed, closed, closed]) is\n [list: open, closed, closed, open, closed, closed]\n\n closed-100 = for map(_ from range(1, 101)): closed end\n answer-100 = for map(n from range(1, 101)):\n if num-is-integer(num-sqrt(n)): open\n else: closed\n end\n end\n\n flip-doors(closed-100) is answer-100\nend\n\nfun find-indices
(pred\u00a0:: (A -> Boolean), xs\u00a0:: List) -> List:\n doc:```Given a list and a predicate function, produce a list of index\n positions where there's a match on the predicate```\n ps = map_n(lam(n,e): if pred(e): n else: -1 end end, 1, xs)\n ps.filter(lam(x): x >= 0 end)\nwhere:\n find-indices((lam(i): i == true end), [list: true,false,true]) is [list:1,3]\nend\n\n\nfun run(n):\n doc:```Given a list of doors that are closed, make repeated passes \n over the list, switching the positions of every nth door for \n each nth pass. Return a list of positions in the list where the\n door is Open.```\n doors = repeat(n, closed)\n ys = flip-doors(doors)\n find-indices((lam(y): y == open end), ys)\nwhere:\n run(4) is [list: 1,4]\nend\n \nrun(100)", "safe": true }, { "filename": "100 doors_569.txt", "content": "doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\"\u00a0% (i+1), 'open' if doors[i] else 'close')", "safe": true }, { "filename": "100 doors_57.txt", "content": "use std, array\n\nclose all doors\nfor each pass from 1 to 100\n for (door = pass) (door <= 100) (door += pass)\n toggle door\n\nlet int pass, door.\n\n.: close all doors\u00a0:. {memset doors 0 size of doors}\n.:toggle :. { \u00a0!!(doors[door - 1]) }\n\nlet doors be an array of 100 bool\n\nfor each door from 1 to 100\n printf \"#%.3d %s\\n\" door (doors[door - 1])\u00a0? \"[ ]\", \"[X]\"", "safe": true }, { "filename": "100 doors_570.txt", "content": "for i in xrange(1, 101):\n root = i ** 0.5\n print \"Door %d:\"\u00a0% i, 'open' if root == int(root) else 'close'", "safe": true }, { "filename": "100 doors_571.txt", "content": "print '\\n'.join(['Door %s is %s'\u00a0% (i, ('closed', 'open')[(i**0.5).is_integer()]) for i in xrange(1, 101)])", "safe": true }, { "filename": "100 doors_572.txt", "content": "print '\\n'.join('Door %s is %s'\u00a0% (i, 'closed' if i**0.5\u00a0% 1 else 'open') for i in range(1, 101))", "safe": true }, { "filename": "100 doors_573.txt", "content": "for i in range(1, 101):\n if i**0.5\u00a0% 1:\n state='closed'\n else:\n state='open'\n print(\"Door {}:{}\".format(i, state))", "safe": true }, { "filename": "100 doors_574.txt", "content": "for i in range(1,11): print(\"Door %s is open\"\u00a0% i**2)", "safe": true }, { "filename": "100 doors_575.txt", "content": "`closed`open(100#0b){@[x;where y;not]}/100#'(til[100]#'0b),'1b", "safe": true }, { "filename": "100 doors_576.txt", "content": "`closed`open (1+til 100) in {x*x} 1+til 10", "safe": true }, { "filename": "100 doors_577.txt", "content": "@[100#`closed; -1+{x*x}1+til 10;\u00a0:; `open]", "safe": true }, { "filename": "100 doors_578.txt", "content": "Const Opened = -1, Closed = 0\nDim Doors(1 To 100) As Integer, Passes As Integer, Index As Integer\nRem Normal implementation\nPrint \"100doors Normal method\"\nFor Passes = 1 To 100 Step 1\n Doors(Passes) = Closed\nNext Passes\nFor Passes = 1 To 100 Step 1\n For Index = 0 To 100 Step Passes\n If Index > 100 Then Exit For\n If Index > 0 Then If Doors(Index) = Opened Then Doors(Index) = Closed Else Doors(Index) = Opened\n Next Index\nNext Passes\nPrint \"OPEN DOORS after 100th passes\"\nFor Passes = 1 To 100 Step 1\n If Doors(Passes) = Opened Then Print Passes; \" \";\nNext\n\nRem Alternative solution of perfect squares\n\nPrint \"Alternative method\"\nPasses = 0\nFor Passes = 1 To 100 Step 1\n Doors(Passes) = Closed\nNext Passes\nFor Passes = 1 To 100 Step 1\n If Sqr(Passes) = Int(Sqr(Passes)) Then Doors(Passes) = Opened\nNext\nPrint \"Opened doors found by SQR method\"\nFor Passes = 1 To 100 Step 1\n If Doors(Passes) = Opened Then Print Passes; \" \";\nNext Passes\nEnd", "safe": true }, { "filename": "100 doors_579.txt", "content": "/O> [ bit ^ ] is toggle ( f n --> f )\n... \n... [ 0\n... 100 times\n... [ i^ 1+ swap\n... 101 times\n... [ i^ toggle over step ]\n... nip ] ] is toggledoors ( --> f )\n... \n... [ 100 times\n... [ 1 >> dup 1 &\n... if [ i^ 1+ echo sp ] ]\n... drop ] is echodoors ( f --> )\n... \n... toggledoors\n... say \" These doors are open: \" echodoors cr\n... say \" The rest are closed.\" cr\n... \n These doors are open: 1 4 9 16 25 36 49 64 81 100 \n The rest are closed.\n\nStack empty.", "safe": true }, { "filename": "100 doors_58.txt", "content": "/* ARM assembly Raspberry PI */\n/* program 100doors.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \"The door \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\n .asciz \"is open.\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \nstTableDoors:\t.skip 4 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n @ display first line\n ldr r3,iAdrstTableDoors @ table address\n mov r5,#1 \n1:\n mov r4,r5\n2: @ begin loop\n ldr r2,[r3,r4,lsl #2] @ read doors index r4\n cmp r2,#0\n moveq r2,#1 @ if r2 = 0 1 -> r2\n movne r2,#0 @ if r2 = 1 0 -> r2\n str r2,[r3,r4,lsl #2] @ store value of doors\n add r4,r5 @ increment r4 with r5 value\n cmp r4,#NBDOORS @ number of doors\u00a0?\n ble 2b @ no -> loop\n add r5,#1 @ increment the increment\u00a0!!\n cmp r5,#NBDOORS @ number of doors\u00a0?\n ble 1b @ no -> loop\n\n @ loop display state doors\n mov r4,#0 \n3:\n ldr r2,[r3,r4,lsl #2] @ read state doors r4 index\n cmp r2,#0\n beq 4f\n mov r0,r4 @ open -> display message\n ldr r1,iAdrsMessValeur @ display value index\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n4:\n add r4,#1\n cmp r4,#NBDOORS\n ble 3b @ loop\n \n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrstTableDoors:\t\t.int stTableDoors\niAdrsMessResult:\t\t.int sMessResult\n\n/******************************************************************/\n/* display text with size calculation */ \n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t @ address message in r1 \n mov r0,#STDOUT \t\t @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ \n bx lr @ return \n/******************************************************************/\n/* Converting a register to a decimal unsigned */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n // and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n // and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\t\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\t\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n //mov r3,#0xCCCD @ r3 <- magic_number lower @ for Raspberry pi 3\n //movt r3,#0xCCCC @ r3 <- magic_number upper @ for Raspberry pi 3\n ldr r3,iMagicNumber @ for Raspberry pi 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: .int 0xCCCCCCCD", "safe": true }, { "filename": "100 doors_580.txt", "content": "doors_puzzle <- function(ndoors, passes = ndoors) {\n doors <- logical(ndoors)\n for (ii in seq(passes)) {\n mask <- seq(ii, ndoors, ii)\n doors[mask] <- !doors[mask]\t\n }\n which(doors)\n}\n\ndoors_puzzle(100)", "safe": true }, { "filename": "100 doors_581.txt", "content": "x <- rep(1, 100)\nfor (i in 1:100-1) {\n x <- xor(x, rep(c(rep(0,i),1), length.out=100))\n}\nwhich(!x)", "safe": true }, { "filename": "100 doors_582.txt", "content": "doors_puzzle <- function(ndoors=100,passes=100) {\nnames(which(table(unlist(sapply(1:passes, function(X) seq(0, ndoors, by=X))))\u00a0%% 2 == 1))\n}\n\ndoors_puzzle()", "safe": true }, { "filename": "100 doors_583.txt", "content": "H=100\nf=rep(F,H)\nwhich(Reduce(function(d,n) xor(replace(f,seq(n,H,n),T),d), 1:H, f))", "safe": true }, { "filename": "100 doors_584.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_585.txt", "content": "#lang racket\n\n;; Applies fun to every step-th element of seq, leaving the others unchanged.\n(define (map-step fun step seq)\n (for/list ([elt seq] [i (in-naturals)])\n ((if (zero? (modulo i step)) fun values) elt)))\n\n(define (toggle-nth n seq)\n (map-step not n seq))\n\n(define (solve seq)\n (for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)])\n (toggle-nth pass result)))\n\n(for ([door (solve (make-vector 101 #f))] [index (in-naturals)]\n #:when (and door (> index 0)))\n (printf \"~a is open~%\" index))", "safe": true }, { "filename": "100 doors_586.txt", "content": "#lang racket\n(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x)))\n (printf \"~a is open\\n\" x))", "safe": true }, { "filename": "100 doors_587.txt", "content": "#lang slideshow\n(define-syntax-rule (vector-neg! vec pos)\n (vector-set! vec pos (not (vector-ref vec pos))))\n\n(define (make-doors)\n (define doors (make-vector 100 #f))\n (for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j))\n doors)\n\n(displayln (list->string (for/list ([d (make-doors)]) (if d #\\o #\\-))))\n\n(define closed-door (inset (filled-rectangle 4 20) 2))\n(define open-door (inset (rectangle 4 20) 2))\n\n(for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)])\n (hc-append doors (if open? open-door closed-door)))", "safe": true }, { "filename": "100 doors_588.txt", "content": "my @doors = False xx 101;\n \n(.=not for @doors[0, $_ ... 100]) for 1..100;\n \nsay \"Door $_ is \", [ @doors[$_] ] for 1..100;", "safe": true }, { "filename": "100 doors_589.txt", "content": "say \"Door $_ is open\" for map {$^n ** 2}, 1..10;", "safe": true }, { "filename": "100 doors_59.txt", "content": "/*********************************************/\n/* optimized version */\n/*********************************************/\n/* ARM assembly Raspberry PI */\n/* program 100doors.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \"The door \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\n .asciz \"is open.\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n @ display first line\n mov r5,#3 @ start value of increment\n mov r4,#1 @ start doors\n @ loop display state doors\n1:\n mov r0,r4 @ open -> display message\n ldr r1,iAdrsMessValeur @ display value index\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r4,r5 @ add increment\n add r5,#2 @ new increment\n cmp r4,#NBDOORS\n ble 1b @ loop\n \n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @ restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrsMessResult:\t\t.int sMessResult\n\n/******************************************************************/\n/* display text with size calculation */ \n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t @ address message in r1 \n mov r0,#STDOUT \t\t @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ \n bx lr @ return \n/******************************************************************/\n/* Converting a register to a decimal unsigned */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\t\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\t\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n //mov r3,#0xCCCD @ r3 <- magic_number lower @ for raspberry 3\n //movt r3,#0xCCCC @ r3 <- magic_number upper @ for raspberry 3\n ldr r3,iMagicNumber @ for raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: .int 0xCCCCCCCD", "safe": true }, { "filename": "100 doors_590.txt", "content": "say 'Door $_ is open' for (1..10)\u00bb\u00b2;", "safe": true }, { "filename": "100 doors_591.txt", "content": " say \"Door $_ is open\" for 1..10 X** 2;", "safe": true }, { "filename": "100 doors_592.txt", "content": "say \"Door $_ is \", [.sqrt == .sqrt.floor] for 1..100;", "safe": true }, { "filename": "100 doors_593.txt", "content": "sub output( @arr, $max ) {\n my $output = 1;\n for 1..^$max -> $index {\n\tif @arr[$index] {\n\t printf \"%4d\", $index;\n\t say '' if $output++\u00a0%% 10;\n\t}\n }\n say '';\n}\n\nsub MAIN ( Int\u00a0:$doors = 100 ) {\n my $doorcount = $doors + 1;\n my @door[$doorcount] = 0 xx ($doorcount);\n \n INDEX:\n for 1...^$doorcount -> $index {\n # flip door $index & its multiples, up to last door.\n #\n\tfor ($index, * + $index ... *)[^$doors] -> $multiple {\n\t next INDEX if $multiple > $doors;\n\t @door[$multiple] = @door[$multiple]\u00a0?? 0\u00a0!! 1;\n\t}\n }\n output @door, $doors+1;\n}", "safe": true }, { "filename": "100 doors_594.txt", "content": "$ ./100_doors.pl6 -doors=100\n 1 4 9 16 25 36 49 64 81\n", "safe": true }, { "filename": "100 doors_595.txt", "content": "dim x as integer, y as integer\ndim door(1 to 100) as byte\n\n'initialize array\nfor x = 1 to 100\u00a0: door(x) = 0\u00a0: next\n\n'set door values\nfor y = 1 to 100\n for x = y to 100 step y\n door(x) = not door(x)\n next x\nnext y\n\n'print result\nfor x = 1 to 100\n if door(x) then print \"Door \" + str$(x) + \" = open\"\nnext \n\nwhile inkey$=\"\":wend\nend", "safe": true }, { "filename": "100 doors_596.txt", "content": "Door 1 = open\nDoor 4 = open\nDoor 9 = open\nDoor 16 = open\nDoor 25 = open\nDoor 36 = open\nDoor 49 = open\nDoor 64 = open\nDoor 81 = open\nDoor 100 = open", "safe": true }, { "filename": "100 doors_597.txt", "content": "doors: array/initial 100 'closed\nrepeat i 100 [\n door: at doors i\n forskip door i [change door either 'open = first door ['closed] ['open]]\n]", "safe": true }, { "filename": "100 doors_598.txt", "content": "doors: array/initial 100 'closed\nrepeat i 10 [doors/(i * i): 'open]", "safe": true }, { "filename": "100 doors_599.txt", "content": "Red [\n Purpose: \"100 Doors Problem (Perfect Squares)\"\n Author: \"Barry Arthur\"\n Date: \"07-Oct-2016\"\n]\ndoors: make vector! [char! 8 100]\nrepeat i 100 [change at doors i #\".\"]\n\nrepeat i 100 [\n j: i\n while [j <= 100] [\n door: at doors j\n change door either #\"O\" = first door [#\".\"] [#\"O\"]\n j: j + i\n ]\n]\n\nrepeat i 10 [\n print copy/part at doors (i - 1 * 10 + 1) 10\n]", "safe": true }, { "filename": "100 doors_6.txt", "content": "; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html\n; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.\n; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC\n;\n; Notes:\n; Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will \n; be directly shown as pixels in the display.\n; $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops.\n; Y register holds Stride\n; X register holds Index\n; Zero Page address $01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction.\n\n \u00a0; First, zero door array\n LDA #00\n LDX #100\nZ_LOOP:\n STA 200,X\n DEX\n BNE Z_LOOP\n STA 200,X\n\n \u00a0; Now do doors repeated open/close\n LDY #01 \u00a0; Initial value of Stride\nS_LOOP:\n CPY #101\n BCS S_DONE\n TYA \u00a0; Initial value of Index\nI_LOOP:\n CMP #101\n BCS I_DONE\n TAX \u00a0; Use as Door array index\n INC $200,X \u00a0; Toggle bit 0 to reverse state of door\n STY 01 \u00a0; Add stride (Y) to index (X, via A)\n ADC 01\n BCC I_LOOP\nI_DONE:\n INY\n BNE S_LOOP\nS_DONE:\n\n \u00a0; Finally, format array values for output: 0 for closed, 1 for open\n LDX #100\nC_LOOP:\n LDA $200,X\n AND #$01\n STA $200,X\n DEX\n BNE C_LOOP", "safe": true }, { "filename": "100 doors_60.txt", "content": "isOpen: map 1..101 => false\n \nloop 1..100 'pass ->\n\tloop (range.step:pass pass 100) 'door [\n\t\tisOpen\\[door]: not? isOpen\\[door]\n\t]\n\nloop 1..100 'x ->\n\tif isOpen\\[x] [\n\t\tprint [\"Door\" x \"is open.\"]\n\t]\n", "safe": true }, { "filename": "100 doors_600.txt", "content": "Red [\"Doors\"]\n\ndoors: make bitset! len: 100\nrepeat step len [\n\trepeat n to-integer len / step [\n\t\tm: step * n \n\t\tdoors/:m: not doors/:m\n\t]\n]\nrepeat n len [if doors/:n [print n]]", "safe": true }, { "filename": "100 doors_601.txt", "content": "$ENTRY Go {\n = >>;\n};\n\nNDoors { = 100; };\nDoors { = Closed>; };\n\nRepeat {\n 0 s.val =\u00a0;\n s.N s.val = s.val s.val>\u00a0;\n}; \n\nToggle {\n 1 Closed e.rest = Open e.rest;\n 1 Open e.rest = Closed e.rest;\n s.N s.door e.rest = s.door e.rest>;\n};\n \nPass {\n s.pass s.door e.doors, >: '+'\n = e.doors;\n s.pass s.door e.doors\n = >;\n};\n\nWalk {\n s.pass e.doors, >: '+' \n = e.doors;\n s.pass e.doors\n = >;\n};\n\nShow {\n s.N Open e.rest = \n e.rest>;\n s.N Closed e.rest = e.rest>;\n s.N =\u00a0;\n};", "safe": true }, { "filename": "100 doors_602.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100 doors_603.txt", "content": "relation door, state\nset i = 1\nwhile i <= 100\ninsert i, 1\nset i = i+1\nend while\nset i = 2\nwhile i <= 100\nupdate state = 1-state where not (door mod i)\nset i = i+1\nend while\nupdate state = \"open\" where state\nupdate state = \"closed\" where state\u00a0!== \"open\"\nprint", "safe": true }, { "filename": "100 doors_604.txt", "content": ":doors (n-) [ #1 repeat dup-pair n:square gt? 0; drop dup n:square n:put sp n:inc again ] do drop-pair\u00a0;\n#100 doors", "safe": true }, { "filename": "100 doors_605.txt", "content": "/*REXX pgm solves the 100 doors puzzle, doing it the hard way by opening/closing doors.*/\nparse arg doors . /*obtain the optional argument from CL.*/\nif doors=='' | doors==\",\" then doors=100 /*not specified? Then assume 100 doors*/\n /* 0 = the door is closed. */\n /* 1 = \" \" \" open. */\ndoor.=0 /*assume all doors are closed at start.*/\n do #=1 for doors /*process a pass\u2500through for all doors.*/\n do j=# by # to doors /* \u00b7\u00b7\u00b7 every Jth door from this point.*/\n door.j= \\door.j /*toggle the \"openness\" of the door. */\n end /*j*/\n end /*#*/\n\nsay 'After ' doors \" passes, the following doors are open:\"\nsay\n do k=1 for doors\n if door.k then say right(k, 20) /*add some indentation for the output. */\n end /*k*/ /*stick a fork in it, we're all done. */", "safe": true }, { "filename": "100 doors_606.txt", "content": "After 100 passes, the following doors are open:\n\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n 100\n", "safe": true }, { "filename": "100 doors_607.txt", "content": "/*REXX pgm solves the 100 doors puzzle, doing it the easy way by calculating squares.*/\nparse arg doors . /*obtain the optional argument from CL.*/\nif doors=='' | doors==\",\" then doors=100 /*not specified? Then assume 100 doors*/\nsay 'After ' doors \" passes, the following doors are open:\"\nsay\n do #=1 while #**2 <= doors /*process easy pass\u2500through (squares).*/\n say right(#**2, 20) /*add some indentation for the output. */\n end /*#*/ /*stick a fork in it, we're all done. */", "safe": true }, { "filename": "100 doors_608.txt", "content": "doors = list(100)\nfor i = 1 to 100\ndoors[i] = false\nnext\n\nFor pass = 1 To 100\n For door = pass To 100\n if doors[door] doors[door] = false else doors[door] = true ok\n door += pass-1\n Next\nNext\n\nFor door = 1 To 100\n see \"Door (\" + door + \") is \"\n If doors[door] see \"Open\" else see \"Closed\" ok\n see nl\nNext", "safe": true }, { "filename": "100 doors_609.txt", "content": "doors = list(100)\nfor i = 1 to 100\ndoors[i] = false\nnext\n\nFor p = 1 To 10\n doors[pow(p,2)] = True\nNext\n\nFor door = 1 To 100\n see \"Door (\" + door + \") is \"\n If doors[door] see \"Open\" else see \"Closed\" ok\n see nl\nNext", "safe": true }, { "filename": "100 doors_61.txt", "content": "Door 1 is open. \nDoor 4 is open. \nDoor 9 is open. \nDoor 16 is open. \nDoor 25 is open. \nDoor 36 is open. \nDoor 49 is open. \nDoor 64 is open. \nDoor 81 is open. \nDoor 100 is open.", "safe": true }, { "filename": "100 doors_610.txt", "content": " \u226a { }\n { 100 } 0 CON \n 1 100 FOR ii\n ii 100 FOR j\n DUP j GET NOT j SWAP PUT ii STEP \n IF DUP ii GET THEN SWAP ii + SWAP END\n NEXT DROP\n\u226b 'DOORS' STO\n", "safe": true }, { "filename": "100 doors_611.txt", "content": "DOORS ( -- { open_doors } ) \n doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n if doors[i} then print(i)\n// clean stack\n\n", "safe": true }, { "filename": "100 doors_612.txt", "content": "1: { 1 4 9 16 25 36 49 64 81 100 }\n", "safe": true }, { "filename": "100 doors_613.txt", "content": "\u226a { } 1 100 FOR ii IF ii \u221a FP NOT THEN ii + END NEXT \u226b\n", "safe": true }, { "filename": "100 doors_614.txt", "content": "doors = Array.new(101,0)\nprint \"Open doors \"\n(1..100).step(){ |i|\n(i..100).step(i) { |d|\n doors[d] = doors[d]^= 1\n if i == d and doors[d] == 1 then\n print \"#{i} \"\n end\n }\n}", "safe": true }, { "filename": "100 doors_615.txt", "content": "Open doors 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_616.txt", "content": "class Door\n attr_reader :state\n\n def initialize\n @state = :closed\n end\n \n def close\n @state = :closed\n end\n\n def open\n @state = :open\n end\n \n def closed?\n @state == :closed\n end\n \n def open?\n @state == :open\n end\n \n def toggle\n if closed? then open else close end\n end\n \n def to_s\n @state.to_s\n end\nend\n\ndoors = Array.new(100) { Door.new }\n1.upto(100) do |multiplier|\n doors.each_with_index do |door, i|\n door.toggle if (i + 1)\u00a0% multiplier == 0\n end\nend\n\ndoors.each_with_index { |door, i| puts \"Door #{i+1} is #{door}.\" }", "safe": true }, { "filename": "100 doors_617.txt", "content": "n = 100\nOpen = \"open\"\nClosed = \"closed\"\ndef Open.toggle\n Closed\nend\ndef Closed.toggle\n Open\nend\ndoors = [Closed] * (n + 1)\nfor mul in 1..n\n for x in (mul..n).step(mul)\n doors[x] = doors[x].toggle\n end\nend\ndoors.each_with_index do |b, i|\n puts \"Door #{i} is #{b}\" if i > 0\nend", "safe": true }, { "filename": "100 doors_618.txt", "content": "n = 100\n(1..n).each do |i| \n puts \"Door #{i} is #{i**0.5 == (i**0.5).round\u00a0? \"open\"\u00a0: \"closed\"}\"\nend", "safe": true }, { "filename": "100 doors_619.txt", "content": "doors = [false] * 100\n100.times do |i|\n (i ... doors.length).step(i + 1) do |j|\n doors[j] = !doors[j]\n end\nend\nputs doors.map.with_index(1){|d,i| \"Door #{i} is #{d\u00a0? 'open'\u00a0: 'closed'}.\"}", "safe": true }, { "filename": "100 doors_62.txt", "content": "var doors = falses(100)\n\nfor a in 1..100: for b in a..a..100:\n doors[b] = not doors[b]\n\nfor a in 1..100:\n print \"Door $a is ${(doors[a])\u00a0? 'open.': 'closed.'}\"\n", "safe": true }, { "filename": "100 doors_620.txt", "content": "Door 1 is open\nDoor 2 is closed\nDoor 3 is closed\nDoor 4 is open\nDoor 5 is closed\nDoor 6 is closed\nDoor 7 is closed\nDoor 8 is closed\nDoor 9 is open\nDoor 10 is closed\nDoor 11 is closed\nDoor 12 is closed\nDoor 13 is closed\nDoor 14 is closed\nDoor 15 is closed\nDoor 16 is open\nDoor 17 is closed\nDoor 18 is closed\nDoor 19 is closed\nDoor 20 is closed\nDoor 21 is closed\nDoor 22 is closed\nDoor 23 is closed\nDoor 24 is closed\nDoor 25 is open\nDoor 26 is closed\nDoor 27 is closed\nDoor 28 is closed\nDoor 29 is closed\nDoor 30 is closed\nDoor 31 is closed\nDoor 32 is closed\nDoor 33 is closed\nDoor 34 is closed\nDoor 35 is closed\nDoor 36 is open\nDoor 37 is closed\nDoor 38 is closed\nDoor 39 is closed\nDoor 40 is closed\nDoor 41 is closed\nDoor 42 is closed\nDoor 43 is closed\nDoor 44 is closed\nDoor 45 is closed\nDoor 46 is closed\nDoor 47 is closed\nDoor 48 is closed\nDoor 49 is open\nDoor 50 is closed\nDoor 51 is closed\nDoor 52 is closed\nDoor 53 is closed\nDoor 54 is closed\nDoor 55 is closed\nDoor 56 is closed\nDoor 57 is closed\nDoor 58 is closed\nDoor 59 is closed\nDoor 60 is closed\nDoor 61 is closed\nDoor 62 is closed\nDoor 63 is closed\nDoor 64 is open\nDoor 65 is closed\nDoor 66 is closed\nDoor 67 is closed\nDoor 68 is closed\nDoor 69 is closed\nDoor 70 is closed\nDoor 71 is closed\nDoor 72 is closed\nDoor 73 is closed\nDoor 74 is closed\nDoor 75 is closed\nDoor 76 is closed\nDoor 77 is closed\nDoor 78 is closed\nDoor 79 is closed\nDoor 80 is closed\nDoor 81 is open\nDoor 82 is closed\nDoor 83 is closed\nDoor 84 is closed\nDoor 85 is closed\nDoor 86 is closed\nDoor 87 is closed\nDoor 88 is closed\nDoor 89 is closed\nDoor 90 is closed\nDoor 91 is closed\nDoor 92 is closed\nDoor 93 is closed\nDoor 94 is closed\nDoor 95 is closed\nDoor 96 is closed\nDoor 97 is closed\nDoor 98 is closed\nDoor 99 is closed\nDoor 100 is open\n", "safe": true }, { "filename": "100 doors_621.txt", "content": "dim doors(100)\nprint \"Open doors \";\nfor i = 1 to 100 \n for door = i to 100 step i\n doors(door) = (doors(door) <> 1)\n if i = door and doors(door) = 1 then print i;\" \";\n next door\nnext i", "safe": true }, { "filename": "100 doors_622.txt", "content": "Open doors 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_623.txt", "content": "fn main() {\n let mut door_open = [false; 100];\n for pass in 1..101 {\n let mut door = pass;\n while door <= 100 {\n door_open[door - 1] = !door_open[door - 1];\n door += pass;\n }\n }\n for (i, &is_open) in door_open.iter().enumerate() {\n println!(\n \"Door {} is {}.\",\n i + 1,\n if is_open { \"open\" } else { \"closed\" }\n );\n }\n}", "safe": true }, { "filename": "100 doors_624.txt", "content": "fn main() {\n let doors = vec![false; 100]\n .iter_mut()\n .enumerate()\n .map(|(door, door_state)| {\n (1..100)\n .into_iter()\n .filter(|pass| (door + 1)\u00a0% pass == 0)\n .map(|_| {\n *door_state =\u00a0!*door_state;\n *door_state\n })\n .last()\n .unwrap()\n })\n .collect::>();\n\n println!(\"{:?}\", doors);\n}", "safe": true }, { "filename": "100 doors_625.txt", "content": "fn main() {\n let squares: Vec<_> = (1..11).map(|n| n * n).collect();\n let is_square = |num| squares.binary_search(&num).is_ok();\n\n for i in 1..101 {\n let state = if is_square(i) { \"open\" } else { \"closed\" };\n println!(\"Door {} is {}\", i, state);\n }\n}", "safe": true }, { "filename": "100 doors_626.txt", "content": "fn main() {\n for i in 1u32..11u32 {\n println!(\"Door {} is open\", i.pow(2));\n }\n}", "safe": true }, { "filename": "100 doors_627.txt", "content": "$constant DOOR_OPEN = 1\n$constant DOOR_CLOSED = 0\n$constant MAX_DOORS = 100\n\nvar i, j = integer\ndim integer doors(MAX_DOORS)\n\nrem - all doors are initially closed\nfor i = 1 to MAX_DOORS\n doors(i) = DOOR_CLOSED\nnext i\n\nrem - cycle through at increasing intervals and flip doors\nfor i = 1 to MAX_DOORS\n for j = i to MAX_DOORS step i\n doors(j) = 1 - doors(j)\n next j\nnext i\n\nrem - report results\nprint \"The open doors are:\"\nfor i = 1 to MAX_DOORS\n if doors(i) = DOOR_OPEN then\n print i;\nnext i\n\nend", "safe": true }, { "filename": "100 doors_628.txt", "content": "The open doors are:\n 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_629.txt", "content": "variable door,\n isOpen = Char_Type [101],\n pass;\n \nfor (door = 1; door <= 100; door++) {\n isOpen[door] = 0;\n}\n \nfor (pass = 1; pass <= 100; pass++) {\n for (door = pass; door <= 100; door += pass) {\n isOpen[door] = not isOpen[door];\n }\n}\n \nfor (door = 1; door <= 100; door++) {\n if (isOpen[door]) {\n print(\"Door \" + string(door) + \":open\");\n } else {\n print(\"Door \" + string(door) + \":close\");\n }\n}", "safe": true }, { "filename": "100 doors_63.txt", "content": "for(int i = 1; i < 100; ++i) {\n if (i % i^2 < 11) {\n write(\"Door \", i^2, suffix=none);\n write(\" is open\");\n }\n }\n", "safe": true }, { "filename": "100 doors_630.txt", "content": "variable open\u00a0:= <<(* --> false)>>;\nfor (pass; 1; pass <= 100)\n for (door_num; pass; door_num <= 100; pass)\n open[door_num]\u00a0:=\u00a0!(open[door_num]);;;\niterate (door_num; [1...100])\n print(\"Door \", door_num, \" is \",\n (open[door_num]\u00a0? \"open.\\n\"\u00a0: \"closed.\\n\"));;", "safe": true }, { "filename": "100 doors_631.txt", "content": "iterate (x; [1...10]) { iterate (y; [(x-1)*(x-1)+1...x*x-1]) { print(\"Door \", y, \" is closed.\\n\"); }; print(\"Door \", x*x, \" is open.\\n\"); };", "safe": true }, { "filename": "100 doors_632.txt", "content": "variable y:=1;for(x;1;x<101)\"Door \"~sprint(x)~\" is \"~(x==y*y?{++y;return\"open\";}:\"closed\")!;", "safe": true }, { "filename": "100 doors_633.txt", "content": "data _null_;\n open=1;\n close=0;\n array Door{100};\n do Pass = 1 to 100;\n do Current = Pass to 100 by Pass;\n if Door{Current} ne open \n then Door{Current} = open;\n else Door{Current} = close;\n end;\n end;\n NumberOfOpenDoors = sum(of Door{*});\n put \"Number of Open Doors: \" NumberOfOpenDoors; \nrun;", "safe": true }, { "filename": "100 doors_634.txt", "content": "class MAIN is\n main is\n doors :ARRAY{BOOL}\u00a0:= #(100);\n loop\n pass::= doors.ind!;\n loop\n i::= pass.stepto!(doors.size - 1, pass + 1);\n doors[i]\u00a0:= ~doors[i];\n end;\n end;\n loop\n #OUT + (doors.ind! + 1) + \" \" + doors.elt! + \"\\n\";\n end;\n end;\nend;", "safe": true }, { "filename": "100 doors_635.txt", "content": "for { i <- 1 to 100\n r = 1 to 100 map (i\u00a0% _ == 0) reduceLeft (_^_) \n } println (i +\" \"+ (if (r) \"open\" else \"closed\"))", "safe": true }, { "filename": "100 doors_636.txt", "content": "def openDoors(length\u00a0: Int = 100) = {\n var isDoorOpen = new Array[Boolean](length)\n\n for (i <- 0 until length) {\n for (j <- i until length by i + 1) {\n isDoorOpen(j) ^= true\n }\n }\n isDoorOpen\n}\n\nval doorState = scala.collection.immutable.Map(false -> \"closed\", true -> \"open\")\nval isDoorOpen = openDoors()\n\nfor (doorNo <- 0 until isDoorOpen.length) {\n println(\"Door %d is %s\".format(doorNo + 1, doorState(isDoorOpen(doorNo))))\n}", "safe": true }, { "filename": "100 doors_637.txt", "content": "val o = 1 to 10 map (i => i * i)\nprintln(\"open: \" + o)\nprintln(\"closed: \" + (1 to 100 filterNot o.contains))", "safe": true }, { "filename": "100 doors_638.txt", "content": "(define *max-doors* 100)\n\n(define (show-doors doors)\n (let door ((i 0)\n (l (vector-length doors)))\n (cond ((= i l) \n (newline))\n (else \n (printf \"~nDoor ~a is ~a\" \n (+ i 1) \n (if (vector-ref doors i) \"open\" \"closed\"))\n (door (+ i 1) l)))))\n\n(define (flip-doors doors)\n (define (flip-all i)\n (cond ((> i *max-doors*) doors)\n (else \n (let flip ((idx (- i 1)))\n (cond ((>= idx *max-doors*) \n (flip-all (+ i 1))) \n (else \n (vector-set! doors idx (not (vector-ref doors idx)))\n (flip (+ idx i))))))))\n (flip-all 1))\n\n(show-doors (flip-doors (make-vector *max-doors* #f)))", "safe": true }, { "filename": "100 doors_639.txt", "content": "(define (optimised-flip-doors doors)\n (define (flip-all i)\n (cond ((> i (floor (sqrt *max-doors*))) doors)\n (else \n (vector-set! doors (- (* i i) 1) #t)\n (flip-all (+ i 1)))))\n (flip-all 1))\n\n(show-doors (optimised-flip-doors (make-vector *max-doors* #f)))", "safe": true }, { "filename": "100 doors_64.txt", "content": "#include \"share/atspre_staload.hats\"\n\nimplement\nmain0((*void*)) = let\n//\nvar A = @[bool][100](false)\nval A = $UNSAFE.cast{arrayref(bool,100)}(addr@A)\n//\nfnx\nloop\n(\n pass: intGte(0)\n)\u00a0: void =\n if pass < 100\n then loop2 (pass, pass)\n // end of [if]\nand\nloop2\n(\n pass: natLt(100), door: intGte(0)\n)\u00a0: void =\n if door < 100\n then (A[door]\u00a0:= ~A[door]; loop2(pass, door+pass+1))\n else loop(pass+1)\n // end of [if]\n//\nfun\nloop3\n(\n door: intGte(0)\n)\u00a0: void =\n if door < 100\n then (\n println!(\"door #\", door+1, \" is \", (if A[door] then \"open\" else \"closed\"): string, \".\");\n loop3(door+1)\n ) (* end of [then] *)\n // end of [if]\n//\nin\n loop(0); loop3 (0)\nend // end of [main0]", "safe": true }, { "filename": "100 doors_640.txt", "content": "(define (N_doors N)\n (define (init)\n (define (str n)\n (if (> n N) '() (cons 0 (str (+ 1 n)))))\n (str 1))\n (define (toggle x str)\n (define (s n lis)\n (define (revert x)\n (if (eq? x 0) 1 0))\n (cond ((null? lis) '())\n ((zero? (remainder n x)) (cons (revert (car lis)) (s (+ n 1) (cdr lis))))\n (else (cons (car lis) (s (+ n 1) (cdr lis))))))\n (s 1 str))\n (define (iterate x lis)\n (if (> x N) lis (iterate (+ x 1) (toggle x lis))))\n (iterate 1 (init)))\n(N_doors 100)", "safe": true }, { "filename": "100 doors_641.txt", "content": "(1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)\n", "safe": true }, { "filename": "100 doors_642.txt", "content": "doors=zeros(1,100);\nfor i = 1:100\n for j = i:i:100\n doors(j) = ~doors(j);\n end\nend\nfor i = 1:100\n if ( doors(i) )\n s = \"open\";\n else\n s = \"closed\";\n end\n printf(\"%d %s\\n\", i, s);\nend", "safe": true }, { "filename": "100 doors_643.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n11 closed\n12 closed\n13 closed\n14 closed\n15 closed\n16 open\n17 closed\n18 closed\n19 closed\n20 closed\n21 closed\n22 closed\n23 closed\n24 closed\n25 open\n26 closed\n27 closed\n28 closed\n29 closed\n30 closed\n31 closed\n32 closed\n33 closed\n34 closed\n35 closed\n36 open\n37 closed\n38 closed\n39 closed\n40 closed\n41 closed\n42 closed\n43 closed\n44 closed\n45 closed\n46 closed\n47 closed\n48 closed\n49 open\n50 closed\n51 closed\n52 closed\n53 closed\n54 closed\n55 closed\n56 closed\n57 closed\n58 closed\n59 closed\n60 closed\n61 closed\n62 closed\n63 closed\n64 open\n65 closed\n66 closed\n67 closed\n68 closed\n69 closed\n70 closed\n71 closed\n72 closed\n73 closed\n74 closed\n75 closed\n76 closed\n77 closed\n78 closed\n79 closed\n80 closed\n81 open\n82 closed\n83 closed\n84 closed\n85 closed\n86 closed\n87 closed\n88 closed\n89 closed\n90 closed\n91 closed\n92 closed\n93 closed\n94 closed\n95 closed\n96 closed\n97 closed\n98 closed\n99 closed\n100 open\n", "safe": true }, { "filename": "100 doors_644.txt", "content": "$ include \"seed7_05.s7i\";\n \nconst proc: main is func\n local\n var array boolean: doorOpen is 100 times FALSE;\n var integer: pass is 0;\n var integer: index is 0;\n var array[boolean] string: closedOrOpen is [boolean] (\"closed\", \"open\");\n begin\n for pass range 1 to 100 do\n for key index range doorOpen do\n if index rem pass = 0 then\n doorOpen[index]\u00a0:= not doorOpen[index];\n end if;\n end for;\n end for;\n for key index range doorOpen do\n write(index lpad 3 <& \" is \" <& closedOrOpen[doorOpen[index]] rpad 7);\n if index rem 5 = 0 then\n writeln;\n end if;\n end for;\n end func;", "safe": true }, { "filename": "100 doors_645.txt", "content": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var integer: index is 0;\n var integer: number is 0;\n var array[boolean] string: closedOrOpen is [boolean] (\"closed\", \"open\");\n begin\n for index range 1 to 100 do\n number\u00a0:= sqrt(index);\n write(index lpad 3 <& \" is \" <& closedOrOpen[number**2 = index] rpad 7);\n if index rem 5 = 0 then\n writeln;\n end if;\n end for;\n end func;", "safe": true }, { "filename": "100 doors_646.txt", "content": " 1 is open 2 is closed 3 is closed 4 is open 5 is closed \n 6 is closed 7 is closed 8 is closed 9 is open 10 is closed \n 11 is closed 12 is closed 13 is closed 14 is closed 15 is closed \n 16 is open 17 is closed 18 is closed 19 is closed 20 is closed \n 21 is closed 22 is closed 23 is closed 24 is closed 25 is open \n 26 is closed 27 is closed 28 is closed 29 is closed 30 is closed \n 31 is closed 32 is closed 33 is closed 34 is closed 35 is closed \n 36 is open 37 is closed 38 is closed 39 is closed 40 is closed \n 41 is closed 42 is closed 43 is closed 44 is closed 45 is closed \n 46 is closed 47 is closed 48 is closed 49 is open 50 is closed \n 51 is closed 52 is closed 53 is closed 54 is closed 55 is closed \n 56 is closed 57 is closed 58 is closed 59 is closed 60 is closed \n 61 is closed 62 is closed 63 is closed 64 is open 65 is closed \n 66 is closed 67 is closed 68 is closed 69 is closed 70 is closed \n 71 is closed 72 is closed 73 is closed 74 is closed 75 is closed \n 76 is closed 77 is closed 78 is closed 79 is closed 80 is closed \n 81 is open 82 is closed 83 is closed 84 is closed 85 is closed \n 86 is closed 87 is closed 88 is closed 89 is closed 90 is closed \n 91 is closed 92 is closed 93 is closed 94 is closed 95 is closed \n 96 is closed 97 is closed 98 is closed 99 is closed 100 is open \n", "safe": true }, { "filename": "100 doors_647.txt", "content": "put false repeated 100 times as a list into Doors100\n\nrepeat 1 to 100\n\tset step to it\n\trepeat step to 100 by step \n\t\tset newValue to not item it of Doors100\n\t\tset item it of Doors100 to newValue\n\tend repeat\nend repeat\n\nput the counter for each item of Doors100 which is true", "safe": true }, { "filename": "100 doors_648.txt", "content": "(1,4,9,16,25,36,49,64,81,100)", "safe": true }, { "filename": "100 doors_649.txt", "content": "import ;\n\nmain:=\n\tlet\n\t\tdoors\u00a0:= flipDoors(duplicate(false, 100), 1);\n\t\topen[i]\u00a0:= i when doors[i];\n\tin\n\t\topen;\n\t\nflipDoors(doors(1), count)\u00a0:=\n\tlet\n\t\tnewDoors[i]\u00a0:= not doors[i] when i mod count = 0 else doors[i];\n\tin\n\t\tdoors when count >= 100 else flipDoors(newDoors, count + 1);", "safe": true }, { "filename": "100 doors_65.txt", "content": "Loop, 100\n Door%A_Index% := \"closed\"\n\nLoop, 100 {\n x := A_Index, y := A_Index\n While (x <= 100)\n {\n CurrentDoor := Door%x%\n If CurrentDoor contains closed\n {\n Door%x% := \"open\"\n x += y\n }\n else if CurrentDoor contains open\n {\n Door%x% := \"closed\"\n x += y\n }\n }\n}\n\nLoop, 100 {\n CurrentDoor := Door%A_Index%\n If CurrentDoor contains open\n Res .= \"Door \" A_Index \" is open`n\"\n}\nMsgBox % Res\n", "safe": true }, { "filename": "100 doors_650.txt", "content": "main\u00a0:= flipDoors([1], 2);\n\nflipDoors(openDoors(1), i)\u00a0:=\n\topenDoors when i * i >= 100 else flipDoors(openDoors ++ [i * i], i + 1);", "safe": true }, { "filename": "100 doors_651.txt", "content": "program hundred_doors;\n\nconst toggle\u00a0:= {['open', 'closed'], ['closed', 'open']};\n\ndoorStates\u00a0:= ['closed'] * 100;\n\n(for interval in [1..100])\n doorStates\u00a0:= [if i mod interval = 0 then\n toggle(prevState) else\n prevState end:\n prevState = doorStates(i)];\nend;\n\n(for finalState = doorStates(i))\n print('door', i, 'is', finalState);\nend;\n\nend program;", "safe": true }, { "filename": "100 doors_652.txt", "content": "program hundred_doors;\n\ndoorStates\u00a0:= (+/ [['closed'] * oddNum with 'open': oddNum in [1,3..17]]);\n\n(for finalState = doorStates(i))\n print('door', i, 'is', finalState);\nend;\n\nend program;", "safe": true }, { "filename": "100 doors_653.txt", "content": "!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! I n i t i a l i z a t i o n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndoors% = 100\n\ndim doorArray?(doors%)\n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! M a i n L o g i c A r e a\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n// Initialize Array\nfor index% = 1 to doors%\n doorArray?(index%) = false\nnext index%\n\n// Execute routine\ntoggle_doors\n\n// Print results\nfor index% = 1 to doors%\n if doorArray?(index%) = true then print index%, ' is open'\nnext index%\n\n\nstop\n\n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! R o u t i n e s\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nroutine toggle_doors\n for index_outer% = 1 to doors%\n for index_inner% = 1 to doors%\n if mod(index_inner%, index_outer%) = 0 then\n doorArray?(index_inner%) = not doorArray?(index_inner%) \n end if\n next index_inner%\n next index_outer%\nend routine\n\n\nend", "safe": true }, { "filename": "100 doors_654.txt", "content": "var doors = []\n\n{ |pass|\n { |i|\n if (pass `divides` i) {\n doors[i]\u00a0:= false -> not!\n }\n } << 1..100\n} << 1..100\n\n{ |i|\n say (\"Door %3d is %s\"\u00a0% (i, doors[i]\u00a0? 'open'\u00a0: 'closed'))\n} << 1..100", "safe": true }, { "filename": "100 doors_655.txt", "content": "{ |i|\n \"Door\u00a0%3d is\u00a0%s\\n\".printf(i, [i.is_sqr])\n} << 1..100", "safe": true }, { "filename": "100 doors_656.txt", "content": "BEGIN\n INTEGER LIMIT = 100, door, stride;\n BOOLEAN ARRAY DOORS(1:LIMIT);\n TEXT intro;\n\n FOR stride\u00a0:= 1 STEP 1 UNTIL LIMIT DO\n FOR door\u00a0:= stride STEP stride UNTIL LIMIT DO\n DOORS(door)\u00a0:= NOT DOORS(door);\n\n intro\u00a0:- \"All doors closed but \";\n FOR door\u00a0:= 1 STEP 1 UNTIL LIMIT DO\n IF DOORS(door) THEN BEGIN\n OUTTEXT(intro); OUTINT(door, 0); intro\u00a0:- \", \"\n END;\n OUTIMAGE\nEND.", "safe": true }, { "filename": "100 doors_657.txt", "content": "All doors closed but 1, 4, 9, 16, 25, 36, 49, 64, 81, 100", "safe": true }, { "filename": "100 doors_658.txt", "content": "define: #a -> (Array newSize: 100).\na infect: [| :_ | False].\n\na keysDo: [| :pass |\n pass to: a indexLast by: pass do: [| :door |\n a at: door infect: #not `er]].\n\na keysAndValuesDo: [| :door :isOpen |\n inform: 'door #'\u00a0; door\u00a0; ' is '\u00a0; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].", "safe": true }, { "filename": "100 doors_659.txt", "content": "define: #a -> (Array newSize: 100).\na infect: [| :_ | False].\n\n0 below: 10 do: [| :door | a at: door squared put: True].\na keysAndValuesDo: [| :door :isOpen |\n inform: 'door #'\u00a0; door\u00a0; ' is '\u00a0; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].", "safe": true }, { "filename": "100 doors_66.txt", "content": "increment := 3, square := 1 \nLoop, 100 \n If (A_Index = square) \n outstring .= \"`nDoor \" A_Index \" is open\" \n ,square += increment, increment += 2 \nMsgBox,, Succesfull, % SubStr(outstring, 2)\n", "safe": true }, { "filename": "100 doors_660.txt", "content": "|a|\na\u00a0:= Array new: 100 .\n1 to: 100 do: [ :i | a at: i put: false ].\n\n1 to: 100 do: [ :pass |\n pass to: 100 by: pass do: [ :door |\n a at: door put: (a at: door) not .\n ]\n].\n\n\"output\"\n1 to: 100 do: [ :door |\n ( 'door #%1 is %2'\u00a0%\n { door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl\n]", "safe": true }, { "filename": "100 doors_661.txt", "content": "|a|\na\u00a0:= (1 to: 100) collect: [ :x | false ].\n1 to: 10 do: [ :i | a at: (i squared) put: true ].\n1 to: 100 do: [ :i |\n ( 'door #%1 is %2'\u00a0% { i . \n (a at: i) ifTrue: [ 'open' ] \n ifFalse: [ 'closed' ] }\n ) displayNl\n]", "safe": true }, { "filename": "100 doors_662.txt", "content": "| m w h smh smw delay closedDoor border subMorphList |\n\nclosedDoor\u00a0:= Color black.\nborder\u00a0:= Color veryLightGray.\ndelay\u00a0:= Delay forMilliseconds: 50.\nw\u00a0:= World bounds corner x.\nh\u00a0:= (World bounds corner y) / 2.\nsmw\u00a0:= w/100.\nsmh\u00a0:= h/2.\n\nm\u00a0:= BorderedMorph new position: 0@h.\nm height: smh; width: w; borderColor: border.\nm color: Color veryLightGray.\n\n1 to: 100 do: [ :pos || sm |\n\tsm\u00a0:= BorderedMorph new height: smh\u00a0; width: smw\u00a0; \n\t\tborderColor: border; color: closedDoor; \n\t\tposition: (smw*pos)@h.\n\tm addMorph: sm asElementNumber: pos].\n\nm openInWorld.\ndelay wait.\nsubMorphList\u00a0:= m submorphs.\n\"display every step\"\n[1 to: 100 do: [ :step |\n\tstep to: 100 by: step do: [ :pos | | subMorph |\n\t\tsubMorph\u00a0:= subMorphList at: pos.\n\t\tsubMorph color: subMorph color negated.\n\t\tdelay wait]]] fork.", "safe": true }, { "filename": "100 doors_663.txt", "content": "x=1!y=3!z=0\nPRINT \"Open doors: \";x;\" \";\nDO\n z=x+y\n PRINT z;\" \";\n x=z\n y=y+2\nUNTIL z>=100\nEND", "safe": true }, { "filename": "100 doors_664.txt", "content": "\t\tDEFINE('PASS(A,I),O')\t\t:(PASS.END)\nPASS\t\tO = 0\nPASS.LOOP\tO = O + I\n\t\tEQ(A,1)\t\t\t:S(PASS.1)F(PASS.0)\nPASS.0\t\tA = 1\t\t\t:S(PASS.LOOP)F(RETURN)\nPASS.1\t\tA = 0\t\t\t:S(PASS.LOOP)F(RETURN)\nPASS.END\n \nMAIN\t\tD = ARRAY(100,0)\n\t\tI = 0\n \nMAIN.LOOP\tI = LE(I,100) I + 1\t\t:F(OUTPUT)\n\t\tPASS(D,I)\t\t\t:(MAIN.LOOP)\n \nOUTPUT\t\tI = 1\u00a0; OPEN = 'Opened doors are: '\nOUTPUT.LOOP\tOPEN = OPEN EQ(D,1) \" \" I\n\t\tI = LE(I,100) I + 1\t\t:S(OUTPUT.LOOP)F(OUTPUT.WRITE)\nOUTPUT.WRITE\tOUTPUT = OPEN\n\nEND", "safe": true }, { "filename": "100 doors_665.txt", "content": "$ snobol4 100doors.sno \nThe Macro Implementation of SNOBOL4 in C (CSNOBOL4) Version 1.3+\n by Philip L. Budne, January 23, 2011\nSNOBOL4 (Version 3.11, May 19, 1975)\n Bell Telephone Laboratories, Incorporated\n\nNo errors detected in source program\n\nOpened doors are: 1 4 9 16 25 36 49 64 81 100\nNormal termination at level 0\n100doors.sno:18: Last statement executed was 19\n", "safe": true }, { "filename": "100 doors_666.txt", "content": "MAIN\t\tD = ARRAY(100,0)\n\t\tI = 1\n\nMAIN.LOOP\tLE(I, 10)\t\t\t:F(OUTPUT)\n\t\tD = 1\t\t\n\t\tI = I + 1\t\t\t:(MAIN.LOOP)\n\nOUTPUT\t\tI = 1\u00a0; O = 'Opened doors are: '\nOUTPUT.LOOP\tO = O EQ(D,1) \" \" I\n\t\tI = LE(I,100) I + 1\t\t:S(OUTPUT.LOOP)F(OUTPUT.WRITE)\nOUTPUT.WRITE\tOUTPUT = O\nEND", "safe": true }, { "filename": "100 doors_667.txt", "content": "#!/usr/local/bin/spar\npragma annotate( summary, \"doors\" )\n @( description, \"Problem: You have 100 doors in a row that are all initially closed. You\" )\n @( description, \"make 100 passes by the doors. The first time through, you visit every door\" )\n @( description, \"and toggle the door (if the door is closed, you open it; if it is open, you\" )\n @( description, \"close it). The second time you only visit every 2nd door (door #2, #4, #6,\" )\n @( description, \"...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you\" )\n @( description, \"only visit the 100th door.\" )\n @( description, \"Question: What state are the doors in after the last pass? Which are open,\" )\n @( description, \"which are closed?\" )\n @( see_also, \"http://rosettacode.org/wiki/100_doors\" )\n @( author, \"Ken O. Burtch\" );\npragma license( unrestricted );\n\npragma restriction( no_external_commands );\n\nprocedure Doors is\n type Door_State is (Closed, Open);\n type Door_List is array(1..100) of Door_State;\n The_Doors\u00a0: Door_List;\nbegin\n for I in 1..100 loop\n The_Doors(I)\u00a0:= Closed;\n end loop;\n for I in 1..100 loop\n for J in arrays.first(The_Doors)..arrays.last(The_Doors) loop\n if J mod I = 0 then\n if The_Doors(J) = Closed then\n The_Doors(J)\u00a0:= Open;\n else\n The_Doors(J)\u00a0:= Closed;\n end if;\n end if;\n end loop;\n end loop;\n for I in arrays.first(The_Doors)..arrays.last(The_Doors) loop\n put (I) @ (\" is \") @ (The_Doors(I));\n new_line;\n end loop;\nend Doors;", "safe": true }, { "filename": "100 doors_668.txt", "content": "/* declare the variables */\nvar isOpen = {};\nvar pass, door;\n\n/* initialize the doors */\nfor door = 0; door < 100; door++ {\n\tisOpen[door] = true;\n}\n\n/* do the 99 remaining passes */\nfor pass = 1; pass < 100; ++pass {\n\tfor door = pass; door < 100; door += pass+1 {\n \t\tisOpen[door] = !isOpen[door];\n\t}\n}\n\n/* print the results */\nvar states = { true: \"open\", false: \"closed\" };\nfor door = 0; door < 100; door++ {\n\tprintf(\"Door #%d is %s.\\n\", door+1, states[isOpen[door]]);\n}", "safe": true }, { "filename": "100 doors_669.txt", "content": "/* declare the variables */\nvar door_sqrt = 1;\nvar door;\n\n/* print the perfect square doors as open */\nfor door = 0; door < 100; door++ {\n\tif (door_sqrt*door_sqrt == door+1) {\n\t\tprintf(\"Door #%d is open.\\n\", door+1);\n\t\tdoor_sqrt ++;\n\t} else {\n\t\tprintf(\"Door #%d is closed.\\n\", door+1);\n\t}\n}", "safe": true }, { "filename": "100 doors_67.txt", "content": "While (Door := A_Index ** 2) <= 100\n Result .= \"Door \" Door \" is open`n\"\nMsgBox, %Result%\n", "safe": true }, { "filename": "100 doors_670.txt", "content": "con\n _clkmode = xtal1+pll16x\n _clkfreq = 80_000_000\n\nobj\n ser\u00a0: \"FullDuplexSerial.spin\"\n\npub init\n ser.start(31, 30, 0, 115200)\n\n doors\n\n waitcnt(_clkfreq + cnt)\n ser.stop\n cogstop(0)\n\nvar\n\n byte door[101] ' waste one byte by using only door[1..100]\n\npri doors | i,j\n\n repeat i from 1 to 100\n repeat j from i to 100 step i\n not door[j]\n\n ser.str(string(\"Open doors: \"))\n\n repeat i from 1 to 100\n if door[i]\n ser.dec(i)\n ser.tx(32)\n\n ser.str(string(13,10))", "safe": true }, { "filename": "100 doors_671.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100 doors_672.txt", "content": "DECLARE\t@sqr int,\n\t\t@i int,\n\t\t@door int;\n\t\t\nSELECT @sqr =1,\n\t@i = 3,\n\t@door = 1;\t\n\t\t\t\t\nWHILE(@door <=100)\nBEGIN\n\tIF(@door = @sqr)\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CAST(@door as char)) + ' is open.';\n\t\tSET @sqr= @sqr+@i;\n\t\tSET @i=@i+2;\n\tEND\n\tELSE\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CONVERT(char,@door)) + ' is closed.';\n\tEND\nSET @door = @door + 1\nEND", "safe": true }, { "filename": "100 doors_673.txt", "content": "with numbers as (\n select generate_series(1, 100) as n\n),\npasses as (\n select passes.n pass, doors.n door \n from numbers doors\n cross join numbers passes \n where doors.n\u00a0% passes.n = 0 -- modulo\n),\ncounting as (\n select door, count(pass) pass_number \n from passes\n group by door\n) \nselect door from counting\nwhere pass_number\u00a0% 2 = 1\norder by door", "safe": true }, { "filename": "100 doors_674.txt", "content": "with numbers as (\n select rownum as n from dual connect by level <= 100\n),\npasses as (\n select doors.n door, count(passes.n) pass_number\n from numbers doors\n cross join numbers passes \n where MOD(doors.n, passes.n) = 0 -- modulo\n group by doors.n\n)\nselect door from passes\nwhere MOD(pass_number, 2) = 1\norder by door", "safe": true }, { "filename": "100 doors_675.txt", "content": "door|\n----+\n 1|\n 4|\n 9|\n ...\n", "safe": true }, { "filename": "100 doors_676.txt", "content": "--#SET TERMINATOR @\n\nSET SERVEROUTPUT ON @\n\nBEGIN\n DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY [100];\n DECLARE DOORS DOORS_ARRAY;\n DECLARE I SMALLINT;\n DECLARE J SMALLINT;\n DECLARE STATUS CHAR(10);\n DECLARE SIZE SMALLINT DEFAULT 100;\n\n -- Initializes the array, with all spaces (doors) as false (closed).\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET DOORS[I] = FALSE;\n SET I = I + 1;\n END WHILE;\n\n -- Processes the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET J = 1;\n WHILE (J <= SIZE) DO\n IF (MOD(J, I) = 0) THEN\n IF (DOORS[J] = TRUE) THEN\n SET DOORS[J] = FALSE;\n ELSE\n SET DOORS[J] = TRUE;\n END IF;\n END IF;\n SET J = J + 1;\n END WHILE;\n SET I = I + 1;\n END WHILE;\n\n -- Prints the final status o the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END);\n CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS);\n SET I = I + 1;\n END WHILE;\nEND @", "safe": true }, { "filename": "100 doors_677.txt", "content": "db2 -td@\ndb2 => BEGIN\n...\ndb2 (cont.) => END @\nDB20000I The SQL command completed successfully.\n\nDoor 1 is OPEN \nDoor 2 is CLOSED \nDoor 3 is CLOSED \nDoor 4 is OPEN \nDoor 5 is CLOSED \nDoor 6 is CLOSED \nDoor 7 is CLOSED \nDoor 8 is CLOSED \nDoor 9 is OPEN \nDoor 10 is CLOSED \nDoor 11 is CLOSED \nDoor 12 is CLOSED \nDoor 13 is CLOSED \nDoor 14 is CLOSED \nDoor 15 is CLOSED \nDoor 16 is OPEN \nDoor 17 is CLOSED \nDoor 18 is CLOSED \nDoor 19 is CLOSED \nDoor 20 is CLOSED \nDoor 21 is CLOSED \nDoor 22 is CLOSED \nDoor 23 is CLOSED \nDoor 24 is CLOSED \nDoor 25 is OPEN \nDoor 26 is CLOSED \nDoor 27 is CLOSED \nDoor 28 is CLOSED \nDoor 29 is CLOSED \nDoor 30 is CLOSED \nDoor 31 is CLOSED \nDoor 32 is CLOSED \nDoor 33 is CLOSED \nDoor 34 is CLOSED \nDoor 35 is CLOSED \nDoor 36 is OPEN \nDoor 37 is CLOSED \nDoor 38 is CLOSED \nDoor 39 is CLOSED \nDoor 40 is CLOSED \nDoor 41 is CLOSED \nDoor 42 is CLOSED \nDoor 43 is CLOSED \nDoor 44 is CLOSED \nDoor 45 is CLOSED \nDoor 46 is CLOSED \nDoor 47 is CLOSED \nDoor 48 is CLOSED \nDoor 49 is OPEN \nDoor 50 is CLOSED \nDoor 51 is CLOSED \nDoor 52 is CLOSED \nDoor 53 is CLOSED \nDoor 54 is CLOSED \nDoor 55 is CLOSED \nDoor 56 is CLOSED \nDoor 57 is CLOSED \nDoor 58 is CLOSED \nDoor 59 is CLOSED \nDoor 60 is CLOSED \nDoor 61 is CLOSED \nDoor 62 is CLOSED \nDoor 63 is CLOSED \nDoor 64 is OPEN \nDoor 65 is CLOSED \nDoor 66 is CLOSED \nDoor 67 is CLOSED \nDoor 68 is CLOSED \nDoor 69 is CLOSED \nDoor 70 is CLOSED \nDoor 71 is CLOSED \nDoor 72 is CLOSED \nDoor 73 is CLOSED \nDoor 74 is CLOSED \nDoor 75 is CLOSED \nDoor 76 is CLOSED \nDoor 77 is CLOSED \nDoor 78 is CLOSED \nDoor 79 is CLOSED \nDoor 80 is CLOSED \nDoor 81 is OPEN \nDoor 82 is CLOSED \nDoor 83 is CLOSED \nDoor 84 is CLOSED \nDoor 85 is CLOSED \nDoor 86 is CLOSED \nDoor 87 is CLOSED \nDoor 88 is CLOSED \nDoor 89 is CLOSED \nDoor 90 is CLOSED \nDoor 91 is CLOSED \nDoor 92 is CLOSED \nDoor 93 is CLOSED \nDoor 94 is CLOSED \nDoor 95 is CLOSED \nDoor 96 is CLOSED \nDoor 97 is CLOSED \nDoor 98 is CLOSED \nDoor 99 is CLOSED \nDoor 100 is OPEN \n", "safe": true }, { "filename": "100 doors_678.txt", "content": "datatype Door = Closed | Opened\n\nfun toggle Closed = Opened\n | toggle Opened = Closed\n\nfun pass (step, doors) = List.map (fn (index, door) => if (index mod step) = 0\n\t\t\t\t\t\t then (index, toggle door)\n\t\t\t\t\t\t else (index, door))\n\t\t\t\t doors\n\n(* [1..n] *)\nfun runs n = List.tabulate (n, fn k => k+1)\n\nfun run n =\n let\n\tval initialdoors = List.tabulate (n, fn i => (i+1, Closed))\n\tval counter = runs n\n in\n\tfoldl pass initialdoors counter\n end\n\nfun opened_doors n = List.mapPartial (fn (index, Closed) => NONE\n\t\t\t\t | (index, Opened) => SOME (index))\n\t\t\t\t (run n)", "safe": true }, { "filename": "100 doors_679.txt", "content": "- opened_doors 100;\nval it = [1,4,9,16,25,36,49,64,81,100]\u00a0: int list\n", "safe": true }, { "filename": "100 doors_68.txt", "content": "#include \n$doors = 100\n\n;door array, 0 = closed, 1 = open\nLocal $door[$doors +1]\n\nFor $ii = 1 To $doors\n\tFor $i = $ii To $doors Step $ii\n\t\t$door[$i] = Not $door[$i]\n\tnext\nNext\n\n;display to screen\nFor $i = 1 To $doors\n\tConsoleWrite (Number($door[$i])& \" \")\n\tIf Mod($i,10) = 0 Then ConsoleWrite(@CRLF)\nNext\n", "safe": true }, { "filename": "100 doors_680.txt", "content": "clear\nset obs 100\ngen doors=0\ngen index=_n\nforvalues i=1/100 {\n\tquietly replace doors=!doors if mod(_n,`i')==0\n}\nlist index if doors, noobs noheader\n\n +-------+\n | 1 |\n | 4 |\n | 9 |\n | 16 |\n | 25 |\n |-------|\n | 36 |\n | 49 |\n | 64 |\n | 81 |\n | 100 |\n +-------+", "safe": true }, { "filename": "100 doors_681.txt", "content": "d \".\"\n#d\ni d\n#i\np \"door\" #i\n*p *p \".\"\ni d f \"oc\"\ni d #@f #*p\ni d .\\f \"o\" $ #i\ni i d\n#i +101 i \"\"\n#i\nd d \".\"\n#d +101 d \"\"\n#d", "safe": true }, { "filename": "100 doors_682.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100", "safe": true }, { "filename": "100 doors_683.txt", "content": "(\nvar n = 100, doors = false\u00a0! n;\nvar pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };\n(1..n-1).do(pass);\ndoors.selectIndices { |open| open }; // all are closed except [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]\n)", "safe": true }, { "filename": "100 doors_684.txt", "content": "/* declare enum to identify the state of a door */\nenum DoorState\u00a0: String {\n case Opened = \"Opened\"\n case Closed = \"Closed\"\n}\n\n/* declare list of doors state and initialize them */\nvar doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)\n\n/* do the 100 passes */\nfor i in 1...100 {\n /* map on a strideTo instance to only visit the needed doors on each iteration */\n map(stride(from: i - 1, to: 100, by: i)) {\n doorsStateList[$0] = doorsStateList[$0] == .Opened\u00a0? .Closed\u00a0: .Opened\n }\n}\n\n/* print the results */\nfor (index, item) in enumerate(doorsStateList) {\n println(\"Door \\(index+1) is \\(item.rawValue)\")\n}", "safe": true }, { "filename": "100 doors_685.txt", "content": "/* declare enum to identify the state of a door */\nenum DoorState\u00a0: String {\n case Opened = \"Opened\"\n case Closed = \"Closed\"\n}\n\n/* declare list of doors state and initialize them */\nvar doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)\n\n/* set i^2 doors to opened */\nvar i = 1\ndo {\n doorsStateList[(i*i)-1] = DoorState.Opened\n ++i\n} while (i*i) <= doorsStateList.count\n\n/* print the results */\nfor (index, item) in enumerate(doorsStateList) {\n println(\"Door \\(index+1) is \\(item.rawValue)\")\n}", "safe": true }, { "filename": "100 doors_686.txt", "content": "var arr: [Bool] = Array(1...100).map{ remquo(exp(log(Float($0))/2.0),1).0 == 0 }", "safe": true }, { "filename": "100 doors_687.txt", "content": "source hundredDoors\n @: [ 1..100 -> 0 ];\n templates toggle\n def jump: $;\n $jump..100:$jump -> \\(\n when )> do @hundredDoors($): 1;\n otherwise @hundredDoors($): 0;\n \\) -> !VOID\n end toggle\n 1..100 -> toggle -> !VOID\n $@ -> \\[i](<=1> ' $i;'\u00a0!\\)\u00a0!\nend hundredDoors\n\n$hundredDoors -> 'Open doors:$...;' -> !OUT::write", "safe": true }, { "filename": "100 doors_688.txt", "content": "hundredDoors source\n @ set [ 1..100 -> 0 ];\n toggle templates\n jump is $;\n $jump..100:$jump -> templates\n when <|?($@hundredDoors($) matches <|=0>)> do @hundredDoors($) set 1;\n otherwise @hundredDoors($) set 0;\n end -> !VOID\n end toggle\n 1..100 -> toggle -> !VOID\n $@(.. as i; -> if <|=1> -> ' $i;')\u00a0!\nend hundredDoors\n\n$hundredDoors -> 'Open doors:$...;'\u00a0!", "safe": true }, { "filename": "100 doors_689.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_69.txt", "content": "BEGIN {\n for(i=1; i <= 100; i++)\n {\n doors[i] = 0 # close the doors\n }\n for(i=1; i <= 100; i++)\n {\n for(j=i; j <= 100; j += i)\n {\n doors[j] = (doors[j]+1) % 2\n }\n }\n for(i=1; i <= 100; i++)\n {\n print i, doors[i] ? \"open\" : \"close\"\n }\n}\n", "safe": true }, { "filename": "100 doors_690.txt", "content": "package require Tcl 8.5\nset n 100\nset doors [concat - [lrepeat $n 0]]\nfor {set step 1} {$step <= $n} {incr step} {\n for {set i $step} {$i <= $n} {incr i $step} {\n lset doors $i [expr {\u00a0! [lindex $doors $i]}]\n }\n}\nfor {set i 1} {$i <= $n} {incr i} {\n puts [format \"door %d is %s\" $i [expr {[lindex $doors $i]\u00a0? \"open\"\u00a0: \"closed\"}]]\n}", "safe": true }, { "filename": "100 doors_691.txt", "content": "package require Tcl 8.5\nset doors [lrepeat [expr {$n + 1}] closed]\nfor {set i 1} {$i <= sqrt($n)} {incr i} {\n lset doors [expr {$i ** 2}] open\n}\nfor {set i 1} {$i <= $n} {incr i} {\n puts [format \"door %d is %s\" $i [lindex $doors $i]]\n}", "safe": true }, { "filename": "100 doors_692.txt", "content": "package require Tcl 8.5\npackage require Tk\n\narray set door_status {}\n\n# create the gui\nset doors [list x]\nfor {set i 0} {$i < 10} {incr i} {\n for {set j 0} {$j < 10} {incr j} {\n set k [expr {1 + $j + 10*$i}]\n lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \\\n -indicatoron no -offrelief flat -width 3 -value open]\n grid [lindex $doors $k] -column $j -row $i\n }\n}\n\n# create the controls\nbutton .start -command go -text Start\nlabel .i_label -text \" door:\"\nentry .i -textvariable i -width 4\nlabel .step_label -text \" step:\"\nentry .step -textvariable step -width 4\ngrid .start - .i_label - .i - .step_label - .step - -row $i\ngrid configure .start -sticky ew\ngrid configure .i_label .step_label -sticky e\ngrid configure .i .step -sticky w\n\nproc go {} {\n global doors door_status i step\n\n # initialize the door_status (all closed)\n for {set d 1} {$d <= 100} {incr d} {\n set door_status($d) closed\n }\n \n # now, begin opening and closing\n for {set step 1} {$step <= 100} {incr step} {\n for {set i 1} {$i <= 100} {incr i} {\n if {$i\u00a0% $step == 0} {\n [lindex $doors $i] [expr {$door_status($i) eq \"open\"\u00a0? \"deselect\"\u00a0: \"select\"}]\n update\n after 50\n }\n }\n }\n}", "safe": true }, { "filename": "100 doors_693.txt", "content": "seq(0,X,1,100\nFor(X,1,100\n0 or Ans-not(fPart(cumSum(1 or Ans)/A\nEnd\nPause Ans\n", "safe": true }, { "filename": "100 doors_694.txt", "content": "Pause not(fPart(\u221a(seq(X,X,1,100\n", "safe": true }, { "filename": "100 doors_695.txt", "content": "Define doors(fast) = Func\n Local doors,i,j\n seq(false,x,1,100)\u00a0? doors\n If fast Then\n For i,1,10,1\n true\u00a0? doors[i^2]\n EndFor\n Else\n For i,1,100,1\n For j,i,100,i\n not doors[j]\u00a0? doors[j]\n EndFor\n EndFor\n EndIf\n Return doors\nEndFunc", "safe": true }, { "filename": "100 doors_696.txt", "content": "for(%steps = 1; %a <= 100; %a++)\n\tfor(%current = %steps; %current <= 100; %current += %steps)\n\t\t%door[%current] =\u00a0!%door[%current];\nfor(%a = 1; %a <= 100; %a++)\n\techo(\"Door #\" @ %a @ \" is\" SPC %door[%current]\u00a0? \"Open\"\u00a0: \"Closed\" @ \".\");", "safe": true }, { "filename": "100 doors_697.txt", "content": "WITH OneToTen (N)\nAS ( SELECT N\n FROM ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)\n ) V(N)\n )\n , InitDoors (Num, IsOpen)\nAS ( SELECT 1\n + 1 * Units.N\n + 10 * Tens.N As Num\n , Convert(Bit, 0) As IsOpen\n FROM OneToTen As Units\n CROSS JOIN OneToTen As Tens\n ) -- This part could be easier with a tally table or equivalent table-valued function\n , States (NbStep, Num, IsOpen)\nAS ( SELECT 0 As NbStep\n , Num\n , IsOpen\n FROM InitDoors As InitState\n UNION ALL\n SELECT 1 + NbStep\n , Num\n , CASE Num\u00a0% (1 + NbStep)\n WHEN 0 THEN ~IsOpen\n ELSE IsOpen\n END\n FROM States\n WHERE NbStep < 100\n )\nSELECT Num As DoorNumber\n , Concat( 'Door number ', Num, ' is '\n , CASE IsOpen\n WHEN 1 THEN ' open'\n ELSE ' closed'\n END ) As Result -- Concat needs SQL Server 2012\nFROM States\nWHERE NbStep = 100\nORDER By Num\n; -- Fortunately, maximum recursion is 100 in SQL Server.\n-- For more doors, the MAXRECURSION hint should be used.\n-- More doors would also need an InitDoors with more rows.", "safe": true }, { "filename": "100 doors_698.txt", "content": "SET NOCOUNT ON;\n\n-- Doors can be open or closed.\nDECLARE @open CHAR(1) = 'O';\nDECLARE @closed CHAR(1) = 'C';\n\n-- There are 100 doors in a row that are all initially closed.\nDECLARE @doorsCount INT = 100;\nDECLARE @doors TABLE (doorKey INT PRIMARY KEY, doorState CHAR(1));\nWITH sample100 AS (\n SELECT TOP(100) object_id\n FROM sys.objects\n)\nINSERT @doors\n SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS doorKey,\n @closed AS doorState\n FROM sample100 AS A\n CROSS JOIN sample100 AS B\n CROSS JOIN sample100 AS C\n CROSS JOIN sample100 AS D\n ORDER BY 1\n OFFSET 0 ROWS\n FETCH NEXT @doorsCount ROWS ONLY;\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.\nDECLARE @pass INT = 1;\nWHILE @pass <= @doorsCount BEGIN\n UPDATE @doors\n SET doorState = CASE doorState WHEN @open THEN @closed ELSE @open END\n WHERE doorKey >= @pass\n AND doorKey\u00a0% @pass = 0;\n\n SET @pass = @pass + 1;\nEND;\n\n-- Answer the question: what state are the doors in after the last pass?\n-- The answer as the query result is:\nSELECT doorKey, doorState FROM @doors;\n-- The answer as the console output is:\nDECLARE @log VARCHAR(max);\nDECLARE @doorKey INT = (SELECT MIN(doorKey) FROM @doors);\nWHILE @doorKey <= @doorsCount BEGIN\n SET @log = (\n SELECT TOP(1) CONCAT('Doors ', doorKey, ' are ',\n CASE doorState WHEN @open THEN ' open' ELSE 'closed' END, '.')\n FROM @doors\n WHERE doorKey = @doorKey\n );\n RAISERROR (@log, 0, 1) WITH NOWAIT;\n\n SET @doorKey = (SELECT MIN(doorKey) FROM @doors WHERE doorKey > @doorKey);\nEND;\n\n-- Which are open, which are closed?\n-- The answer as the query result is:\nSELECT doorKey, doorState FROM @doors WHERE doorState = @open;\nSELECT doorKey, doorState FROM @doors WHERE doorState = @closed;\n-- The answer as the console output is:\nSET @log = (\n SELECT CONCAT('These are open doors: ',\n STRING_AGG(CAST(doorKey AS VARCHAR(max)), ', '), '.')\n FROM @doors\n WHERE doorState = @open\n);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = (\n SELECT CONCAT('These are closed doors: ',\n STRING_AGG(CAST(doorKey AS VARCHAR(max)), ', '), '.')\n FROM @doors\n WHERE doorState = @closed\n);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\n\n-- Assert:\nDECLARE @expected TABLE (doorKey INT PRIMARY KEY);\nSET @doorKey = 1;\nWHILE @doorKey * @doorKey <= @doorsCount BEGIN\n INSERT @expected VALUES (@doorKey * @doorKey);\n SET @doorKey = @doorKey + 1;\nEND;\nIF NOT EXISTS (\n SELECT doorKey FROM @doors WHERE doorState = @open\n EXCEPT\n SELECT doorKey FROM @expected\n )\n AND NOT EXISTS (\n SELECT doorKey FROM @expected\n EXCEPT\n SELECT doorKey FROM @doors WHERE doorState = @open\n )\n PRINT 'The task is solved.';\nELSE\n THROW 50000, 'These aren''t the doors you''re looking for.', 1;", "safe": true }, { "filename": "100 doors_699.txt", "content": "#lang transd\n\nMainModule: {\n doors: Vector(100),\n _start: (\u03bb \n (for i in Seq(100) do\n (for k in Seq(i 100 (+ i 1)) do\n (set-el doors k (not (get doors k)))\n ))\n\n (for i in Seq(100) do\n (if (get doors i) (textout (+ i 1) \" \"))\n ))\n}", "safe": true }, { "filename": "100 doors_7.txt", "content": "\n \n \n \n \n \n \n n\n \n 2\n \n \n =\n 1\n +\n 3\n +\n 5\n +\n \u2026\n +\n (\n 2\n n\n \u2212\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle n^{2}=1+3+5+\\ldots +(2n-1)}}\n \n.\n", "safe": true }, { "filename": "100 doors_70.txt", "content": "BEGIN {\n for(i=1; i <= 100; i++) {\n doors[i] = 0 # close the doors\n }\n for(i=1; i <= 100; i++) {\n if ( int(sqrt(i)) == sqrt(i) ) {\n doors[i] = 1\n }\n }\n for(i=1; i <= 100; i++)\n {\n print i, doors[i] ? \"open\" : \"close\"\n }\n}\n", "safe": true }, { "filename": "100 doors_700.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100 doors_701.txt", "content": "! Optimized solution with True BASIC\n\nOPTION NOLET\nx = 1 \ny = 3 \nz = 0\nPRINT STR$(x) & \" Open\"\nDO UNTIL z >= 100\nz = x + y\nPRINT STR$(z) & \" Open\"\nx = z \ny = y + 2\nLOOP\n\nEND", "safe": true }, { "filename": "100 doors_702.txt", "content": "// library: math: get: task: door: open: close100 1.0.0.0.11 (filenamemacro=getmaocl.s) [] [] [kn, ri, mo, 31-12-2012 22:03:16]\nPROC PROCMathGetTaskDoorOpenClose( INTEGER doorMaxI, INTEGER passMaxI )\n // e.g. PROC Main()\n // e.g. PROCMathGetTaskDoorOpenClose( 100, 100 )\n // e.g. END\n // e.g.\n // e.g. Main()\n //\n // ===\n //\n // The output will be:\n //\n // door 1 is open\n // door 4 is open\n // door 9 is open\n // door 16 is open\n // door 25 is open\n // door 36 is open\n // door 49 is open\n // door 64 is open\n // door 81 is open\n // door 100 is open\n // all other doors are closed\n //\n // ===\n //\n INTEGER passMinI = 1\n INTEGER passI = 0\n //\n INTEGER doorminI = 1\n INTEGER doorI = 0\n //\n STRING s[255] = \"\"\n //\n INTEGER bufferI = 0\n //\n PushPosition()\n bufferI = CreateTempBuffer()\n PopPosition()\n //\n FOR doorI = doorMinI TO doorMaxI\n //\n SetGlobalInt( Format( \"doorsI\", doorI ), 0 )\n //\n ENDFOR\n //\n FOR passI = passMinI TO passMaxI\n //\n doorI = passI - passI\n //\n REPEAT\n //\n doorI = doorI + passI\n //\n SetGlobalInt( Format( \"doorsI\", doorI ), NOT( GetGlobalInt( Format( \"doorsI\", doorI ) ) ) )\n //\n UNTIL ( doorI >= doorMaxI )\n //\n ENDFOR\n //\n FOR doorI = doorMinI TO doorMaxI\n //\n IF ( GetGlobalInt( Format( \"doorsI\", doorI ) ) > 0 )\n //\n s = \"open\"\n //\n AddLine( Format( \"door\", \" \", doorI, \" \", \"is\", \" \", s ), bufferI )\n //\n ELSE\n //\n s = \"closed\"\n //\n ENDIF\n //\n ENDFOR\n //\n AddLine( \"all other doors are closed\", bufferI )\n //\n GotoBufferId( bufferI )\n //\nEND\n\nPROC Main()\n PROCMathGetTaskDoorOpenClose( 100, 100 )\nEND", "safe": true }, { "filename": "100 doors_703.txt", "content": "$$ MODE TUSCRIPT\nDICT doors create\nCOMPILE\nLOOP door=1,100\n LOOP pass=1,100\n SET go=MOD (door,pass)\n DICT doors lookup door,num,cnt,status\n IF (num==0) THEN\n SET status=\"open\"\n DICT doors add door,num,cnt,status\n ELSE\n IF (go==0) THEN\n IF (status==\"closed\") THEN\n SET status=\"open\"\n ELSE\n SET status=\"closed\"\n ENDIF\n DICT doors update door,num,cnt,status\n ENDIF\n ENDIF\n ENDLOOP\nENDLOOP\nENDCOMPILE\nDICT doors unload door,num,cnt,status", "safe": true }, { "filename": "100 doors_704.txt", "content": " status = *\n 1 = open\n 2 = closed\n 3 = closed\n 4 = open\n 5 = closed\n 6 = closed\n 7 = closed\n 8 = closed\n 9 = open\n 10 = closed\n 11 = closed\n 12 = closed\n 13 = closed\n 14 = closed\n 15 = closed\n 16 = open\n 17 = closed\n 18 = closed\n 19 = closed\n 20 = closed\n 21 = closed\n 22 = closed\n 23 = closed\n 24 = closed\n 25 = open\n 26 = closed\n 27 = closed\n 28 = closed\n 29 = closed\n 30 = closed\n 31 = closed\n 32 = closed\n 33 = closed\n 34 = closed\n 35 = closed\n 36 = open\n 37 = closed\n 38 = closed\n 39 = closed\n 40 = closed\n 41 = closed\n 42 = closed\n 43 = closed\n 44 = closed\n 45 = closed\n 46 = closed\n 47 = closed\n 48 = closed\n 49 = open\n 50 = closed\n 51 = closed\n 52 = closed\n 53 = closed\n 54 = closed\n 55 = closed\n 56 = closed\n 57 = closed\n 58 = closed\n 59 = closed\n 60 = closed\n 61 = closed\n 62 = closed\n 63 = closed\n 64 = open\n 65 = closed\n 66 = closed\n 67 = closed\n 68 = closed\n 69 = closed\n 70 = closed\n 71 = closed\n 72 = closed\n 73 = closed\n 74 = closed\n 75 = closed\n 76 = closed\n 77 = closed\n 78 = closed\n 79 = closed\n 80 = closed\n 81 = open\n 82 = closed\n 83 = closed\n 84 = closed\n 85 = closed\n 86 = closed\n 87 = closed\n 88 = closed\n 89 = closed\n 90 = closed\n 91 = closed\n 92 = closed\n 93 = closed\n 94 = closed\n 95 = closed\n 96 = closed\n 97 = closed\n 98 = closed\n 99 = closed\n 100 = open\n", "safe": true }, { "filename": "100 doors_705.txt", "content": "interface Door {\n id: number;\n open: boolean;\n}\n\nfunction doors(): Door[] {\n var Doors: Door[] = [];\n\n for (let i = 1; i <= 100; i++) {\n Doors.push({id: i, open: false});\n }\n\n for (let secuence of Doors) {\n for (let door of Doors) {\n if (door.id\u00a0% secuence.id == 0) {\n door.open = !door.open;\n }\n }\n }\n\n return Doors.filter(a => a.open);\n}", "safe": true }, { "filename": "100 doors_706.txt", "content": "(defun hyaku-mai-tobira ()\n (let ((doors (vector 100)))\n (each ((i (range 0 99)))\n (each ((j (range i 99 (+ i 1))))\n (flip [doors j])))\n doors))\n\n(each ((counter (range 1))\n (door (hyaku-mai-tobira)))\n (put-line `door @counter is @(if door \"open\" \"closed\")`))", "safe": true }, { "filename": "100 doors_707.txt", "content": "FOR p = 1 TO 100\n FOR d = p TO 100 STEP p\n @(d) = @(d) = 0\n NEXT d\nNEXT p\n\nFOR d= 1 TO 100\n IF @(d) PRINT \"Door \";d;\" is open\"\nNEXT d", "safe": true }, { "filename": "100 doors_708.txt", "content": "\u25ff2/+=0\u229e\u25ff.+1\u21e1100\n +1\u21e1100 # 1-100\n \u229e\u25ff. # Mod each with 1-100\n =0 # Find where mod = 0, aka the divisors\n /+ # Sum to get num of divisors\n\u25ff2 # Num divisors is odd\n", "safe": true }, { "filename": "100 doors_709.txt", "content": "[1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]", "safe": true }, { "filename": "100 doors_71.txt", "content": "(open,closed,change,open?)\u00a0:= (true,false,not,test);\ndoors\u00a0:= bits(100,closed);\nfor i in 1..#doors repeat\n for j in i..#doors by i repeat\n doors.j\u00a0:= change doors.j\n[i for i in 1..#doors | open? doors.i]", "safe": true }, { "filename": "100 doors_710.txt", "content": "entry LP_DO_IT\n\n variables\n string V_DOORS\n boolean V_DOOR_STATE\n string V_DOOR_STATE_S\n numeric V_IDX\n numeric V_TOTAL_DOORS\n string V_DOOR_STATE_LIST\n numeric V_LOOP_COUNT\n endvariables\n\n V_TOTAL_DOORS = 100\n putitem V_DOORS, V_TOTAL_DOORS, 0\n\n V_DOORS = $replace (V_DOORS, 1, \"\u00b7;\", \"\u00b7;0\", -1)\n\n putitem/id V_DOOR_STATE_LIST, \"1\", \"Open\"\n putitem/id V_DOOR_STATE_LIST, \"0\", \"Close\"\n\n V_LOOP_COUNT = 1\n while (V_LOOP_COUNT <= V_TOTAL_DOORS)\n V_IDX = 0\n V_IDX = V_IDX + V_LOOP_COUNT\n\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n while (V_IDX <= V_TOTAL_DOORS)\n\n V_DOOR_STATE = !V_DOOR_STATE\n getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)\n putitem V_DOORS, V_IDX, V_DOOR_STATE\n\n V_IDX = V_IDX + V_LOOP_COUNT\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n endwhile\n\n V_LOOP_COUNT = V_LOOP_COUNT + 1\n\n endwhile\n\n V_IDX = 1\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n while (V_IDX <= V_TOTAL_DOORS)\n getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)\n if (V_DOOR_STATE)\n putmess \"Door\u00a0%%V_IDX%%% is finally\u00a0%%V_DOOR_STATE_S%%%\"\n endif\n\n V_IDX = V_IDX + 1\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n endwhile\n\nend\u00a0; LP_DO_IT", "safe": true }, { "filename": "100 doors_711.txt", "content": "\n\nDoor 1 is finally Open\nDoor 4 is finally Open\nDoor 9 is finally Open\nDoor 16 is finally Open\nDoor 25 is finally Open\nDoor 36 is finally Open\nDoor 49 is finally Open\nDoor 64 is finally Open\nDoor 81 is finally Open\nDoor 100 is finally Open\n\n", "safe": true }, { "filename": "100 doors_712.txt", "content": "hundredDoors\u00a0: [Boolean]\nhundredDoors =\n toggleEachNth\u00a0: Nat -> [Boolean] -> [Boolean]\n toggleEachNth n doors =\n go counter = cases\n [] -> []\n (d +: ds) -> if counter == n\n then (not d) +: go 1 ds\n else d +: go (counter+1) ds\n\n go 1 doors\n\n foldr toggleEachNth (replicate 100 'false) (range 1 101)\n\nresults = filterMap (cases (open, ix) -> if open then Some (ix+1) else None)\n (indexed hundredDoors)", "safe": true }, { "filename": "100 doors_713.txt", "content": "#! /bin/bash\n\ndeclare -a doors\nfor((i=1; i <= 100; i++)); do\n doors[$i]=0\ndone\n\nfor((i=1; i <= 100; i++)); do\n for((j=i; j <= 100; j += i)); do\n\techo $i $j\n\tdoors[$j]=$(( doors[j] ^ 1 ))\n done\ndone\n\nfor((i=1; i <= 100; i++)); do\n if [[ ${doors[$i]} -eq 0 ]]; then\n\top=\"closed\"\n else\n\top=\"open\"\n fi\n echo $i $op\ndone", "safe": true }, { "filename": "100 doors_714.txt", "content": "#!/bin/bash\n\nfor i in {1..100}; do\n door[$i*$i]=1\n [ -z ${door[$i]} ] && echo \"$i closed\" || echo \"$i open\"\ndone", "safe": true }, { "filename": "100 doors_715.txt", "content": "#\n# 100 doors\n#\n\ndecl int i j\ndecl boolean<> doors\n\n# append 101 boolean values to doors stream\nfor (set i 0) (or (< i 100) (= i 100)) (inc i)\n append false doors\nend for\n\n# loop through, opening and closing doors\nfor (set i 1) (or (< i 100) (= i 100)) (inc i)\n for (set j i) (or (< j 100) (= j 100)) (inc j)\n if (= (mod j i) 0)\n set doors (not doors)\n end if\n end for\nend for\n\n# loop through and output which doors are open\nfor (set i 1) (or (< i 100) (= i 100)) (inc i)\n out \"Door \" i \": \" console\n if doors\n out \"open\" endl console\n else\n out \"closed\" endl console\n end if\nend if", "safe": true }, { "filename": "100 doors_716.txt", "content": "#import std\n#import nat\n\ndoors = 0!* iota 100\n\npass(\"n\",\"d\") = remainder\\\"n\"?l(~&r,not ~&r)* num \"d\"\n\n#cast %nL\n\nmain = ~&rFlS num pass=>doors nrange(100,1)", "safe": true }, { "filename": "100 doors_717.txt", "content": "#import nat\n\n#cast %nL\n\nmain = product*tiiXS iota10", "safe": true }, { "filename": "100 doors_718.txt", "content": "<1,4,9,16,25,36,49,64,81>\n", "safe": true }, { "filename": "100 doors_719.txt", "content": "\u00b7\u00b7\u00b7\nhttp://rosettacode.org/wiki/100_doors\n\u00b7\u00b7\u00b7\n\u25a0 HundredDoors \n \u00a7 static\n \u25b6 main\n \u2022 args\u2982 String[]\n open\u2982 boolean: true\n closed\u2982 boolean: false\n doors\u2982 boolean[1+100] \u00b7 all initially closed\n \ud83d\udd01 pass from 1 to 100\n \u2200 visited \u2208 pass\u2025100 by pass\n \u00b7 toggle the visited doors\n if the doors[visited] are closed\n let the doors[visited] be open\n else\n let the doors[visited] be closed\n for each door #n in doors\u2982 boolean\n if the door is open\n System.out.println \"Door #\u2e28n\u2e29 is open.\"", "safe": true }, { "filename": "100 doors_72.txt", "content": "[i for i in 1..100 | perfectSquare? i] -- or\n[i^2 for i in 1..sqrt(100)::Integer]", "safe": true }, { "filename": "100 doors_720.txt", "content": "int main() {\n\tbool doors_open[101];\n\tfor(int i = 1; i < doors_open.length; i++) {\n\t\tfor(int j = 1; i*j < doors_open.length; j++) {\n\t\t\tdoors_open[i*j] = !doors_open[i*j];\n\t\t}\n\t\tstdout.printf(\"%d: %s\\n\", i, (doors_open[i]\u00a0? \"open\"\u00a0: \"closed\"));\n\t}\n\treturn 0;\n}", "safe": true }, { "filename": "100 doors_721.txt", "content": "1: open\n2: closed\n3: closed\n4: open\n5: closed\n6: closed\n7: closed\n8: closed\n9: open\n10: closed\n11: closed\n...", "safe": true }, { "filename": "100 doors_722.txt", "content": "int main() {\n\tint i = 1;\n\twhile(i*i <= 100) {\n\t\tstdout.printf(\"${i*i} open\\n\");\n\t\ti++;\n\t}\n\treturn 0;\n}", "safe": true }, { "filename": "100 doors_723.txt", "content": "1 open\n4 open\n9 open\n16 open\n25 open\n36 open\n49 open\n64 open\n81 open\n100 open", "safe": true }, { "filename": "100 doors_724.txt", "content": " 00000064 0000 1 n = 100\n 0000 0000 2 .entry\tdoors, ^m<>\n 26'AF 9F 0002 3 \tpushab\tb^arr\t\t\t\t; offset signed byte\n 50 64 8F 9A 0005 4 \tmovzbl\t#n, r0\n 50 DD 0009 5 \tpushl\tr0\t\t\t\t; (sp) -> .ascid arr\n 000B 6 10$:\n 51 50 D0 000B 7 \tmovl\tr0, r1\t\t\t\t; step = start index\n 000E 8 20$:\n 25'AF41 01 8C 000E 9 \txorb2\t#^a\"0\" \\^a\"1\", b^arr-1[r1]\t; \\ xor toggle \"1\"<->\"0\"\n FFF5 51 50 6E F1 0013 10 \tacbl\t(sp), r0, r1, 20$\t\t; limit, step, index\n EF 50 F5 0019 11 \tsobgtr\tr0, 10$\t\t\t\t; n..1\n 001C 12 \n 5E DD 001C 13 \tpushl\tsp\t\t\t\t; descriptor by reference\n 00000000'GF 01 FB 001E 14 \tcalls\t#1, g^lib$put_output\t\t; show result\n 04 0025 15 \tret\n 0026 16 \n30'30'30'30'30'30'30'30'30'30'30'30' 0026 17 arr:\t.byte\t^a\"0\"[n]\n30'30'30'30'30'30'30'30'30'30'30'30' 0032 \n30'30'30'30'30'30'30'30'30'30'30'30' 003E \n30'30'30'30'30'30'30'30'30'30'30'30' 004A \n30'30'30'30'30'30'30'30'30'30'30'30' 0056 \n30'30'30'30'30'30'30'30'30'30'30'30' 0062 \n30'30'30'30'30'30'30'30'30'30'30'30' 006E \n30'30'30'30'30'30'30'30'30'30'30'30' 007A \n 30'30'30'30' 0086 \n 008A 18 .end\tdoors\n$ run doors\n1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100 doors_725.txt", "content": "Sub Rosetta_100Doors()\nDim Door(100) As Boolean, i As Integer, j As Integer\nFor i = 1 To 100 Step 1\n For j = i To 100 Step i\n Door(j) = Not Door(j)\n Next j\n If Door(i) = True Then\n Debug.Print \"Door \" & i & \" is Open\"\n Else\n Debug.Print \"Door \" & i & \" is Closed\"\n End If\nNext i\nEnd Sub\n\n\n*** USE THIS ONE, SEE COMMENTED LINES, DONT KNOW WHY EVERYBODY FOLLOWED OTHERS ANSWERS AND CODED THE PROBLEM DIFFERENTLY ***\n*** ALWAYS USE AND TEST A READABLE, EASY TO COMPREHEND CODING BEFORE 'OPTIMIZING' YOUR CODE AND TEST THE 'OPTIMIZED' CODE AGAINST THE 'READABLE' ONE.\nPanikkos Savvides.\n\n\nSub Rosetta_100Doors2()\nDim Door(100) As Boolean, i As Integer, j As Integer\nDim strAns As String\n' There are 100 doors in a row that are all initially closed.\n' You make 100 passes by the doors.\nFor j = 1 To 100\n ' The first time through, visit every door and toggle the door\n ' (if the door is closed, open it; if it is open, close it).\n For i = 1 To 100 Step 1\n Door(i) = Not Door(i)\n Next i\n ' The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.\n For i = 2 To 100 Step 2\n Door(i) = Not Door(i)\n Next i\n ' The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n For i = 3 To 100 Step 3\n Door(i) = Not Door(i)\n Next i\nNext j\n\nFor j = 1 To 100\n If Door(j) = True Then\n strAns = j & strAns & \", \"\n End If\nNext j\n\nIf Right(strAns, 2) = \", \" Then strAns = Left(strAns, Len(strAns) - 2)\nIf Len(strAns) = 0 Then strAns = \"0\"\nDebug.Print \"Doors [\" & strAns & \"] are open, the rest are closed.\"\n' Doors [0] are open, the rest are closed., AKA ZERO DOORS OPEN\nEnd Sub", "safe": true }, { "filename": "100 doors_726.txt", "content": "Dim doorIsOpen(100), pass, currentDoor, text\n\nFor currentDoor = 0 To 99\n\tdoorIsOpen(currentDoor) = False\nNext\n\nFor pass = 0 To 99\n\tFor currentDoor = pass To 99 Step pass + 1\n\t\tdoorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)\n\tNext\nNext\n\nFor currentDoor = 0 To 99\n\ttext = \"Door #\" & currentDoor + 1 & \" is \"\n\tIf doorIsOpen(currentDoor) Then\n\t\ttext = text & \"open.\"\n\tElse\n\t\ttext = text & \"closed.\"\n\tEnd If\n\tWScript.Echo(text)\nNext", "safe": true }, { "filename": "100 doors_727.txt", "content": "Buf_Switch(Buf_Free)\nIns_Char('-', COUNT, 100) // All doors closed\nfor (#1 = 1; #1 <= 100; #1++) {\n for (#2 = #1; #2 <= 100; #2 += #1) {\n Goto_Col(#2)\n Ins_Char((Cur_Char^0x62), OVERWRITE) // Toggle between '-' and 'O'\n }\n}", "safe": true }, { "filename": "100 doors_728.txt", "content": "Buf_Switch(Buf_Free)\nIns_Char('-', COUNT, 100)\nfor (#1=1; #1 <= 10; #1++) {\n Goto_Col(#1*#1)\n Ins_Char('O', OVERWRITE)\n}", "safe": true }, { "filename": "100 doors_729.txt", "content": "O--O----O------O--------O----------O------------O--------------O----------------O------------------O\n", "safe": true }, { "filename": "100 doors_73.txt", "content": "main()\n{\n auto doors[100]; /*\u00a0!= 0 means open */\n auto pass, door;\n\n door = 0;\n while( door<100 ) doors[door++] = 0;\n\n pass = 0;\n while( pass<100 )\n {\n door = pass;\n while( door<100 )\n {\n doors[door] = !doors[door];\n door =+ pass+1;\n }\n ++pass;\n }\n\n door = 0;\n while( door<100 )\n {\n printf(\"door #%d is %s.*n\", door+1, doors[door]\u00a0? \"open\"\u00a0: \"closed\");\n ++door;\n }\n\n return(0);\n}", "safe": true }, { "filename": "100 doors_730.txt", "content": "module main;\n integer i;\n \n initial begin\n $display(\"Las siguientes puertas est\u00e1n abiertas:\");\n for (i=1; i<=10; i=i+1) if (i%i*i<11) $display(i*i);\n $finish\u00a0;\n end\nendmodule", "safe": true }, { "filename": "100 doors_731.txt", "content": "library IEEE;\nuse IEEE.STD_LOGIC_1164.ALL;\n\nentity DOORS is\n\tport (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100));\nend DOORS;\n\narchitecture Behavioral of DOORS is\nbegin\n\tprocess (CLK)\n\tvariable TEMP: std_logic_vector(1 to 100);\n\tbegin\n\t\t--setup closed doors\n\t\tTEMP\u00a0:= (others => '0');\n\t\t\n\t\t--looping through\n\t\tfor i in 1 to TEMP'length loop\n\t\t\tfor j in i to TEMP'length loop\n\t\t\t\tif (j mod i) = 0 then\n\t\t\t\t\tTEMP(j)\u00a0:= not TEMP(j);\n\t\t\t\tend if;\n\t\t\tend loop;\n\t\tend loop;\n\t\t\n\t\t--assign output\n\t\tOUTPUT <= TEMP;\n\tend process;\nend Behavioral;", "safe": true }, { "filename": "100 doors_732.txt", "content": "LIBRARY ieee;\nUSE ieee.std_logic_1164.all;\n\n\nentity doors is\n port (\n clk \u00a0: in std_logic;\n reset\u00a0: in std_logic;\n door \u00a0: buffer std_logic_vector(1 to 100)\n );\nend entity doors;\n\n\narchitecture rtl of doors is\n signal step\u00a0: integer range 1 to 101;\n signal addr\u00a0: integer range 1 to 201;\nbegin\n proc_step: process(clk, reset)\n begin\n if reset = '1' then\n step <= 1;\n addr <= 1;\n door <= (others => '0');\n elsif rising_edge(clk) then\n if addr <= 100 then\n door(addr) <= not door(addr);\n addr <= addr + step;\n elsif step <= 100 then\n addr <= step + 1;\n step <= step + 1;\n end if;\n end if;\n end process;\nend;", "safe": true }, { "filename": "100 doors_733.txt", "content": "Public Sub Doors100()\n ' the state of a door is represented by the data type boolean (false = door closed, true = door opened)\n Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false'\n Dim i As Long, j As Long\n \n For i = 1 To 100\n For j = i To 100 Step i\n doorstate(j) = Not doorstate(j)\n Next j\n Next i\n \n Debug.Print \"The following doors are open:\"\n For i = 1 To 100\n ' print number if door is openend\n If doorstate(i) Then Debug.Print CStr(i)\n Next i\nEnd Sub", "safe": true }, { "filename": "100 doors_734.txt", "content": "The following doors are open:\n1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100 doors_735.txt", "content": "Module Module1\n\n Sub Main()\n Dim doors(100) As Boolean 'Door 1 is at index 0\n\n For pass = 1 To 100\n For door = pass - 1 To 99 Step pass\n doors(door) = Not doors(door)\n Next\n Next\n\n For door = 0 To 99\n Console.WriteLine(\"Door # \" & (door + 1) & \" is \" & If(doors(door), \"Open\", \"Closed\"))\n Next\n\n Console.ReadLine()\n End Sub\n\nEnd Module", "safe": true }, { "filename": "100 doors_736.txt", "content": "Module Module1\n\n Sub Main()\n Dim doors(100) As Boolean 'Door 1 is at index 0\n\n For i = 1 To 10\n doors(i ^ 2 - 1) = True\n Next\n\n For door = 0 To 99\n Console.WriteLine(\"Door # \" & (door + 1) & \" is \" & If(doors(door), \"Open\", \"Closed\"))\n Next\n\n Console.ReadLine()\n End Sub\n\nEnd Module", "safe": true }, { "filename": "100 doors_737.txt", "content": "const number_doors = 101\n\nfn main() {\n mut closed_doors\u00a0:= []bool{len: number_doors, init: true} \n for pass in 0..number_doors {\n for door\u00a0:= 0; door < number_doors; door += pass + 1 {\n closed_doors[door] = !closed_doors[door]\n }\n }\n for pass in 1..number_doors {\n if !closed_doors[pass] {\n println('Door #$pass Open')\n }\n }\n}", "safe": true }, { "filename": "100 doors_738.txt", "content": "Door #1 Open\nDoor #4 Open\nDoor #9 Open\nDoor #16 Open\nDoor #25 Open\nDoor #36 Open\nDoor #49 Open\nDoor #64 Open\nDoor #81 Open\nDoor #100 Open\n", "safe": true }, { "filename": "100 doors_739.txt", "content": "const door_number = 100\n\nfn main(){\n mut doors\u00a0:= []bool{ len: door_number, init: false } //true open false closed\n\n mut door_nbr\u00a0:= 1\n mut increment\u00a0:= 0\n\n for current in 1..( door_number + 1) {\n if current == door_nbr {\n doors[current - 1] = true\n increment++\n door_nbr += 2 * increment + 1\n\t\t\tprint('O')\n\t\t} else {\n\t\t\tprint('=')\n\t\t}\n }\n println('')\n}", "safe": true }, { "filename": "100 doors_74.txt", "content": " * NB: the implementation is rather vanilla\n * besides using the idiomatic buffer overrun.\n * LOOP is what PERFORM in COBOL is, with defaults.\n * MOVE in this language acts like OVE CORRESPONDING,\n * which is actually good here.\n IDENTIFICATION DIVISION.\n PROGRAM-ID. ONE HUNDRED DOORS.\n DATA DIVISION.\n 01 I PICTURE IS 9(3).\n 01 J LIKE I.\n 01 DOOR PICTURE IS 9 OCCURS 100 TIMES.\n 01 STOP LIKE DOOR.\n PROCEDURE DIVISION.\n * Initialise the data\n MOVE HIGH-VALUES TO STOP\n MOVE SPACES TO DOOR.\n * Do the main algorithm\n LOOP VARYING I UNTIL DOOR(I) = 9\n LOOP VARYING J FROM I TO 100 BY I\n SUBTRACT DOOR (J) FROM 1 GIVING DOOR (J)\n END\n END.\n * Print the results\n LOOP VARYING I UNTIL DOOR(I) = 9\n DISPLAY \"Door\" I \"is\" WITH NO ADVANCING\n IF DOOR (I) = 1\n THEN DISPLAY \"open\"\n ELSE DISPLAY \"closed\".\n END.\n", "safe": true }, { "filename": "100 doors_740.txt", "content": "O==O====O======O========O==========O============O==============O================O==================O\n", "safe": true }, { "filename": "100 doors_741.txt", "content": "fn main() {\n\tfor i in 1..11 {\n\t\tprint ( \" Door ${i*i} is open.\\n\" )\n\t}\n}", "safe": true }, { "filename": "100 doors_742.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.\n", "safe": true }, { "filename": "100 doors_743.txt", "content": "10 D=1\n20 :D)=0\n30 D=D+1\n40 #=100>D*20\n50 P=1\n60 D=P\n70 :D)=:D)=0\n80 D=D+P\n90 #=100>D*70\n100 P=P+1\n110 #=100>P*60\n120 D=1\n130 #=:D)*170\n140 D=D+1\n150 #=100>D*130\n160 #=999\n170\u00a0?=\"DOOR \";\n180\u00a0?=D\n190\u00a0?=\" IS OPEN\"\n200 #=!", "safe": true }, { "filename": "100 doors_744.txt", "content": "DOOR 1 IS OPEN\nDOOR 4 IS OPEN\nDOOR 9 IS OPEN\nDOOR 16 IS OPEN\nDOOR 25 IS OPEN\nDOOR 36 IS OPEN\nDOOR 49 IS OPEN\nDOOR 64 IS OPEN\nDOOR 81 IS OPEN\nDOOR 100 IS OPEN", "safe": true }, { "filename": "100 doors_745.txt", "content": "def (doors n)\n let door (table)\n for step 1 (step <= n) ++step\n for j 0 (j < n) (j <- j+step)\n zap! not door.j\n\n for j 0 (j < n) ++j\n when door.j\n pr j\n pr \" \"", "safe": true }, { "filename": "100 doors_746.txt", "content": "let a => import 'arrays';\nlet s => import 'stream';\nlet io => import 'io';\n\nlet toggle doors m =>\n\ta.stream doors\n\t-> s.enumerate\n\t-> s.map (@ s n => [+ (a.at n 0) 1; a.at n 1])\n\t-> s.map (@ s n => switch n {\n\t\t\t(@ s n => == (% (a.at n 0) m) 0) =>\u00a0! (a.at n 1);\n\t\t\ttrue => a.at n 1;\n\t\t})\n\t-> s.collect\n\t;\n\ns.range 100\n-> s.map false\n-> s.collect\u00a0: doors\n-> s.range 1 100\n-> s.reduce doors toggle\n-> a.stream\n-> s.map (@ s n => switch 0 {\n\t\tn => 'Open';\n\t\ttrue => 'Closed';\n\t} -- io.writeln io.stdout)\n-> s.drain\n;", "safe": true }, { "filename": "100 doors_747.txt", "content": "; unoptimized\n+^[\n @var doors []\n \n @for i rangei [1 100]\n @for j rangei [i 100 i]\n \u00a0:!@not `j doors\n \n @for i rangei [1 100]\n @if `i doors\n !console.log \"door {i} is open\"\n]\n; optimized, map square over 1 to 10\n!*^@sq @to 10", "safe": true }, { "filename": "100 doors_748.txt", "content": "MOD Doors;\n\nIMP Agg.Table;\nIMP Std.String;\nIMP IO.Terminal USE Out;\n\nVAR door <- {}; EVERY door[1:to(100), \"closed\"];\n\nDEF toggle(num) door[num] <- door[num] = \"open\" => \"closed\" // \"open\";\n\nEVERY WITH pass <- 1:to(100), num <- pass:to(100, pass) DO toggle(num);\n\nOut:write('Doors {door @ String.T}.');\n\nEND Doors.", "safe": true }, { "filename": "100 doors_749.txt", "content": "MOD Doors;\n\nIMP IO.Terminal USE Out;\n\nDEF open <- ALL 1:to(100) ^ 2 \\ $ <= 100;\nDEF closed <- ALL 1:to(100) \\ NOT $ IN open;\n\nOut:write('Doors {open} are open.\\n');\nOut:write('Doors {closed} are closed.\\n');\n\nEND Doors.", "safe": true }, { "filename": "100 doors_75.txt", "content": "OPTION BASE 1\n\nDECLARE doors[100]\n\nFOR size = 1 TO 100\n FOR pass = 0 TO 100 STEP size\n\tdoors[pass] = NOT(doors[pass])\n NEXT\nNEXT\n\nFOR which = 1 TO 100\n IF doors[which] THEN PRINT which\nNEXT\n", "safe": true }, { "filename": "100 doors_750.txt", "content": "var doors = [true] * 100\nfor (i in 1..100) {\n var j = i\n while (j < 100) {\n doors[j] = !doors[j]\n j = j + i + 1\n }\n}\n\nfor (i in 0...100) {\n if (doors[i]) System.write(\"%(i + 1) \")\n}\nSystem.print()", "safe": true }, { "filename": "100 doors_751.txt", "content": "var door = 1\nvar increment = 3\nwhile (door <= 100) {\n System.write(\"%(door) \")\n door = door + increment\n increment = increment + 2\n}\nSystem.print()", "safe": true }, { "filename": "100 doors_752.txt", "content": "1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100 doors_753.txt", "content": "\t\t.NOLIST\n\n; The task can be completed in 48 and \"half\" steps:\n; On the first pass ALL doors are opened.\n; On the second pass every EVEN door is closed.\n; So, instead of all closed, the doors can initially be:\n; Every odd door open, every even door closed and start at pass 3.\n; On 51st and all the next passes, only one door is visited per pass:\n; On 51st pass door 51, on 52nd pass door 52 etc.\n; So, after pass 50, we can make \"half a pass\" starting with door 51\n; and toggling every door up to and including 100.\n; The code uses only volatile registers, so, no string (STOS etc) instructions.\n\n\t\tTITLE\t100 Doors\n\t\tPAGE\t, 132\n\t\t.686\n\t\t.MODEL\tFLAT\n\t\tOPTION\tCASEMAP:NONE\n\n\t\t.SFCOND\n\t\t.LIST\n\n; =============================================================================\n\n\t\t.DATA?\n\nDoors\t\tBYTE\t100 DUP (\u00a0? )\n\n; =============================================================================\n\n\t\t.CODE\n\nPass_Doors\tPROC\n\n\t\tMOV\tEDX, OFFSET Doors\t; Initialize all doors.\n\t\tMOV\tECX, SIZEOF Doors / SIZEOF DWORD\n\t\tMOV\tEAX, 01010101h\t\t; This does first and second pass.\n\nClose_Doors:\tMOV\t[ EDX ], EAX\n\t\tADD\tEDX, SIZEOF DWORD\n\t\tLOOP\tClose_Doors\n\n\t\tMOV\tECX, 2\t\t\t; Pass and step.\n\nPass_Loop:\tMOV\tEDX, OFFSET Doors\n\n\t\tASSUME\tEDX:PTR BYTE\n\nDoors_Loop:\tXOR\t[ EDX ], 1\t\t; Toggle this door.\n\t\tADD\tEDX, ECX \u00a0; Advance.\n\t\tCMP\tEDX, OFFSET Doors[ SIZEOF Doors ]\n\n\t\tJB\tDoors_Loop\n\n\t\tINC\tECX\n\t\tCMP\tECX, SIZEOF Doors\n\n\t\tJB\tPass_Loop\n\n\t\tXOR\tDoors[ SIZEOF Doors -1 ], 1\u00a0; This is pass 100.\n\t\tRET\n\nPass_Doors\tENDP\n\n; =============================================================================\n\n\t\tEND", "safe": true }, { "filename": "100 doors_754.txt", "content": "PROGRAM \"100doors\"\nVERSION \"0.0001\"\n\nIMPORT \"xma\"\nIMPORT \"xst\"\n\nDECLARE FUNCTION Entry()\n\nFUNCTION Entry()\n maxpuertas = 100\n cont = 0\n DIM puertas[100]\n\n FOR p = 1 TO maxpuertas\n IF INT(SQRT(p)) = SQRT(p) THEN puertas[p] = 1\n NEXT p\n\n PRINT \"The doors are open: \";\n FOR p = 1 TO maxpuertas\n IF puertas[p] = 1 THEN\n PRINT p; \" \";\n INC cont\n END IF\n NEXT p\n\n PRINT CHR$(10); \"Are \"; STR$(cont); \" open doors.\"\n\nEND FUNCTION\nEND PROGRAM", "safe": true }, { "filename": "100 doors_755.txt", "content": "// True=Open; False=Closed\nDim doors(100) As Boolean // Booleans default to false\nFor j As Integer = 1 To 100\n For i As Integer = 1 to 100\n If i Mod j = 0 Then doors(i) = Not doors(i)\n Next\nNext", "safe": true }, { "filename": "100 doors_756.txt", "content": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nint Door(100); \\You have 100 doors in a row\ndefine Open, Closed;\nint D, Pass, Step;\n\n[for D:= 0 to 100-1 do \\that are all initially closed\n Door(D):= Closed;\n\nStep:= 1; \\The first time through, you visit every door\nfor Pass:= 1 to 100 do \\You make 100 passes by the doors\n [D:= Step-1;\n repeat \\if the door is closed, you open it; if it is open, you close it\n if Door(D)=Closed then Door(D):= Open else Door(D):= Closed;\n D:= D+Step;\n until D>=100;\n Step:= Step+1; \\The second time you only visit every 2nd door\n ]; \\The third time, every 3rd door\n \\until you only visit the 100th door\n\\What state are the doors in after the last pass?\nText(0, \"Open: \"); \\Which are open?\nfor D:= 0 to 100-1 do \n if Door(D)=Open then [IntOut(0, D+1); ChOut(0,^ )];\nCrLf(0);\n\nText(0, \"Closed: \"); \\Which are closed?\nfor D:= 0 to 100-1 do \n if Door(D)=Closed then [IntOut(0, D+1); ChOut(0,^ )];\nCrLf(0);\n\n\\Optimized: The only doors that remain open are those that are perfect squares\nText(0, \"Open: \");\nD:= 1;\nrepeat IntOut(0, D*D); ChOut(0,^ );\n D:= D+1;\nuntil D*D>100;\nCrLf(0);\n]", "safe": true }, { "filename": "100 doors_757.txt", "content": "\n closed\n closed\n closed\n closed\n ... etc ...\n closed\n", "safe": true }, { "filename": "100 doors_758.txt", "content": "\n\n\n\n \n \n \n\n \n\n \n \n \n \n !\n \n \n \n \n \n \n open\n \n \n closed\n \n \n \n\n \n", "safe": true }, { "filename": "100 doors_759.txt", "content": "\n\n\n\n \n \n \n \n \n \n \n \n\n \n", "safe": true }, { "filename": "100 doors_76.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100 doors_760.txt", "content": "n = 100\t// doors\nppa = 1\t// next open door\np2 = 1\n\nfor i = 1 to n\n\tprint \"Door \", i, \" is \";\n\tif i < p2 then\n\t\tprint \"closed.\"\n\telse\n\t\tppa = ppa + 1\n\t\tp2 = ppa^2\n\t\tprint \"OPEN.\"\n\tend if\nnext", "safe": true }, { "filename": "100 doors_761.txt", "content": "for i = 1 to sqrt(100)\u00a0: print \"Door \", i**2, \" is open\"\u00a0: next", "safe": true }, { "filename": "100 doors_762.txt", "content": "!yamlscript/v0\n\ndefn main():\n open =:\n reduce _ vec([true] * 100) (1 .. 100):\n fn(doors i):\n loop j i, doors doors:\n if j < 100:\n recur (j + i).++:\n update-in doors [j]: \\(doors.$j.!)\n else: doors\n say: -\"Open doors after 100 passes:\\ \" +\n (1 .. 100).map(\\(_.--:open && _))\n .filter(a).join(', ')", "safe": true }, { "filename": "100 doors_763.txt", "content": "$ ys 100-doors.ys\nOpen doors after 100 passes: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100 doors_764.txt", "content": "doors = array(0, 100);\nfor(i = 1; i <= 100; i++)\n for(j = i; j <= 100; j += i)\n doors(j) ~= 1;\nprint, where(doors);", "safe": true }, { "filename": "100 doors_765.txt", "content": "doors = array(0, 100);\nfor(i = 1; i <= 100; i++)\n doors(i::i) ~= 1;\nprint, where(doors);", "safe": true }, { "filename": "100 doors_766.txt", "content": "print, indgen(1:long(sqrt(100)))^2", "safe": true }, { "filename": "100 doors_767.txt", "content": "[1,4,9,16,25,36,49,64,81,100]\n", "safe": true }, { "filename": "100 doors_768.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n \n var doors = [_]bool{false} ** 101;\n var pass: u8 = 1;\n var door: u8 = undefined;\n \n while (pass <= 100)\u00a0: (pass += 1) {\n door = pass;\n while (door <= 100)\u00a0: (door += pass)\n doors[door] = !doors[door];\n }\n \n for (doors, 0..) |open, num|\n if (open) \n try stdout.print(\"Door {d} is open.\\n\", .{num});\n}", "safe": true }, { "filename": "100 doors_769.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n \n var square: u8 = 1;\n var increment: u8 = 3;\n var door: u8 = 1;\n while (door <= 100)\u00a0: (door += 1) {\n if (door == square) {\n try stdout.print(\"Door {d} is open\\n\", .{door});\n square += increment;\n increment += 2;\n }\n }\n}", "safe": true }, { "filename": "100 doors_77.txt", "content": "const NUM_DOORS\u00a0:= 100\n\nfun main() {\n\t// All doors are closed by default (`false`)\n\tmut is_open\u00a0:= []bool{length = NUM_DOORS}\n\n\t// Make 100 passes by the doors\n\tfor pass\u00a0:= 0; pass < 100; pass += 1 {\n\t\t// Only visit every `pass + 1`th door\n\t\tfor door\u00a0:= pass; door < NUM_DOORS; door += pass + 1 {\n\t\t\tis_open[door] = not is_open[door]\n\t\t}\n\t}\n\n\t// Print the doors that are open\n\tfor i, open in is_open {\n\t\tif open {\n\t\t\tprintln(\"Door #${i + 1} is open.\")\n\t\t}\n\t}\n\n}", "safe": true }, { "filename": "100 doors_770.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n\n var square: u8 = 1;\n var increment: u8 = 3;\n for (1..101) |door| {\n if (door == square) {\n try stdout.print(\"Door {d} is open\\n\", .{door});\n square += increment;\n increment += 2;\n }\n }\n}", "safe": true }, { "filename": "100 doors_771.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n\n var door: u8 = 1;\n while (door * door <= 100)\u00a0: (door += 1) {\n try stdout.print(\"Door {d} is open\\n\", .{door * door});\n }\n}", "safe": true }, { "filename": "100 doors_772.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100 doors_773.txt", "content": "doors:=List.createLong(100,False);\t// list of 100 Falses\nforeach n,m in (100,[n..99,n+1]){ doors[m]=(not doors[m]); } //foreach{ foreach{} }\ndoors.filterNs().apply('+(1)).println();", "safe": true }, { "filename": "100 doors_774.txt", "content": "L(1,4,9,16,25,36,49,64,81,100)", "safe": true }, { "filename": "100 doors_775.txt", "content": " 10 REM 100 doors open/closed?\n 20 DIM d(100)\n 25 LET o=0\n 30 FOR a=1 TO 100\n 40 FOR b=a TO 100 STEP a\n 50 LET d(b)=NOT d(b)\n 55 LET o=o+(d(b)=1)-(d(b)=0)\n 60 NEXT b\n 70 NEXT a\n 80 PRINT o;\" open doors\"\n", "safe": true }, { "filename": "100 doors_776.txt", "content": " 10 REM 100 doors open/closed?\n 20 DIM d(100)\n 25 GO SUB 170\n 30 FOR a=1 TO 100\n 35 PRINT AT 0,0;\"step \";a\n 40 FOR b=a TO 100 STEP a\n 45 PRINT AT 0,10;\"door:\";b;\" \"\n 50 LET d(b)=NOT d(b)\n 55 GO SUB 150\n 60 NEXT b\n 70 NEXT a\n 80 GO SUB 170\n 90 STOP \n150 REM print door status\n151 LET p=(b-1)/10\n152 LET q=1+10*(p-INT p)\n153 LET p=INT p\n154 LET op=op+(d(b)=1)-(d(b)=0)\n156 PRINT AT 2*p+2,2*q;d(b);AT 0,27;op;\" \"\n160 RETURN \n165 REM print step status\n170 LET op=0\n175 FOR p=0 TO 9\n180 FOR q=1 TO 10\n185 PRINT AT 2*p+2,2*q;d(p*10+q)\n188 LET op=op+d(p*10+q)\n190 NEXT q\n200 NEXT p\n205 PRINT AT 0,22;\"open:\";op;\" \"\n210 RETURN\n", "safe": true }, { "filename": "100 doors_78.txt", "content": "Door #1 is open.\nDoor #4 is open.\nDoor #9 is open.\nDoor #16 is open.\nDoor #25 is open.\nDoor #36 is open.\nDoor #49 is open.\nDoor #64 is open.\nDoor #81 is open.\nDoor #100 is open.\n", "safe": true }, { "filename": "100 doors_79.txt", "content": " 100 :\n 110 REM 100 DOORS PROBLEM\n 120 :\n 130 DIM D(100)\n 140 FOR P = 1 TO 100\n 150 FOR T = P TO 100 STEP P\n 160 D(T) = NOT D(T): NEXT T\n 170 NEXT P\n 180 FOR I = 1 TO 100\n 190 IF D(I) THEN PRINT I;\" \";\n 200 NEXT I\n", "safe": true }, { "filename": "100 doors_8.txt", "content": " ;assumes memory at $02xx is initially set to 0 and stack pointer is initialized\n ;the 1 to 100 door byte array will be at $0200-$0263 (decimal 512 to 611)\n ;Zero-page location $01 will hold delta\n ;At end, closed doors = $00, open doors = $01\n\nstart: ldx #0 ;initialize index - first door will be at $200 + $0\n stx $1\n inc $1 ;start out with a delta of 1 (0+1=1)\nopenloop: inc $200,X ;open X'th door\n inc $1 ;add 2 to delta\n inc $1\n txa ;add delta to X by transferring X to A, adding delta to A, then transferring back to X\n clc \u00a0; clear carry before adding (6502 has no add-without-carry instruction)\n adc $1\n tax\n cpx #$64 ;check to see if we're at or past the 100th door (at $200 + $63)\n bmi openloop ;jump back to openloop if less than 100", "safe": true }, { "filename": "100 doors_80.txt", "content": " \n]RUN\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_81.txt", "content": "# 100 doors problem\ndim d(100)\n\n# simple solution\nprint \"simple solution\"\ngosub initialize\nfor t = 1 to 100\n for j = t to 100 step t\n d[j-1] = not d[j-1]\n next j\nnext t\ngosub showopen\n\n# more optimized solution\nprint \"more optimized solution\"\ngosub initialize\nfor t = 1 to 10\n d[t^2-1] = true\nnext t\ngosub showopen\nend\n\ninitialize:\nfor t = 1 to d[?]\n d[t-1] = false\t # closed\nnext t\nreturn\n\nshowopen:\nfor t = 1 to d[?]\n print d[t-1]+ \" \";\n if t%10 = 0 then print\nnext t\nreturn", "safe": true }, { "filename": "100 doors_82.txt", "content": "for i = 1 to 10 : if i % i^2 < 11 then print \"La puerta \"; int(i^2); \" esta abierta\" : end if : next i : end\n", "safe": true }, { "filename": "100 doors_83.txt", "content": "dim doors%(100)\n\nprint \"Finding solution to the 100 Doors Problem\"\n\nrem - all doors are initially closed\nfor i% = 1 to 100\n doors%(i%) = 0\nnext i%\n\nrem - pass through at increasing intervals\nfor i% = 1 to 100\n for j% = i% to 100 step i%\n rem - flip each door encountered\n doors%(j%) = 1 - doors%(j%)\n next j%\nnext i%\n\nrem - show which doors are open\nprint \"The open doors are: \";\nfor i% = 1 to 100\n if doors%(i%) = 1 then print i%;\nnext i%\n\nprint\nprint \"Thanks for consulting the puzzle guru!\"\n\nend\n", "safe": true }, { "filename": "100 doors_84.txt", "content": "Finding solution to the 100 Doors Problem\nThe open doors are: 1 4 9 15 25 36 47 64 81 100\nThanks for consulting the puzzle guru!\n", "safe": true }, { "filename": "100 doors_85.txt", "content": "100 CLS : REM 10 HOME for Applesoft BASIC\n110 DIM D(100)\n120 FOR P = 1 TO 100\n130 FOR T = P TO 100 STEP P\n140 D(T) = NOT D(T)\n150 NEXT T\n160 NEXT P\n170 ' Print \"opened\" doors\n180 FOR I = 1 TO 100\n190 IF D(I) THEN PRINT I;\" \";\n200 NEXT I\n210 END\n", "safe": true }, { "filename": "100 doors_86.txt", "content": ">RUN\n1 4 9 16 25 36 49 64 81 100 >", "safe": true }, { "filename": "100 doors_87.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=I TO 100 STEP I\n40 D(J) = NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I,\n90 NEXT I\n", "safe": true }, { "filename": "100 doors_88.txt", "content": "100 CLS : REM 10 HOME for Applesoft BASIC\n110 DIM D(100)\n120 FOR P = 1 TO 100\n130 FOR T = P TO 100 STEP P\n140 D(T) = NOT D(T)\n150 NEXT T\n160 NEXT P\n170 ' Print \"opened\" doors\n180 FOR I = 1 TO 100\n190 IF D(I) THEN PRINT I;\" \";\n200 NEXT I\n210 END\n", "safe": true }, { "filename": "100 doors_89.txt", "content": " 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_9.txt", "content": "*-----------------------------------------------------------\n* Title : 100Doors.X68\n* Written by : G. A. Tippery\n* Date : 2014-01-17\n* Description: Solves \"100 Doors\" problem, see: http://rosettacode.org/wiki/100_doors\n* Notes : Translated from C \"Unoptimized\" version, http://rosettacode.org/wiki/100_doors#unoptimized\n* : No optimizations done relative to C version; \"for(\"-equivalent loops could be optimized.\n*-----------------------------------------------------------\n\n*\n* System-specific general console I/O macros (Sim68K, in this case)\n*\nPUTS MACRO\n ** Print a null-terminated string w/o CRLF **\n ** Usage: PUTS stringaddress\n ** Returns with D0, A1 modified\n MOVEQ #14,D0 ; task number 14 (display null string)\n LEA \\1,A1 ; address of string\n TRAP #15 ; display it\n ENDM\n*\nPRINTN MACRO\n ** Print decimal integer from number in register\n ** Usage: PRINTN register\n ** Returns with D0,D1 modified\n IFNC '\\1','D1' ;if some register other than D1\n MOVE.L \\1,D1 ;put number to display in D1\n ENDC\n MOVE.B #3,D0\n TRAP #15 ;display number in D1\n*\n* Generic constants\n*\nCR EQU 13 ;ASCII Carriage Return\nLF EQU 10 ;ASCII Line Feed\n\n*\n* Definitions specific to this program\n*\n* Register usage:\n* D3 == pass (index)\n* D4 == door (index)\n* A2 == Doors array pointer\n*\nSIZE EQU 100 ;Define a symbolic constant for # of doors\n\n ORG $1000 ;Specify load address for program -- actual address system-specific\nSTART: ; Execution starts here\n LEA Doors,A2 ; make A2 point to Doors byte array\n MOVEQ #0,D3\nPassLoop:\n CMP #SIZE,D3\n BCC ExitPassLoop ; Branch on Carry Clear - being used as Branch on Higher or Equal\n MOVE D3,D4\nDoorLoop:\n CMP #SIZE,D4\n BCC ExitDoorLoop\n NOT.B 0(A2,D4)\n ADD D3,D4\n ADDQ #1,D4\n BRA DoorLoop\nExitDoorLoop:\n ADDQ #1,D3\n BRA PassLoop\nExitPassLoop:\n\n* $28 = 40. bytes of code to this point. 32626 cycles so far.\n* At this point, the result exists as the 100 bytes starting at address Doors.\n* To get output, we must use methods specific to the particular hardware, OS, or\n* emulator system that the code is running on. I use macros to \"hide\" some of the\n* system-specific details; equivalent macros would be written for another system.\n\n MOVEQ #0,D4\nPrintLoop:\n CMP #SIZE,D4\n BCC ExitPrintLoop\n PUTS DoorMsg1\n MOVE D4,D1\n ADDQ #1,D1 ; Convert index to 1-based instead of 0-based\n PRINTN D1\n PUTS DoorMsg2\n TST.B 0(A2,D4) ; Is this door open (!= 0)?\n BNE ItsOpen\n PUTS DoorMsgC\n BRA Next\nItsOpen:\n PUTS DoorMsgO\nNext:\n ADDQ #1,D4\n BRA PrintLoop\nExitPrintLoop:\n\n* What to do at end of program is also system-specific\n SIMHALT ;Halt simulator\n*\n* $78 = 120. bytes of code to this point, but this will depend on how the I/O macros are actually written.\n* Cycle count is nearly meaningless, as the I/O hardware and routines will dominate the timing.\n\n*\n* Data memory usage\n*\n ORG $2000\nDoors DCB.B SIZE,0 ;Reserve 100 bytes, prefilled with zeros\n\nDoorMsg1 DC.B 'Door ',0\nDoorMsg2 DC.B ' is ',0\nDoorMsgC DC.B 'closed',CR,LF,0\nDoorMsgO DC.B 'open',CR,LF,0\n\n END START ;last line of source\n", "safe": true }, { "filename": "100 doors_90.txt", "content": "100 PROGRAM \"100doors.bas\"\n110 NUMERIC D(1 TO 100)\n120 FOR I=1 TO 100\n130 LET D(I)=0\n140 NEXT\n150 FOR I=1 TO 100\n160 FOR J=I TO 100 STEP I\n170 LET D(J)=NOT D(J)\n180 NEXT \n190 NEXT\n200 FOR I=1 TO 100\n210 IF D(I) THEN PRINT I\n220 NEXT", "safe": true }, { "filename": "100 doors_91.txt", "content": "100 PROGRAM \"100doors.bas\"\n110 LET NR=1:LET D=3\n120 DO\n130 PRINT NR\n140 LET NR=NR+D:LET D=D+2\n150 LOOP WHILE NR<=100", "safe": true }, { "filename": "100 doors_92.txt", "content": "10 PRINT \"FOLLOWING DOORS ARE OPEN:\"\n20 LET I = 0\n30 REM LOOP\n40 LET I = I + 1\n50 PRINT I * I; \" \";\n60 IF I * I < 100 THEN 30\n70 END\n", "safe": true }, { "filename": "100 doors_93.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=i TO 100 STEP I\n40 D(J)=NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I;\n90 NEXT I\n100 END\n", "safe": true }, { "filename": "100 doors_94.txt", "content": " \n]RUN\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100 doors_95.txt", "content": "REM \"100 Doors\" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler.\nREM Author: G. A. Tippery\nREM Date: 12-Feb-2014\nREM\nREM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors\n\nDEFINT A-Z\nCONST N = 100\nDIM door(N)\n\nFOR stride = 1 TO N\n FOR index = stride TO N STEP stride\n LET door(index) = NOT (door(index))\n NEXT index\nNEXT stride\n\nPRINT \"Open doors:\"\nFOR index = 1 TO N\n IF door(index) THEN PRINT index\nNEXT index\n\nEND\n", "safe": true }, { "filename": "100 doors_96.txt", "content": "DIM doors(0 TO 99)\nFOR pass = 0 TO 99\n\tFOR door = pass TO 99 STEP pass + 1\n\t\tPRINT doors(door)\n\t\tPRINT NOT doors(door)\n\t\tdoors(door) = NOT doors(door)\n\tNEXT door\nNEXT pass\nFOR i = 0 TO 99\n\tPRINT \"Door #\"; i + 1; \" is \";\n\tIF NOT doors(i) THEN\n\t\tPRINT \"closed\"\n\tELSE\n\t\tPRINT \"open\"\n\tEND IF\nNEXT i\n", "safe": true }, { "filename": "100 doors_97.txt", "content": "DIM doors(0 TO 99)\nFOR door = 0 TO 99\n\tIF INT(SQR(door)) = SQR(door) THEN doors(door) = -1\nNEXT door\nFOR i = 0 TO 99\n\tPRINT \"Door #\"; i + 1; \" is \";\n\tIF NOT doors(i) THEN\n\t\tPRINT \"closed\"\n\tELSE\n\t\tPRINT \"open\"\n\tEND IF\nNEXT i\n", "safe": true }, { "filename": "100 doors_98.txt", "content": "100 ARRAY D\n110 FOR P = 1 TO 100\n120 FOR T = P TO 100 STEP P\n130 LET D[T] = (D[T] <> 1)\n140 NEXT T\n150 NEXT P\n160 FOR I = 1 TO 100\n170 IF D[I] THEN PRINT I;\" \";\n180 NEXT I\n190 END\n", "safe": true }, { "filename": "100 doors_99.txt", "content": " PRINT \"Open doors are:\"\n\n LET I = 1\n10 IF I = 100 THEN END \n rem funcion SQR\n LET B = I*I\n rem funcion MODULO\n LET A = I - (I / B) * B\n IF A < 11 THEN PRINT B\n LET I = I + 1\n GOTO 10", "safe": true }, { "filename": "100 prisoners_1.txt", "content": "F play_random(n)\n V pardoned = 0\n V in_drawer = Array(0.<100)\n V sampler = Array(0.<100)\n L 0 .< n\n random:shuffle(&in_drawer)\n V found = 0B\n L(prisoner) 100\n found = 0B\n L(reveal) random:sample(sampler, 50)\n V card = in_drawer[reveal]\n I card == prisoner\n found = 1B\n L.break\n I !found\n L.break\n I found\n pardoned++\n R Float(pardoned) / n * 100\n\nF play_optimal(n)\n V pardoned = 0\n V in_drawer = Array(0.<100)\n L 0 .< n\n random:shuffle(&in_drawer)\n V found = 0B\n L(prisoner) 100\n V reveal = prisoner\n found = 0B\n L 50\n V card = in_drawer[reveal]\n I card == prisoner\n found = 1B\n L.break\n reveal = card\n I !found\n L.break\n I found\n pardoned++\n R Float(pardoned) / n * 100\n\nV n = 100'000\nprint(\u2018 Simulation count: \u2019n)\nprint(\u2018 Random play wins: #2.1% of simulations\u2019.format(play_random(n)))\nprint(\u2018Optimal play wins: #2.1% of simulations\u2019.format(play_optimal(n)))", "safe": true }, { "filename": "100 prisoners_10.txt", "content": "Optimal Strategy = 31.80%\nRandom Strategy = 0.00%\n", "safe": true }, { "filename": "100 prisoners_100.txt", "content": "a:=[seq(max(GroupTheory[PermCycleType](Perm(Statistics[Shuffle]([$1..100])))),i=1..100000)]:\nnops(select(n->n<=50,a))/nops(a);\nevalf(%);\n# 31239/100000\n# 0.3123900000", "safe": true }, { "filename": "100 prisoners_101.txt", "content": "1-(harmonic(100)-harmonic(50));\nevalf(%);\n\n# 21740752665556690246055199895649405434183/69720375229712477164533808935312303556800\n# 0.3118278207", "safe": true }, { "filename": "100 prisoners_102.txt", "content": "ClearAll[PlayRandom, PlayOptimal]\nPlayRandom[n_] := \n Module[{pardoned = 0, sampler, indrawer, found, reveal},\n sampler = indrawer = Range[100];\n Do[\n indrawer //= RandomSample;\n found = 0;\n Do[\n reveal = RandomSample[sampler, 50];\n If[MemberQ[indrawer[[reveal]], p],\n found++;\n ]\n ,\n {p, 100}\n ];\n If[found == 100, pardoned++];\n ,\n {n}\n ];\n N[pardoned/n]\n ]\nPlayOptimal[n_] := \n Module[{pardoned = 0, indrawer, reveal, found, card},\n indrawer = Range[100];\n Do[\n indrawer //= RandomSample;\n Do[\n reveal = p;\n found = False;\n Do[\n card = indrawer[[reveal]];\n If[card == p,\n found = True;\n Break[];\n ];\n reveal = card;\n ,\n {g, 50}\n ];\n If[! found, Break[]];\n ,\n {p, 100}\n ];\n If[found, pardoned++];\n ,\n {n}\n ];\n N[pardoned/n]\n ];\nPlayRandom[1000]\nPlayOptimal[10000]\n", "safe": true }, { "filename": "100 prisoners_103.txt", "content": "0.\n0.3116", "safe": true }, { "filename": "100 prisoners_104.txt", "content": "function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)\n %numP is the number of prisoners\n %numG is the number of guesses\n %numT is the number of trials\n randSuccess=0;\n \n %Random\n for trial=1:numT\n drawers=randperm(numP);\n won=1;\n for i=1:numP\n correct=0;\n notopened=drawers;\n for j=1:numG\n ind=randi(numel(notopened));\n m=notopened(ind);\n if m==i\n correct=1;\n break;\n end\n notopened(ind)=[];\n end\n if correct==0\n won=0;\n break;\n end\n end\n randSuccess=randSuccess*(trial-1)/trial+won/trial;\n end\n \n\n %Ideal\n idealSuccess=0;\n\n for trial=1:numT\n drawers=randperm(numP);\n won=1;\n for i=1:numP\n correct=0;\n guess=i;\n for j=1:numG\n m=drawers(guess);\n if m==i\n correct=1;\n break;\n end\n guess=m;\n end\n if correct==0\n won=0;\n break;\n end\n end\n idealSuccess=idealSuccess*(trial-1)/trial+won/trial;\n end\n disp(['Probability of success with random strategy: ' num2str(randSuccess*100) '%']);\n disp(['Probability of success with ideal strategy: ' num2str(idealSuccess*100) '%']);\nend\n", "safe": true }, { "filename": "100 prisoners_105.txt", "content": ">> [randSuccess,idealSuccess]=prisoners(100,50,10000);\nProbability of success with random strategy: 0%\nProbability of success with ideal strategy: 31.93%", "safe": true }, { "filename": "100 prisoners_106.txt", "content": "playRandom = function(n)\n // using 0-99 instead of 1-100\n pardoned = 0\n numInDrawer = range(99)\n choiceOrder = range(99)\n for round in range(1, n)\n \tnumInDrawer.shuffle\n choiceOrder.shuffle\n for prisoner in range(99)\n found = false\n for card in choiceOrder[:50]\n if card == prisoner then\n found = true\n break\n end if\n end for\n if not found then break\n end for\n if found then pardoned = pardoned + 1\n end for\n return pardoned / n * 100\nend function\n\nplayOptimal = function(n)\n // using 0-99 instead of 1-100\n pardoned = 0\n numInDrawer = range(99)\n for round in range(1, n)\n \tnumInDrawer.shuffle\n for prisoner in range(99)\n found = false\n\t drawer = prisoner\n for i in range(1,50)\n card = numInDrawer[drawer]\n if card == prisoner then\n found = true\n break\n end if\n drawer = card\n end for\n if not found then break\n end for\n if found then pardoned = pardoned + 1\n end for\n return pardoned / n * 100\nend function\n\nprint \"Random: \" + playRandom(10000) + \"%\"\nprint \"Optimal: \" + playOptimal(10000) + \"%\"\n", "safe": true }, { "filename": "100 prisoners_107.txt", "content": "Random: 0%\nOptimal: 31.06%", "safe": true }, { "filename": "100 prisoners_108.txt", "content": "import random, sequtils, strutils\n\ntype\n Sample = tuple\n succ: int\n fail: int\n\nconst\n numPrisoners = 100\n numDrawsEachPrisoner = numPrisoners div 2\n numDrawings: Positive = 1_000_000 div 1\n\nproc `$`(s: Sample): string =\n \"Succs: $#\\tFails: $#\\tTotal: $#\\tSuccess Rate: $#%.\" % [$s.succ, $s.fail, $(s.succ + s.fail), $(s.succ.float / (s.succ + s.fail).float * 100.0)]\n\nproc prisonersWillBeReleasedSmart(): bool =\n result = true\n var drawers = toSeq(0..0)/LOOP\n R \u2190 R \u00f7 M\n\u2207\n\n\u2395TS\n'>>>>>'\n1000 timesSimPrisoners 100 50\n'>>>>>'\n\u2395TS\n", "safe": true }, { "filename": "100 prisoners_110.txt", "content": "program Prisoners100;\n\nconst\n rounds = 100000;\n\ntype\n tValue = Uint32;\n tPrisNum = array of tValue;\nvar\n drawers,\n PrisonersChoice : tPrisNum;\n\nprocedure shuffle(var N:tPrisNum);\nvar\n i,j,lmt : nativeInt;\n tmp: tValue;\nBegin\n lmt := High(N);\n For i := lmt downto 1 do\n begin\n //take on from index i..limit\n j := random(i+1);\n //exchange with i\n tmp := N[i];N[i]:= N[j];N[j]:= tmp;\n end;\nend;\n\nfunction PardonedRandom(maxTestNum: NativeInt):boolean;\nvar\n PrisNum,TestNum,Lmt : NativeUint;\n Pardoned : boolean;\nBegin\n IF maxTestNum <=0 then\n Begin\n PardonedRandom := false;\n EXIT;\n end;\n Lmt := High(drawers);\n IF (maxTestNum >= Lmt) then\n Begin\n PardonedRandom := true;\n EXIT;\n end;\n\n shuffle(drawers);\n PrisNum := 0;\n repeat\n //every prisoner uses his own list of drawers\n shuffle(PrisonersChoice);\n TestNum := 0;\n repeat\n Pardoned := drawers[PrisonersChoice[TestNum]] = PrisNum;\n inc(TestNum);\n until Pardoned OR (TestNum>=maxTestNum);\n IF Not(Pardoned) then\n BREAK;\n inc(PrisNum);\n until PrisNum>=Lmt;\n PardonedRandom:= Pardoned;\nend;\n\nfunction PardonedOptimized(maxTestNum: NativeUint):boolean;\nvar\n PrisNum,TestNum,NextNum,Cnt,Lmt : NativeUint;\n Pardoned : boolean;\nBegin\n IF maxTestNum <=0 then\n Begin\n PardonedOptimized := false;\n EXIT;\n end;\n Lmt := High(drawers);\n IF (maxTestNum >= Lmt) then\n Begin\n PardonedOptimized := true;\n EXIT;\n end;\n\n shuffle(drawers);\n Lmt := High(drawers);\n IF maxTestNum >= Lmt then\n Begin\n PardonedOptimized := true;\n EXIT;\n end;\n PrisNum := 0;\n repeat\n Cnt := 0;\n NextNum := PrisNum;\n repeat\n TestNum := NextNum;\n NextNum := drawers[TestNum];\n inc(cnt);\n Pardoned := NextNum = PrisNum;\n until Pardoned OR (cnt >=maxTestNum);\n\n IF Not(Pardoned) then\n BREAK;\n inc(PrisNum);\n until PrisNum>Lmt;\n PardonedOptimized := Pardoned;\nend;\n\nprocedure CheckRandom(testCount : NativeUint);\nvar\n i,cnt : NativeInt;\nBegin\n cnt := 0;\n For i := 1 to rounds do\n IF PardonedRandom(TestCount) then\n inc(cnt);\n writeln('Randomly ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);\nend;\n\nprocedure CheckOptimized(testCount : NativeUint);\nvar\n i,cnt : NativeInt;\nBegin\n cnt := 0;\n For i := 1 to rounds do\n IF PardonedOptimized(TestCount) then\n inc(cnt);\n writeln('Optimized ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);\nend;\n\nprocedure OneCompareRun(PrisCnt:NativeInt);\nvar\n i,lmt :nativeInt;\nbegin\n setlength(drawers,PrisCnt);\n For i := 0 to PrisCnt-1 do\n drawers[i] := i;\n PrisonersChoice := copy(drawers);\n\n //test\n writeln('Checking ',PrisCnt,' prisoners');\n\n lmt := PrisCnt;\n repeat\n CheckOptimized(lmt);\n dec(lmt,PrisCnt DIV 10);\n until lmt < 0;\n writeln;\n\n lmt := PrisCnt;\n repeat\n CheckRandom(lmt);\n dec(lmt,PrisCnt DIV 10);\n until lmt < 0;\n writeln;\n writeln;\nend;\n\nBegin\n //init\n randomize;\n OneCompareRun(20);\n OneCompareRun(100);\nend.\n", "safe": true }, { "filename": "100 prisoners_111.txt", "content": "Checking 20 prisoners\nOptimized 100.00% get pardoned out of 100000 checking max 20\nOptimized 89.82% get pardoned out of 100000 checking max 18\nOptimized 78.25% get pardoned out of 100000 checking max 16\nOptimized 65.31% get pardoned out of 100000 checking max 14\nOptimized 50.59% get pardoned out of 100000 checking max 12\nOptimized 33.20% get pardoned out of 100000 checking max 10\nOptimized 15.28% get pardoned out of 100000 checking max 8\nOptimized 3.53% get pardoned out of 100000 checking max 6\nOptimized 0.10% get pardoned out of 100000 checking max 4\nOptimized 0.00% get pardoned out of 100000 checking max 2\nOptimized 0.00% get pardoned out of 100000 checking max 0\n\nRandomly 100.00% get pardoned out of 100000 checking max 20\nRandomly 13.55% get pardoned out of 100000 checking max 18\nRandomly 1.38% get pardoned out of 100000 checking max 16\nRandomly 0.12% get pardoned out of 100000 checking max 14\nRandomly 0.00% get pardoned out of 100000 checking max 12\nRandomly 0.00% get pardoned out of 100000 checking max 10\nRandomly 0.00% get pardoned out of 100000 checking max 8\nRandomly 0.00% get pardoned out of 100000 checking max 6\nRandomly 0.00% get pardoned out of 100000 checking max 4\nRandomly 0.00% get pardoned out of 100000 checking max 2\nRandomly 0.00% get pardoned out of 100000 checking max 0\n\n\nChecking 100 prisoners\nOptimized 100.00% get pardoned out of 100000 checking max 100\nOptimized 89.48% get pardoned out of 100000 checking max 90\nOptimized 77.94% get pardoned out of 100000 checking max 80\nOptimized 64.48% get pardoned out of 100000 checking max 70\nOptimized 49.35% get pardoned out of 100000 checking max 60\nOptimized 31.10% get pardoned out of 100000 checking max 50\nOptimized 13.38% get pardoned out of 100000 checking max 40\nOptimized 2.50% get pardoned out of 100000 checking max 30\nOptimized 0.05% get pardoned out of 100000 checking max 20\nOptimized 0.00% get pardoned out of 100000 checking max 10\nOptimized 0.00% get pardoned out of 100000 checking max 0\n\nRandomly 100.00% get pardoned out of 100000 checking max 100\nRandomly 0.01% get pardoned out of 100000 checking max 90\nRandomly 0.00% get pardoned out of 100000 checking max 80\nRandomly 0.00% get pardoned out of 100000 checking max 70\nRandomly 0.00% get pardoned out of 100000 checking max 60\nRandomly 0.00% get pardoned out of 100000 checking max 50\nRandomly 0.00% get pardoned out of 100000 checking max 40\nRandomly 0.00% get pardoned out of 100000 checking max 30\nRandomly 0.00% get pardoned out of 100000 checking max 20\nRandomly 0.00% get pardoned out of 100000 checking max 10\nRandomly 0.00% get pardoned out of 100000 checking max 0", "safe": true }, { "filename": "100 prisoners_112.txt", "content": "program Prisoners100;\n{$IFDEF FPC}\n {$MODE DELPHI}{$OPTIMIZATION ON,ALL}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\ntype\n tValue = NativeUint;\n tpValue = pNativeUint;\n tPrisNum = array of tValue;\n\nconst\n rounds = 1000000;\n cAlreadySeen = High(tValue);\nvar\n drawers,\n Visited,\n CntToPardoned : tPrisNum;\n PrisCount : NativeInt;\n\nprocedure shuffle(var N:tPrisNum;lmt : nativeInt = 0);\nvar\n pN : tpValue;\n i,j : nativeInt;\n tmp: tValue;\nBegin\n pN := @N[0];\n if lmt = 0 then\n lmt := High(N);\n For i := lmt downto 1 do\n begin\n //take one from index [0..i]\n j := random(i+1);\n //exchange with i\n tmp := pN[i];pN[i]:= pN[j];pN[j]:= tmp;\n end;\nend;\n\nprocedure CopyDrawers2Visited;\n//drawers and Visited are of same size, so only moving values\nBegin\n Move(drawers[0],Visited[0],SizeOf(tValue)*PrisCount);\nend;\n\nfunction GetMaxCycleLen:NativeUint;\nvar\n pVisited : tpValue;\n cycleLen,MaxCycLen,Num,NumBefore : NativeUInt;\nBegin\n CopyDrawers2Visited;\n pVisited := @Visited[0];\n MaxCycLen := 0;\n cycleLen := MaxCycLen;\n Num := MaxCycLen;\n repeat\n NumBefore := Num;\n Num := pVisited[Num];\n pVisited[NumBefore] := cAlreadySeen;\n inc(cycleLen);\n IF (Num= NumBefore) or (Num = cAlreadySeen) then\n begin\n IF Num = cAlreadySeen then\n dec(CycleLen);\n IF MaxCycLen < cycleLen then\n MaxCycLen := cycleLen;\n Num := 0;\n while (Num< PrisCount) AND (pVisited[Num] = cAlreadySeen) do\n inc(Num);\n //all cycles found\n IF Num >= PrisCount then\n BREAK;\n cycleLen :=0;\n end;\n until false;\n GetMaxCycleLen := MaxCycLen-1;\nend;\n\nprocedure CheckOptimized(testCount : NativeUint);\nvar\n factor: extended;\n i,sum,digit,delta : NativeInt;\nBegin\n For i := 1 to rounds do\n begin\n shuffle(drawers);\n inc(CntToPardoned[GetMaxCycleLen]);\n end;\n\n digit := 0;\n sum := rounds;\n while sum > 100 do\n Begin\n inc(digit);\n sum := sum DIV 10;\n end;\n factor := 100.0/rounds;\n\n delta :=0;\n sum := 0;\n For i := 0 to High(drawers) do\n Begin\n inc(sum,CntToPardoned[i]);\n dec(delta);\n IF delta <= 0 then\n Begin\n writeln(sum*factor:Digit+5:Digit,'% get pardoned checking max ',i+1);\n delta := delta+Length(drawers) DIV 10;\n end;\n end;\nend;\n\nprocedure OneCompareRun(PrisCnt:NativeInt);\nvar\n i,lmt :nativeInt;\nbegin\n PrisCount := PrisCnt;\n setlength(drawers,PrisCnt);\n For i := 0 to PrisCnt-1 do\n drawers[i] := i;\n setlength(Visited,PrisCnt);\n setlength(CntToPardoned,PrisCnt);\n //test\n writeln('Checking ',PrisCnt,' prisoners for ',rounds,' rounds');\n lmt := PrisCnt;\n CheckOptimized(lmt);\n writeln;\n\n setlength(CntToPardoned,0);\n setlength(Visited,0);\n setlength(drawers,0);\nend;\n\nBegin\n randomize;\n OneCompareRun(10);\n OneCompareRun(100);\n OneCompareRun(1000);\nend.\n", "safe": true }, { "filename": "100 prisoners_113.txt", "content": "Checking 10 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.2584% get pardoned checking max 2\n 4.7431% get pardoned checking max 3\n 17.4409% get pardoned checking max 4\n 35.4983% get pardoned checking max 5\n 52.1617% get pardoned checking max 6\n 66.4807% get pardoned checking max 7\n 78.9761% get pardoned checking max 8\n 90.0488% get pardoned checking max 9\n 100.0000% get pardoned checking max 10\n\nChecking 100 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.0000% get pardoned checking max 10\n 0.0459% get pardoned checking max 20\n 2.5996% get pardoned checking max 30\n 13.5071% get pardoned checking max 40\n 31.2258% get pardoned checking max 50\n 49.3071% get pardoned checking max 60\n 64.6128% get pardoned checking max 70\n 77.8715% get pardoned checking max 80\n 89.5385% get pardoned checking max 90\n 100.0000% get pardoned checking max 100\n\nChecking 1000 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.0000% get pardoned checking max 100\n 0.0374% get pardoned checking max 200\n 2.3842% get pardoned checking max 300\n 13.1310% get pardoned checking max 400\n 30.7952% get pardoned checking max 500\n 48.9710% get pardoned checking max 600\n 64.3555% get pardoned checking max 700\n 77.6950% get pardoned checking max 800\n 89.4515% get pardoned checking max 900\n 100.0000% get pardoned checking max 1000\n\nreal 0m9,975s", "safe": true }, { "filename": "100 prisoners_114.txt", "content": "use strict;\nuse warnings;\nuse feature 'say';\nuse List::Util 'shuffle';\n\nsub simulation {\n my($population,$trials,$strategy) = @_;\n my $optimal = $strategy =~ /^o/i ? 1 : 0;\n my @prisoners = 0..$population-1;\n my $half = int $population / 2;\n my $pardoned = 0;\n\n for (1..$trials) {\n my @drawers = shuffle @prisoners;\n my $total = 0;\n for my $prisoner (@prisoners) {\n my $found = 0;\n if ($optimal) {\n my $card = $drawers[$prisoner];\n if ($card == $prisoner) {\n $found = 1;\n } else {\n for (1..$half-1) {\n $card = $drawers[$card];\n ($found = 1, last) if $card == $prisoner\n }\n }\n } else {\n for my $card ( (shuffle @drawers)[0..$half]) {\n ($found = 1, last) if $card == $prisoner\n }\n }\n last unless $found;\n $total++;\n }\n $pardoned++ if $total == $population;\n }\n $pardoned / $trials * 100\n}\n\nmy $population = 100;\nmy $trials = 10000;\nsay \" Simulation count: $trials\\n\" .\n(sprintf \" Random strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'random' ) .\n(sprintf \"Optimal strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'optimal');\n\n$population = 10;\n$trials = 100000;\nsay \" Simulation count: $trials\\n\" .\n(sprintf \" Random strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'random' ) .\n(sprintf \"Optimal strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'optimal');\n", "safe": true }, { "filename": "100 prisoners_115.txt", "content": " Simulation count: 10000\n Random strategy pardons: 0.000% of simulations\nOptimal strategy pardons: 31.510% of simulations\n\n Simulation count: 1000000\n Random strategy pardons: 0.099% of simulations\nOptimal strategy pardons: 35.420% of simulations", "safe": true }, { "filename": "100 prisoners_116.txt", "content": "(de shuffle (Lst)\n (by '(NIL (rand)) sort Lst) )\n\n# Extend this class with a `next-guess>` method and a `str>` method.\n(class +Strategy +Entity)\n(dm prev-drawer> (Num)\n (=: prev Num) )\n\n(class +Random +Strategy)\n(dm T (Prisoner)\n (=: guesses (nth (shuffle (range 1 100)) 51)) )\n(dm next-guess> ()\n (pop (:: guesses)) )\n(dm str> ()\n \"Random\" )\n\n(class +Optimal +Strategy)\n(dm T (Prisoner)\n (=: prisoner-id Prisoner) )\n(dm next-guess> ()\n (or (: prev) (: prisoner-id)) )\n(dm str> ()\n \"Optimal/Wikipedia\" )\n\n\n(de test-strategy (Strategy)\n \"Simulate one round of 100 prisoners who use `Strategy`\"\n (let Drawers (shuffle (range 1 100))\n (for Prisoner (range 1 100)\n (NIL # Break and return NIL if any prisoner fails their test.\n (let Strat (new (list Strategy) Prisoner)\n (do 50 # Try 50 iterations of `Strat`. Break and return T iff success.\n (T (= Prisoner (prev-drawer> Strat (get Drawers (next-guess> Strat))))\n T ) ) ) )\n T ) ) )\n\n(de test-strategy-n-times (Strategy N)\n \"Simulate `N` rounds of 100 prisoners who use `Strategy`\"\n (let Successes 0\n (do N\n (when (test-strategy Strategy)\n (inc 'Successes) ) )\n (prinl \"We have a \" (/ (* 100 Successes) N) \"% success rate with \" N \" trials.\")\n (prinl \"This is using the \" (str> Strategy) \" strategy.\") ) )", "safe": true }, { "filename": "100 prisoners_117.txt", "content": "(test-strategy-n-times '+Random 10000)\n(test-strategy-n-times '+Optimal 10000)", "safe": true }, { "filename": "100 prisoners_118.txt", "content": "We have a 0% success rate with 10000 trials.\nThis is using the Random strategy.\nWe have a 31% success rate with 10000 trials.\nThis is using the Optimal/Wikipedia strategy.", "safe": true }, { "filename": "100 prisoners_119.txt", "content": "function play(integer prisoners, iterations, bool optimal)\n sequence drawers = shuffle(tagset(prisoners))\n integer pardoned = 0\n bool found = false\n for i=1 to iterations do\n drawers = shuffle(drawers)\n for prisoner=1 to prisoners do\n found = false\n integer drawer = iff(optimal?prisoner:rand(prisoners))\n for j=1 to prisoners/2 do\n drawer = drawers[drawer]\n if drawer==prisoner then found = true exit end if\n if not optimal then drawer = rand(prisoners) end if\n end for\n if not found then exit end if\n end for\n pardoned += found\n end for\n return 100*pardoned/iterations\nend function\n \nconstant iterations = 100_000\nprintf(1,\"Simulation count: %d\\n\",iterations)\nfor prisoners in {10,100} do\n atom random = play(prisoners,iterations,false),\n optimal = play(prisoners,iterations,true)\n printf(1,\"Prisoners:%d, random:%g, optimal:%g\\n\",{prisoners,random,optimal})\nend for\n", "safe": true }, { "filename": "100 prisoners_12.txt", "content": "2023 3 26 17 43 32 983\n>>>>>\n0 0.307\n>>>>>\n2023 3 26 17 53 48 531\n", "safe": true }, { "filename": "100 prisoners_120.txt", "content": "Simulation count: 100000\nPrisoners:10, random:0.006, optimal:35.168\nPrisoners:100, random:0, optimal:31.098\n", "safe": true }, { "filename": "100 prisoners_121.txt", "content": "/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners\nby Galileo, 05/2022 #/\n\ninclude ..\\Utilitys.pmt\n\ndef random rand * 1 + int enddef\n\ndef shuffle\n len var l\n l for var a\n l random var b\n b get var p\n a get b set\n p a set\n endfor\nenddef\n\ndef play var optimal var iterations var prisoners\n 0 var pardoned\n\n ( prisoners for endfor )\n \n iterations for drop\n shuffle\n prisoners for var prisoner\n false var found\n optimal if prisoner else prisoners random endif\n prisoners 2 / int for drop\n get dup prisoner == if true var found exitfor\n else\n optimal not if drop prisoners random endif\n endif\n endfor\n found not if exitfor endif\n drop\n endfor\n pardoned found + var pardoned\n endfor\n drop\n pardoned 100 * iterations /\nenddef\n\n\"Please, be patient ...\"\u00a0?\n\n( \"Optimal: \" 100 10000 true play\n \" Random: \" 100 10000 false play\n \" Prisoners: \" prisoners ) lprint", "safe": true }, { "filename": "100 prisoners_122.txt", "content": "Please, be patient ...\nOptimal: 31.65 Random: 0 Prisoners: 100\n=== Press any key to exit ===", "safe": true }, { "filename": "100 prisoners_123.txt", "content": "100H:\n/* PARAMETERS */\nDECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */\nDECLARE N$ATTEMPTS LITERALLY '50'; /* ATTEMPTS PER PRISONER */\nDECLARE N$SIMS LITERALLY '2000'; /* N. OF SIMULATIONS TO RUN */ \nDECLARE RAND$SEED LITERALLY '193'; /* RANDOM SEED */\n\n/* CP/M CALLS */\nBDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;\nEXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;\nPRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;\n\n/* PRINT NUMBER */\nPRINT$NUMBER: PROCEDURE (N);\n DECLARE S (6) BYTE INITIAL ('.....$');\n DECLARE (P, N) ADDRESS, C BASED P BYTE;\n P = .S(5);\nDIGIT:\n P = P - 1;\n C = N MOD 10 + '0';\n N = N / 10;\n IF N > 0 THEN GO TO DIGIT;\n CALL PRINT(P);\nEND PRINT$NUMBER;\n\n/* RANDOM NUMBER GENERATOR */\nRAND$BYTE: PROCEDURE BYTE;\n DECLARE (X, A, B, C) BYTE \n INITIAL (RAND$SEED, RAND$SEED, RAND$SEED, RAND$SEED);\n X = X+1;\n A = A XOR C XOR X;\n B = B+A;\n C = C+SHR(B,1)+A;\n RETURN C;\nEND RAND$BYTE;\n\n/* GENERATE RANDOM NUMBER FROM 0 TO MAX */\nRAND$MAX: PROCEDURE (MAX) BYTE;\n DECLARE (X, R, MAX) BYTE;\n X = 1;\n DO WHILE X < MAX;\n X = SHL(X,1);\n END;\n X = X-1;\n DO WHILE 1;\n R = RAND$BYTE AND X;\n IF R < MAX THEN RETURN R;\n END;\nEND RAND$MAX;\n\n/* PLACE CARDS RANDOMLY IN DRAWERS */\nINIT$DRAWERS: PROCEDURE (DRAWERS);\n DECLARE DRAWERS ADDRESS, (D BASED DRAWERS, I, J, K) BYTE;\n DO I=0 TO N$DRAWERS-1;\n D(I) = I;\n END;\n DO I=0 TO N$DRAWERS-1;\n J = I + RAND$MAX(N$DRAWERS-I);\n K = D(I);\n D(I) = D(J);\n D(J) = K;\n END;\nEND INIT$DRAWERS;\n\n/* PRISONER OPENS RANDOM DRAWERS */\nRANDOM$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;\n DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;\n DECLARE (P, I, TRIES) BYTE;\n \n /* KEEP TRACK OF WHICH DRAWERS HAVE BEEN OPENED */\n DECLARE OPEN (N$DRAWERS) BYTE;\n DO I=0 TO N$DRAWERS-1;\n OPEN(I) = 0;\n END;\n \n /* OPEN RANDOM DRAWERS */\n TRIES = N$ATTEMPTS;\n DO WHILE TRIES > 0;\n IF NOT OPEN(I\u00a0:= RAND$MAX(N$DRAWERS)) THEN DO;\n /* IF WE FIND OUR NUMBER, SUCCESS */\n IF D(I) = P THEN RETURN 1;\n OPEN(I) = 1; \n TRIES = TRIES - 1;\n END;\n END;\n \n RETURN 0; /* WE DID NOT FIND OUR NUMBER */\nEND RANDOM$STRATEGY;\n\n/* PRISONER USES OPTIMAL STRATEGY */\nOPTIMAL$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;\n DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;\n DECLARE (P, I, TRIES) BYTE;\n TRIES = N$ATTEMPTS;\n I = P;\n DO WHILE TRIES > 0;\n I = D(I); /* OPEN DRAWER W/ CURRENT NUMBER */\n IF I = P THEN RETURN 1; /* DID WE FIND IT? */\n TRIES = TRIES - 1;\n END;\n RETURN 0;\nEND OPTIMAL$STRATEGY;\n\n/* RUN A SIMULATION */\nDECLARE RANDOM LITERALLY '0';\nDECLARE OPTIMAL LITERALLY '1';\nSIMULATE: PROCEDURE (STRAT) BYTE;\n DECLARE (STRAT, P, R) BYTE;\n \n /* PLACE CARDS IN DRAWERS */\n DECLARE DRAWERS (N$DRAWERS) BYTE;\n CALL INIT$DRAWERS(.DRAWERS);\n \n /* TRY EACH PRISONER */\n DO P=0 TO N$DRAWERS-1;\n DO CASE STRAT;\n R = RANDOM$STRATEGY(.DRAWERS, P);\n R = OPTIMAL$STRATEGY(.DRAWERS, P);\n END;\n \n /* IF ONE PRISONER FAILS THEY ALL HANG */\n IF NOT R THEN RETURN 0;\n END;\n \n RETURN 1; /* IF THEY ALL SUCCEED NONE HANG */\nEND SIMULATE;\n\n/* RUN MANY SIMULATIONS AND COUNT THE SUCCESSES */\nRUN$SIMULATIONS: PROCEDURE (N, STRAT) ADDRESS;\n DECLARE STRAT BYTE, (I, N, SUCC) ADDRESS;\n SUCC = 0;\n DO I=1 TO N;\n SUCC = SUCC + SIMULATE(STRAT);\n END;\n RETURN SUCC;\nEND RUN$SIMULATIONS;\n\n/* RUN AND PRINT SIMULATIONS */\nRUN$AND$PRINT: PROCEDURE (NAME, STRAT, N);\n DECLARE (NAME, N, S) ADDRESS, STRAT BYTE;\n CALL PRINT(NAME);\n CALL PRINT(.' STRATEGY: $');\n S = RUN$SIMULATIONS(N, STRAT);\n CALL PRINT$NUMBER(S);\n CALL PRINT(.' OUT OF $');\n CALL PRINT$NUMBER(N);\n CALL PRINT(.' - $');\n CALL PRINT$NUMBER( S*10 / (N/10) );\n CALL PRINT(.(37,13,10,'$'));\nEND RUN$AND$PRINT;\n\nCALL RUN$AND$PRINT(.'RANDOM$', RANDOM, N$SIMS);\nCALL RUN$AND$PRINT(.'OPTIMAL$', OPTIMAL, N$SIMS);\nCALL EXIT;\nEOF", "safe": true }, { "filename": "100 prisoners_124.txt", "content": "RANDOM STRATEGY: 0 OUT OF 2000 - 0%\nOPTIMAL STRATEGY: 653 OUT OF 2000 - 32%", "safe": true }, { "filename": "100 prisoners_125.txt", "content": "optimalSeq(drawers, n) =\n iterate(ind => drawers[ind - 1], n)\n |> takeUntil(ind => drawers[ind - 1] == n)\n\noptimalTrial(drawers) =\n range(1, 100)\n |> map(optimalSeq(drawers))\n\nrandomSeq(drawers, n) =\n iterate(ind => randRange(1, 100), randRange(1, 100))\n |> takeUntil(ind => drawers[ind - 1] == n)\n\nrandomTrial(drawers) =\n range(1, 100)\n |> map(randomSeq(drawers))\n\ncheckLength(seq) =\n length(take(51, seq)) <= 50\n\nnumTrials = 3000\n\nrunTrials(trialFunc) =\n for t in range(1, numTrials)\n yield\n range(1, 100)\n |> shuffle\n |> toArray\n |> trialFunc\n |> map(checkLength)\n |> all\n\ncountSuccess(trialFunc) =\n runTrials(trialFunc)\n |> filter(id)\n |> length\n\noptimalCount = countSuccess(optimalTrial)\nrandomCount = countSuccess(randomTrial)\n\noutput =\n format(\"optimal: {} / {} = {} prob\\nrandom: {} / {} = {} prob\", [\n optimalCount, numTrials, optimalCount / numTrials,\n randomCount, numTrials, randomCount / numTrials,\n ])\n |> println\n", "safe": true }, { "filename": "100 prisoners_126.txt", "content": "optimal: 923 / 3000 = 0.30766666666666664 prob\nrandom: 0 / 3000 = 0.0 prob", "safe": true }, { "filename": "100 prisoners_127.txt", "content": "### Clear Screen from old Output\nClear-Host\n\nFunction RandomOpening () \n {\n $Prisoners = 1..100 | Sort-Object {Get-Random}\n $Cupboard = 1..100 | Sort-Object {Get-Random}\n ## Loop for the Prisoners\n $Survived = $true\n for ($I=1;$I -le 100;$i++)\n {\n $OpeningListe = 1..100 | Sort-Object {Get-Random}\n $Gefunden = $false\n ## Loop for the trys of every prisoner\n for ($X=1;$X -le 50;$X++)\n {\n $OpenNumber = $OpeningListe[$X]\n IF ($Cupboard[$OpenNumber] -eq $Prisoners[$I])\n {\n $Gefunden = $true\n }\n ## Cancel loop if prisoner found his number (yeah i know, dirty way ^^ ) \n IF ($Gefunden)\n {\n $X = 55\n }\n }\n IF ($Gefunden -eq $false)\n {\n $I = 120\n $Survived = $false\n } \n }\n Return $Survived\n }\n\n Function StrategyOpening () \n {\n $Prisoners = 1..100 | Sort-Object {Get-Random}\n $Cupboard = 1..100 | Sort-Object {Get-Random}\n $Survived = $true\n for ($I=1;$I -le 100;$i++)\n {\n $Gefunden = $false\n $OpeningNumber = $Prisoners[$I-1]\n for ($X=1;$X -le 50;$X++)\n {\n IF ($Cupboard[$OpeningNumber-1] -eq $Prisoners[$I-1])\n {\n $Gefunden = $true\n }\n else \n {\n $OpeningNumber = $Cupboard[$OpeningNumber-1] \n } \n IF ($Gefunden)\n {\n $X = 55\n }\n }\n IF ($Gefunden -eq $false)\n {\n $I = 120\n $Survived = $false\n } \n }\n Return $Survived\n }\n\n$MaxRounds = 10000\n\nFunction TestRandom\n {\n $WinnerRandom = 0\n for ($Round = 1; $Round -le $MaxRounds;$Round++)\n {\n IF (($Round%1000) -eq 0)\n {\n $Time = Get-Date\n Write-Host \"Currently we are at rount $Round at $Time\"\n }\n $Rueckgabewert = RandomOpening\n IF ($Rueckgabewert)\n {\n $WinnerRandom++\n }\n }\n \n $Prozent = (100/$MaxRounds)*$WinnerRandom\n Write-Host \"There are $WinnerRandom survivors whit random opening. This is $Prozent percent\"\n }\n\nFunction TestStrategy\n {\n $WinnersStrategy = 0 \n for ($Round = 1; $Round -le $MaxRounds;$Round++)\n {\n IF (($Round%1000) -eq 0)\n {\n $Time = Get-Date\n Write-Host \"Currently we are at $Round at $Time\"\n }\n $Rueckgabewert = StrategyOpening\n IF ($Rueckgabewert)\n {\n $WinnersStrategy++\n }\n }\n \n $Prozent = (100/$MaxRounds)*$WinnersStrategy\n Write-Host \"There are $WinnersStrategy survivors whit strategic opening. This is $Prozent percent\"\n }\n\nFunction Main () \n {\n Clear-Host\n TestRandom\n TestStrategy\n }\n\nMain\n", "safe": true }, { "filename": "100 prisoners_128.txt", "content": "# of executions: 10000\nThere are 0 survivors whit random opening. This is 0 percent\nThere are 3104 survivors whit strategic opening. This is 31,04 percent\"\n", "safe": true }, { "filename": "100 prisoners_129.txt", "content": "IntList drawers = new IntList();\nint trials = 100000;\nint succes_count;\n\nvoid setup() {\n for (int i = 0; i < 100; i++) {\n drawers.append(i);\n }\n println(trials + \" trials\\n\");\n\n //Random strategy\n println(\"Random strategy\");\n succes_count = trials;\n for (int i = 0; i < trials; i++) {\n drawers.shuffle();\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n boolean found = false;\n for (int attempt = 0; attempt < 50; attempt++) {\n if (drawers.get(int(random(drawers.size()))) == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n succes_count--;\n break;\n }\n }\n }\n println(\" Succeses: \" + succes_count);\n println(\" Succes rate: \" + 100.0 * succes_count / trials + \"%\\n\");\n\n //Optimal strategy\n println(\"Optimal strategy\");\n succes_count = trials;\n for (int i = 0; i < trials; i++) {\n drawers.shuffle();\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n boolean found = false;\n int next = prisoner;\n for (int attempt = 0; attempt < 50; attempt++) {\n next = drawers.get(next);\n if (next == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n succes_count--;\n break;\n }\n }\n }\n println(\" Succeses: \" + succes_count);\n print(\" Succes rate: \" + 100.0 * succes_count / trials + \"%\");\n}", "safe": true }, { "filename": "100 prisoners_13.txt", "content": "0 GOTO 9\n\n1 FOR X = 0 TO N:J(X) = X: NEXT: FOR I = 0 TO N:FOR X = 0 TO N:T = J(X):NP = INT ( RND (1) * H):J(X) = J(NP):J(NP) = T: NEXT :FOR G = 1 TO W:IF D(J(G)) = I THEN IP = IP + 1: NEXT I: RETURN \n2 NEXT G:RETURN \n\n3 FOR I = 0 TO N:NG = I: FOR G = 0 TO W:CD = D(NG):IF CD = I THEN IP = IP + 1: NEXT I: RETURN \n4 NG = CD:IF CD = I THEN STOP\n5 NEXT G: RETURN \n\n9 H=100:N=H-1:DIM D(99),J(99):FOR I = 0 TO N:D(I) = I: NEXT:W=INT(H/2)-1:M$=CHR$(13):M$(1)=\"RANDOM GUESSING\":M$(2)=\"CHAINED NUMBER PICKING\"\n\n1000 FOR Q = 0 TO 1 STEP 0 : HOME : PRINT \"100 PRISONERS\"M$: INPUT \"HOW MANY TRIALS FOR EACH METHOD? \"; TT\n1010 VTAB 2:CALL-958:PRINT M$\"RESULTS:\"M$\n1020 FOR M = 1 TO 2: SU(M) = 0:FA(M) = 0\n1030 FOR TN = 1 TO TT\n1040 VTAB 4:PRINT M$ \" OUT OF \" TT \" TRIALS, THE RESULTS ARE\"M$\" AS FOLLOWS...\";\n1050 IP = 0: X = RND ( - TI): FOR I = 0 TO N:R = INT ( RND (1) * N):T = D(I):D(I) = D(R):D(R) = T: NEXT\n1060 ON M GOSUB 1,3 : SU(M) = SU(M) + (IP = H):FA(M) = FA(M) + (IP < H)\n1070 FOR Z = 1 TO 2\n1071 PRINT M$M$Z\". \"M$(Z)\":\"M$\n1073 PRINT \" \"SU(Z)\" SUCCESSES\"TAB(21)\n1074 PRINT \" \"FA(Z)\" FAILURES\"M$\n1075 PRINT \" \"(SU(Z) / TT) * 100\"% SUCCESS RATE.\";:CALL-868\n1090 NEXT Z,TN,M\n\n1100 PRINT M$M$\"AGAIN?\"\n1110 GET K$\n1120 Q = K$ <> \"Y\" AND K$ <> CHR$(ASC(\"Y\") + 32) : NEXT Q\n", "safe": true }, { "filename": "100 prisoners_130.txt", "content": "100000 trials\n\nRandom strategy\n Succeses: 0\n Succes rate: 0.0%\n\nOptimal strategy\n Succeses: 31134\n Succes rate: 31.134%", "safe": true }, { "filename": "100 prisoners_131.txt", "content": "#PRISONERS=100\n#DRAWERS =100\n#LOOPS = 50\n#MAXPROBE = 10000\nOpenConsole()\n\nDim p1(#PRISONERS,#DRAWERS)\nDim p2(#PRISONERS,#DRAWERS)\nDim d(#DRAWERS)\n\nFor i=1 To #DRAWERS : d(i)=i : Next\nStart:\nFor probe=1 To #MAXPROBE\n RandomizeArray(d(),1,100)\n c1=0 : c2=0 \n For m=1 To #PRISONERS\n p2(m,1)=d(m) : If d(m)=m : p2(m,0)=1 : EndIf\n For n=1 To #LOOPS\n p1(m,n)=d(Random(100,1))\n If p1(m,n)=m : p1(m,0)=1 : EndIf\n If n>1 : p2(m,n)=d(p2(m,n-1)) : If p2(m,n)=m : p2(m,0)=1 : EndIf : EndIf\n Next n\n Next m\n \n For m=1 To #PRISONERS\n If p1(m,0) : c1+1 : p1(m,0)=0 : EndIf \n If p2(m,0) : c2+1 : p2(m,0)=0 : EndIf\n Next m\n \n If c1=#PRISONERS : w1+1 : EndIf\n If c2=#PRISONERS : w2+1 : EndIf\nNext probe\nPrint(\"TRIALS: \"+Str(#MAXPROBE))\nPrint(\" RANDOM= \"+StrF(100*w1/#MAXPROBE,2)+\"% STATEGY= \"+StrF(100*w2/#MAXPROBE,2)+\"%\")\nPrintN(~\"\\tFIN =q.\") : inp$=Input()\nw1=0 : w2=0\nIf inp$<>\"q\" : Goto Start : EndIf\n", "safe": true }, { "filename": "100 prisoners_132.txt", "content": "TRIALS: 10000 RANDOM= 0.00% STATEGY= 30.83%\tFIN =q.\n\nTRIALS: 10000 RANDOM= 0.00% STATEGY= 31.60%\tFIN =q.\n\nTRIALS: 10000 RANDOM= 0.00% STATEGY= 31.20%\tFIN =q.", "safe": true }, { "filename": "100 prisoners_133.txt", "content": "import random\n\ndef play_random(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n sampler = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n found = False\n for prisoner in range(100):\n found = False\n for reveal in random.sample(sampler, 50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 #\u00a0%\n\ndef play_optimal(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n for prisoner in range(100):\n reveal = prisoner\n found = False\n for go in range(50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n reveal = card\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 #\u00a0%\n\nif __name__ == '__main__':\n n = 100_000\n print(\" Simulation count:\", n)\n print(f\" Random play wins: {play_random(n):4.1f}% of simulations\")\n print(f\"Optimal play wins: {play_optimal(n):4.1f}% of simulations\")\n", "safe": true }, { "filename": "100 prisoners_134.txt", "content": " Simulation count: 100000\n Random play wins: 0.0% of simulations\nOptimal play wins: 31.1% of simulations", "safe": true }, { "filename": "100 prisoners_135.txt", "content": "# http://rosettacode.org/wiki/100_prisoners\n\nimport random\n\n\ndef main():\n NUM_DRAWERS = 10\n NUM_REPETITIONS = int(1E5)\n\n print('{:15}: {:5} ({})'.format('approach', 'wins', 'ratio'))\n for approach in PrisionersGame.approaches:\n num_victories = 0\n for _ in range(NUM_REPETITIONS):\n game = PrisionersGame(NUM_DRAWERS)\n num_victories += PrisionersGame.victory(game.play(approach))\n\n print('{:15}: {:5} ({:.2%})'.format(\n approach.__name__, num_victories, num_victories / NUM_REPETITIONS))\n\n\nclass PrisionersGame:\n \"\"\"docstring for PrisionersGame\"\"\"\n def __init__(self, num_drawers):\n assert num_drawers % 2 == 0\n self.num_drawers = num_drawers\n self.max_attempts = int(self.num_drawers / 2)\n self.drawer_ids = list(range(1, num_drawers + 1))\n shuffled = self.drawer_ids[:]\n random.shuffle(shuffled)\n self.drawers = dict(zip(self.drawer_ids, shuffled))\n\n def play_naive(self, player_number):\n \"\"\" Randomly open drawers \"\"\"\n for attempt in range(self.max_attempts):\n if self.drawers[random.choice(self.drawer_ids)] == player_number:\n return True\n\n return False\n\n def play_naive_mem(self, player_number):\n \"\"\" Randomly open drawers but avoiding repetitions \"\"\"\n not_attemped = self.drawer_ids[:]\n for attempt in range(self.max_attempts):\n guess = random.choice(not_attemped)\n not_attemped.remove(guess)\n\n if self.drawers[guess] == player_number:\n return True\n\n return False\n\n def play_optimum(self, player_number):\n \"\"\" Open the drawer that matches the player number and then open the drawer\n with the revealed number.\n \"\"\"\n prev_attempt = player_number\n for attempt in range(self.max_attempts):\n if self.drawers[prev_attempt] == player_number:\n return True\n else:\n prev_attempt = self.drawers[prev_attempt]\n\n return False\n\n @classmethod\n def victory(csl, results):\n \"\"\"Defines a victory of a game: all players won\"\"\"\n return all(results)\n\n approaches = [play_naive, play_naive_mem, play_optimum]\n\n def play(self, approach):\n \"\"\"Plays this game and returns a list of booleans with\n True if a player one, False otherwise\"\"\"\n return [approach(self, player) for player in self.drawer_ids]\n\n\nif __name__ == '__main__':\n main()\n", "safe": true }, { "filename": "100 prisoners_136.txt", "content": "With 10 drawers (100k runs)\napproach \u00a0: wins (ratio)\nplay_naive \u00a0: 14 (0.01%)\nplay_naive_mem\u00a0: 74 (0.07%)\nplay_optimum \u00a0: 35410 (35.41%)\n\nWith 100 drawers (10k runs)\napproach \u00a0: wins (ratio)\nplay_naive \u00a0: 0 (0.00%)\nplay_naive_mem\u00a0: 0 (0.00%)\nplay_optimum \u00a0: 3084 (30.84%)", "safe": true }, { "filename": "100 prisoners_137.txt", "content": "'''100 Prisoners'''\n\nfrom random import randint, sample\n\n\n# allChainedPathsAreShort\u00a0:: Int -> IO (0|1)\ndef allChainedPathsAreShort(n):\n '''1 if none of the index-chasing cycles in a shuffled\n sample of [1..n] cards are longer than half the\n sample size. Otherwise, 0.\n '''\n limit = n // 2\n xs = range(1, 1 + n)\n shuffled = sample(xs, k=n)\n\n # A cycle of boxes, drawn from a shuffled\n # sample, which includes the given target.\n def cycleIncluding(target):\n boxChain = [target]\n v = shuffled[target - 1]\n while v != target:\n boxChain.append(v)\n v = shuffled[v - 1]\n return boxChain\n\n # Nothing if the target list is empty, or if the cycle which contains the\n # first target is larger than half the sample size.\n # Otherwise, just a cycle of enchained boxes containing the first target\n # in the list, tupled with the residue of any remaining targets which\n # fall outside that cycle.\n def boxCycle(targets):\n if targets:\n boxChain = cycleIncluding(targets[0])\n return Just((\n difference(targets[1:])(boxChain),\n boxChain\n )) if limit >= len(boxChain) else Nothing()\n else:\n return Nothing()\n\n # No cycles longer than half of total box count\u00a0?\n return int(n == sum(map(len, unfoldr(boxCycle)(xs))))\n\n\n# randomTrialResult\u00a0:: RandomIO (0|1) -> Int -> (0|1)\ndef randomTrialResult(coin):\n '''1 if every one of the prisoners finds their ticket\n in an arbitrary half of the sample. Otherwise 0.\n '''\n return lambda n: int(all(\n coin(x) for x in range(1, 1 + n)\n ))\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n '''Two sampling techniques constrasted with 100 drawers\n and 100 prisoners, over 100,000 trial runs.\n '''\n halfOfDrawers = randomRInt(0)(1)\n\n def optimalDrawerSampling(x):\n return allChainedPathsAreShort(x)\n\n def randomDrawerSampling(x):\n return randomTrialResult(halfOfDrawers)(x)\n\n # kSamplesWithNBoxes\u00a0:: Int -> Int -> String\n def kSamplesWithNBoxes(k):\n tests = range(1, 1 + k)\n return lambda n: '\\n\\n' + fTable(\n str(k) + ' tests of optimal vs random drawer-sampling ' +\n 'with ' + str(n) + ' boxes: \\n'\n )(fName)(lambda r: '{:.2%}'.format(r))(\n lambda f: sum(f(n) for x in tests) / k\n )([\n optimalDrawerSampling,\n randomDrawerSampling,\n ])\n\n print(kSamplesWithNBoxes(10000)(10))\n\n print(kSamplesWithNBoxes(10000)(100))\n\n print(kSamplesWithNBoxes(100000)(100))\n\n\n# ------------------------DISPLAY--------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# fname\u00a0:: (a -> b) -> String\ndef fName(f):\n '''Name bound to the given function.'''\n return f.__name__\n\n\n# ------------------------GENERIC -------------------------\n\n# Just\u00a0:: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing\u00a0:: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# difference\u00a0:: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of xs, except any also found in ys.'''\n return lambda ys: list(set(xs) - set(ys))\n\n\n# randomRInt\u00a0:: Int -> Int -> IO () -> Int\ndef randomRInt(m):\n '''The return value of randomRInt is itself\n a function. The returned function, whenever\n called, yields a a new pseudo-random integer\n in the range [m..n].\n '''\n return lambda n: lambda _: randint(m, n)\n\n\n# unfoldr(lambda x: Just((x, x - 1)) if 0\u00a0!= x else Nothing())(10)\n# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n# unfoldr\u00a0:: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns Just(a, b), a is prepended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n xr = v, v\n xs = []\n while True:\n mb = f(xr[0])\n if mb.get('Nothing'):\n return xs\n else:\n xr = mb.get('Just')\n xs.append(xr[1])\n return xs\n return lambda x: go(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "safe": true }, { "filename": "100 prisoners_138.txt", "content": "10000 tests of optimal vs random drawer-sampling with 10 boxes: \n\noptimalDrawerSampling -> 35.47%\n randomDrawerSampling -> 0.09%\n\n10000 tests of optimal vs random drawer-sampling with 100 boxes: \n\noptimalDrawerSampling -> 30.40%\n randomDrawerSampling -> 0.00%\n\n100000 tests of optimal vs random drawer-sampling with 100 boxes: \n\noptimalDrawerSampling -> 31.17%\n randomDrawerSampling -> 0.00%", "safe": true }, { "filename": "100 prisoners_139.txt", "content": "t = 100000 #number of trials\nsuccess.r = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the random method\nsuccess.o = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the optimal method\n\n#random method\nfor(i in 1:t){\n escape = rep(F,100)\n ticket = sample(1:100)\n for(j in 1:length(prisoner)){\n escape[j] = j %in% sample(ticket,50)\n }\n success.r[i] = sum(escape)\n}\n\n#optimal method\nfor(i in 1:t){\n escape = rep(F,100)\n ticket = sample(1:100)\n for(j in 1:100){\n boxes = 0\n current.box = j\n while(boxes<50 && !escape[j]){\n boxes=boxes+1\n escape[j] = ticket[current.box]==j\n current.box = ticket[current.box]\n }\n }\n success.o[i] = sum(escape)\n}\n\ncat(\"Random method resulted in a success rate of \",100*mean(success.r==100),\n \"%.\\nOptimal method resulted in a success rate of \",100*mean(success.o==100),\"%.\",sep=\"\")\n", "safe": true }, { "filename": "100 prisoners_14.txt", "content": "100 PRISONERS\n\nRESULTS:\n\n OUT OF 4000 TRIALS, THE RESULTS ARE\n AS FOLLOWS...\n\n1. RANDOM GUESSING:\n\n 0 SUCCESSES 4000 FAILURES\n\n 0% SUCCESS RATE.\n\n2. CHAINED NUMBER PICKING:\n\n 1278 SUCCESSES 2722 FAILURES\n\n 31.95% SUCCESS RATE.\n", "safe": true }, { "filename": "100 prisoners_140.txt", "content": "Random method resulted in a success rate of 0%.\nOptimal method resulted in a success rate of 31.129%.", "safe": true }, { "filename": "100 prisoners_141.txt", "content": "Const Found = -1, Searching = 0, Status = 1, Tries = 2\nConst Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2\nRandomize Timer\n\nDim Shared Prisoners(1 To 100, Status To Tries) As Integer, Drawers(1 To 100) As Integer, Results(1 To 2, 1 To 2) As Integer\nPrint \"100 prisoners\"\nPrint \"Random way to search...\"\nFor a = 1 To 2000\n Init\n Results(RandomW, Attempt) = Results(RandomW, Attempt) + 1\n RandomWay\n If verify% Then Results(RandomW, Victories) = Results(RandomW, Victories) + 1\nNext\n\nPrint: Print \"Chain way to search...\"\nFor a = 1 To 2000\n Init\n Results(ChainW, Attempt) = Results(ChainW, Attempt) + 1\n ChainWay\n If verify% Then Results(ChainW, Victories) = Results(ChainW, Victories) + 1\nNext\nPrint: Print \"Results: \"\nPrint \" Attempts \"; Results(RandomW, Attempt); \" \"; \"Victories \"; Results(RandomW, Victories); \" Ratio:\"; Results(RandomW, Victories); \"/\"; Results(RandomW, Attempt)\nPrint\nPrint \" Attempts \"; Results(ChainW, Attempt); \" \"; \"Victories \"; Results(ChainW, Victories); \" Ratio:\"; Results(ChainW, Victories); \"/\"; Results(ChainW, Attempt)\nEnd\n\nFunction verify%\n Dim In As Integer\n Print \"veryfing \"\n verify = 0\n For In = 1 To 100\n If Prisoners(In, Status) = Searching Then Exit For\n Next\n If In = 101 Then verify% = Found\nEnd Function\n\nSub ChainWay\n Dim In As Integer, ChainChoice As Integer\n Print \"Chain search\"\n For In = 1 To 100\n ChainChoice = In\n Do\n Prisoners(In, Tries) = Prisoners(In, Tries) + 1\n If Drawers(ChainChoice) = In Then Prisoners(In, Status) = Found: Exit Do\n ChainChoice = Drawers(ChainChoice)\n Loop Until Prisoners(In, Tries) = 50\n Next In\nEnd Sub\n\nSub RandomWay\n Dim In As Integer, RndChoice As Integer\n Print \"Random search\"\n For In = 1 To 100\n Do\n Prisoners(In, Tries) = Prisoners(In, Tries) + 1\n If Drawers(Int(Rnd * 100) + 1) = In Then Prisoners(In, Status) = Found: Exit Do\n Loop Until Prisoners(In, Tries) = 50\n Next\n Print \"Executed \"\nEnd Sub\n\n\nSub Init\n Dim I As Integer, I2 As Integer\n Print \"initialization\"\n For I = 1 To 100\n Prisoners(I, Status) = Searching\n Prisoners(I, Tries) = Searching\n Do\n Drawers(I) = Int(Rnd * 100) + 1\n For I2 = 1 To I\n If Drawers(I2) = Drawers(I) Then Exit For\n Next\n If I2 = I Then Exit Do\n Loop\n Next I\n Print \"Done \"\nEnd Sub", "safe": true }, { "filename": "100 prisoners_142.txt", "content": " [ this ] is 100prisoners.qky\n\n [ dup size 2 / split ] is halve ( [ --> [ [ )\n\n [ stack ] is successes ( --> s )\n\n [ [] swap times [ i join ] shuffle ] is drawers ( n --> [ )\n\n [ false unrot\n temp put \n dup shuffle\n halve drop\n witheach\n [ dip dup peek\n temp share = if\n [ dip not\n conclude ] ]\n drop\n temp release ] is naive ( [ n --> b )\n\n [ false unrot \n dup temp put\n over size 2 / times \n [ dip dup peek\n dup temp share = if\n [ rot not unrot\n conclude ] ]\n 2drop\n temp release ] is smart ( [ n --> b )\n\n [ ]'[ temp put\n drawers\n 0 successes put\n dup size times \n [ dup i temp share do\n successes tally ]\n size successes take = \n temp release ] is prisoners ( n --> b )\n \n [ say \"100 naive prisoners were pardoned \"\n 0 10000 times [ 100 prisoners naive + ] echo\n say \" times out of 10000 simulations.\" cr\n\n say \"100 smart prisoners were pardoned \"\n 0 10000 times [ 100 prisoners smart + ] echo\n say \" times out of 10000 simulations.\" cr ] is simulate ( --> )", "safe": true }, { "filename": "100 prisoners_143.txt", "content": "/O> [ $ '100prisoners.qky' loadfile ] now!\n... simulate\n... \n100 naive prisoners were pardoned 0 times out of 10000 simulations.\n100 smart prisoners were pardoned 3158 times out of 10000 simulations.\n\nStack empty.", "safe": true }, { "filename": "100 prisoners_144.txt", "content": "#lang racket\n(require srfi/1)\n\n(define current-samples (make-parameter 10000))\n(define *prisoners* 100)\n(define *max-guesses* 50)\n\n(define (evaluate-strategy instance-solved? strategy (s (current-samples)))\n (/ (for/sum ((_ s) #:when (instance-solved? strategy)) 1) s))\n\n(define (build-drawers)\n (list->vector (shuffle (range *prisoners*))))\n\n(define (100-prisoners-problem strategy)\n (every (strategy (build-drawers)) (range *prisoners*)))\n\n(define ((strategy-1 drawers) p)\n (any (\u03bb (_) (= p (vector-ref drawers (random *prisoners*)))) (range *max-guesses*)))\n\n(define ((strategy-2 drawers) p)\n (define-values (_ found?)\n (for/fold ((d p) (found? #f)) ((_ *max-guesses*)) #:break found?\n (let ((card (vector-ref drawers d))) (values card (= card p)))))\n found?)\n\n(define (print-sample-percentage caption f (s (current-samples)))\n (printf \"~a: ~a%~%\" caption (real->decimal-string (* 100 f) (- (order-of-magnitude s) 2))))\n\n(module+ main\n (print-sample-percentage \"random\" (evaluate-strategy 100-prisoners-problem strategy-1))\n (print-sample-percentage \"optimal\" (evaluate-strategy 100-prisoners-problem strategy-2)))\n", "safe": true }, { "filename": "100 prisoners_145.txt", "content": "random: 0.00%\noptimal: 31.18%", "safe": true }, { "filename": "100 prisoners_146.txt", "content": "unit sub MAIN (:$prisoners = 100,\u00a0:$simulations = 10000);\nmy @prisoners = ^$prisoners;\nmy $half = floor +@prisoners / 2;\n\nsub random ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n for @drawers.pick($half) -> $card {\n $found = 1 and last if $card == $prisoner\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsub optimal ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n my $card = @drawers[$prisoner];\n if $card == $prisoner {\n $found = 1\n } else {\n for ^($half - 1) {\n $card = @drawers[$card];\n $found = 1 and last if $card == $prisoner\n }\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsay \"Testing $simulations simulations with $prisoners prisoners.\";\nprintf \" Random play wins:\u00a0%.3f%% of simulations\\n\", random $simulations;\nprintf \"Optimal play wins:\u00a0%.3f%% of simulations\\n\", optimal $simulations;\n", "safe": true }, { "filename": "100 prisoners_147.txt", "content": "Testing 10000 simulations with 100 prisoners.\n Random play wins: 0.000% of simulations\nOptimal play wins: 30.510% of simulations", "safe": true }, { "filename": "100 prisoners_148.txt", "content": "Testing 100000 simulations with 10 prisoners.\n Random play wins: 0.099% of simulations\nOptimal play wins: 35.461% of simulations\n", "safe": true }, { "filename": "100 prisoners_149.txt", "content": "Red []\n\nK_runs: 100000\nrepeat n 100 [append rand_arr: [] n] ;; define array/series with numbers 1..100\n\n;;-------------------------------\nstrat_optimal: function [pris ][\n;;-------------------------------\n locker: pris ;; start with locker equal to prisoner number\n loop 50 [\n if Board/:locker = pris [ return true ] ;; locker with prisoner number found\n locker: Board/:locker\n ]\n false ;; number not found - fail\n]\n;;-------------------------------\nstrat_rand: function [pris ][\n;;-------------------------------\n random rand_arr ;; define set of random lockers\n repeat n 50 [ if Board/(rand_arr/:n) = pris [ return true ] ] ;; try first 50, found\u00a0? then return success\n false \n]\n\n;;------------------------------\ncheck_board: function [ strat][\n;;------------------------------\nrepeat pris 100 [ ;; for each prisoner\n either strat = 'optimal [ unless strat_optimal pris [return false ] ] \n [ unless strat_rand pris [return false ] ] \n] \n true ;; all 100 prisoners passed test\n]\n\nsaved: saved_rand: 0 ;; count all saved runs per strategy\nloop K_runs [\n Board: random copy rand_arr ;; new board for every run\n if check_board 'optimal [saved: saved + 1] ;; optimal stategy\n if check_board 'rand [saved_rand: saved_rand + 1] ;; random strategy\n]\n\nprint [\"runs\" k_runs newline \"Percent saved opt.strategy:\" saved * 100.0 / k_runs ]\nprint [\"Percent saved random strategy:\" saved_rand * 100.0 / k_runs ]\n", "safe": true }, { "filename": "100 prisoners_15.txt", "content": "/* ARM assembly Raspberry PI */\n/* program prisonniers.s */ \n\n/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include */\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n\n.equ NBDOORS, 100\n.equ NBLOOP, 1000\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"Random strategie \u00a0: @ sur 1000 \\n\"\nsMessResultOPT: .asciz \"Optimal strategie\u00a0: @ sur 1000 \\n\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\niGraine: .int 123456\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\ntbDoors: .skip 4 * NBDOORS \ntbTest: .skip 4 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n \n ldr r1,iAdrtbDoors\n mov r2,#0\n1: @ loop init doors table\n add r3,r2,#1\n str r3,[r1,r2,lsl #2]\n add r2,r2,#1\n cmp r2,#NBDOORS\n blt 1b\n \n mov r9,#0 @ loop counter\n mov r10,#0 @ counter successes random strategie\n mov r11,#0 @ counter successes optimal strategie\n2:\n ldr r0,iAdrtbDoors\n mov r1,#NBDOORS\n bl knuthShuffle\n \n ldr r0,iAdrtbDoors\n bl aleaStrategie\n cmp r0,#NBDOORS\n addeq r10,r10,#1\n \n ldr r0,iAdrtbDoors\n bl optimaStrategie\n cmp r0,#NBDOORS\n addeq r11,r11,#1\n \n add r9,r9,#1\n cmp r9,#NBLOOP\n blt 2b\n \n mov r0,r10 @ result display\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResult\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n mov r0,r11 @ result display\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResultOPT\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrsMessResultOPT: .int sMessResultOPT\niAdrtbDoors: .int tbDoors\niAdrtbTest: .int tbTest\niAdrsZoneConv: .int sZoneConv\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* r0 contains the address of table */\naleaStrategie:\n push {r1-r7,lr} @ save registers\n ldr r6,iAdrtbTest @ table doors tests address\n mov r1,r0 @ save table doors address\n mov r4,#0 @ counter number of successes\n mov r2,#0 @ prisonners indice\n1:\n bl razTable @ zero to table doors tests\n mov r5,#0 @ counter of door tests \n add r7,r2,#1\n2:\n mov r0,#NBDOORS - 1\n bl genereraleas @ random test\n add r0,r0,#1\n ldr r3,[r6,r0,lsl #2] @ doors also tested\u00a0?\n cmp r3,#0 \n bne 2b @ yes\n ldr r3,[r1,r0,lsl #2] @ load N\u00b0 door\n cmp r3,r7 @ compar N\u00b0 door N\u00b0 prisonner\n addeq r4,r4,#1 @ succes\n beq 3f\n mov r3,#1 @ top test table item \n str r3,[r6,r0,lsl #2]\n add r5,r5,#1\n cmp r5,#NBDOORS / 2 @ number tests maxi\u00a0?\n blt 2b @ no -> loop\n3:\n add r2,r2,#1 @ other prisonner\n cmp r2,#NBDOORS\n blt 1b\n \n mov r0,r4 @ return number of successes \n100:\n pop {r1-r7,lr}\n bx lr @ return \n/******************************************************************/\n/* raz test table */ \n/******************************************************************/\nrazTable:\n push {r0-r2,lr} @ save registers\n ldr r0,iAdrtbTest\n mov r1,#0 @ item indice\n mov r2,#0\n1:\n str r2,[r0,r1,lsl #2] @ store zero \u00e0 item\n add r1,r1,#1\n cmp r1,#NBDOORS\n blt 1b\n100:\n pop {r0-r2,lr}\n bx lr @ return \n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* r0 contains the address of table */\noptimaStrategie:\n push {r1-r7,lr} @ save registers\n mov r4,#0 @ counter number of successes\n mov r2,#0 @ counter prisonner\n1:\n mov r5,#0 @ counter test\n mov r1,r2 @ first test = N\u00b0 prisonner\n2:\n ldr r3,[r0,r1,lsl #2] @ load N\u00b0 door\n cmp r3,r2\n addeq r4,r4,#1 @ equal -> succes\n beq 3f\n mov r1,r3 @ new test with N\u00b0 door\n add r5,r5,#1 \n cmp r5,#NBDOORS / 2 @ test number maxi\u00a0?\n blt 2b\n3:\n add r2,r2,#1 @ other prisonner\n cmp r2,#NBDOORS\n blt 1b\n \n mov r0,r4\n100:\n pop {r1-r7,lr}\n bx lr @ return \n/******************************************************************/\n/* knuth Shuffle */ \n/******************************************************************/\n/* r0 contains the address of table */\n/* r1 contains the number of elements */\nknuthShuffle:\n push {r2-r5,lr} @ save registers\n mov r5,r0 @ save table address\n mov r2,#0 @ start index\n1:\n mov r0,r2 @ generate aleas\n bl genereraleas\n ldr r3,[r5,r2,lsl #2] @ swap number on the table\n ldr r4,[r5,r0,lsl #2]\n str r4,[r5,r2,lsl #2]\n str r3,[r5,r0,lsl #2]\n add r2,#1 @ next number\n cmp r2,r1 @ end\u00a0?\n blt 1b @ no -> loop\n100:\n pop {r2-r5,lr}\n bx lr @ return \n/***************************************************/\n/* Generation random number */\n/***************************************************/\n/* r0 contains limit */\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n/*****************************************************/\niAdriGraine: .int iGraine\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"", "safe": true }, { "filename": "100 prisoners_150.txt", "content": "\n\nruns 100000\nPercent saved opt.strategy: 31.165\nPercent saved random strategy: 0.0\n\n", "safe": true }, { "filename": "100 prisoners_151.txt", "content": "/*REXX program to simulate the problem of 100 prisoners: random, and optimal strategy.*/\nparse arg men trials seed . /*obtain optional arguments from the CL*/\nif men=='' | men==\",\" then men= 100 /*number of prisoners for this run.*/\nif trials=='' | trials==\",\" then trials= 100000 /* \" \" simulations \" \" \" */\nif datatype(seed, 'W') then call random ,,seed /*seed for the random number generator.*/\ntry= men % 2; swaps= men * 3 /*number tries for searching for a card*/\n$.1= ' a simple '; $.2= \"an optimal\" /*literals used for the SAY instruction*/\nsay center(' running' commas(trials) \"trials with\" commas(men) 'prisoners ', 70, \"\u2550\")\nsay\n do strategy=1 for 2; pardons= 0 /*perform the two types of strategies. */\n\n do trials; call gCards /*do trials for a strategy; gen cards.*/\n do p=1 for men until failure /*have each prisoner go through process*/\n if strategy==1 then failure= simple() /*Is 1st strategy? Use simple strategy*/\n else failure= picker() /* \" 2nd \" \" optimal \" */\n end /*p*/ /*FAILURE \u2261 1? Then a prisoner failed.*/\n if #==men then pardons= pardons + 1 /*was there a pardon of all prisoners? */\n end /*trials*/ /*if 1 prisoner fails, then they all do*/\n\n pc= format( pardons/trials*100, , 3); _= left('', pc<10)\n say right('Using', 9) $.strategy \"strategy yields pardons \" _||pc\"% of the time.\"\n end /*strategy*/\nexit /*stick a fork in it, we're all done. */\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\ncommas: parse arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\ngCards: #= 0; do j=1 for men; @.j= j /*define seq. of cards*/\n end /*j*/ /*same as seq. of men.*/\n do swaps; a= random(1, men) /*get 1st rand number.*/\n do until b\\==a; b= random(1, men) /* \" 2nd \" \" */\n end /*until*/ /* [\u2191] ensure A \u00ac== B */\n parse value @.a @.b with @.b @.a /*swap 2 random cards.*/\n end /*swaps*/; return\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\nsimple: !.= 0; do try; do until !.?==0; ?= random(1, men) /*get random card \u00b7\u00b7\u00b7 */\n end /*until*/ /*\u00b7\u00b7\u00b7 not used before.*/\n if @.?==p then do; #= #+1; return 0; end /*found his own card? */\n !.?= 1 /*flag as being used. */\n end /*try*/; return 1 /*didn't find his card*/\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\npicker: ?= p; do try; if @.?==p then do; #= #+1; return 0 /*Found his own card? */\n end /* [\u2191] indicate success for prisoner. */\n ?= @.? /*choose next drawer from current card.*/\n end /*try*/; return 1 /*choose half of the number of drawers.*/\n", "safe": true }, { "filename": "100 prisoners_152.txt", "content": "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 running 100,000 trials with 100 prisoners \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n Using a simple strategy yields pardons 0.000% of the time.\n Using an optimal strategy yields pardons 31.186% of the time.\n", "safe": true }, { "filename": "100 prisoners_153.txt", "content": "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 running 100,000 trials with 10 prisoners \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n Using a simple strategy yields pardons 0.086% of the time.\n Using an optimal strategy yields pardons 31.204% of the time.\n", "safe": true }, { "filename": "100 prisoners_154.txt", "content": "prisoners = [*1..100]\nN = 10_000\ngenerate_rooms = ->{ [nil]+[*1..100].shuffle }\n \nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)}\nend\nputs \"Random strategy\u00a0: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n\nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? do |pr|\n cur_room = pr\n 50.times.any? do\n found = (rooms[cur_room] == pr)\n cur_room = rooms[cur_room]\n found\n end\n end\nend\nputs \"Optimal strategy: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n", "safe": true }, { "filename": "100 prisoners_155.txt", "content": "Random strategy\u00a0: 0.0000\u00a0%\nOptimal strategy: 30.7400\u00a0%\n", "safe": true }, { "filename": "100 prisoners_156.txt", "content": "[dependencies]\nrand = '0.7.2'\n", "safe": true }, { "filename": "100 prisoners_157.txt", "content": "extern crate rand;\n\nuse rand::prelude::*;\n\n// Do a full run of checking boxes in a random order for a single prisoner\nfn check_random_boxes(prisoner: u8, boxes: &[u8]) -> bool {\n let checks = {\n let mut b: Vec = (1u8..=100u8).collect();\n b.shuffle(&mut rand::thread_rng());\n b\n };\n checks.into_iter().take(50).any(|check| boxes[check as usize - 1] == prisoner)\n}\n\n// Do a full run of checking boxes in the optimized order for a single prisoner\nfn check_ordered_boxes(prisoner: u8, boxes: &[u8]) -> bool {\n let mut next_check = prisoner;\n (0..50).any(|_| {\n next_check = boxes[next_check as usize - 1];\n next_check == prisoner\n })\n}\n\nfn main() {\n let mut boxes: Vec = (1u8..=100u8).collect();\n\n let trials = 100000;\n\n let ordered_successes = (0..trials).filter(|_| {\n boxes.shuffle(&mut rand::thread_rng());\n (1u8..=100u8).all(|prisoner| check_ordered_boxes(prisoner, &boxes))\n }).count();\n\n let random_successes = (0..trials).filter(|_| {\n boxes.shuffle(&mut rand::thread_rng());\n (1u8..=100u8).all(|prisoner| check_random_boxes(prisoner, &boxes))\n }).count();\n\n println!(\"{} / {} ({:.02}%) successes in ordered\", ordered_successes, trials, ordered_successes as f64 * 100.0 / trials as f64);\n println!(\"{} / {} ({:.02}%) successes in random\", random_successes, trials, random_successes as f64 * 100.0 / trials as f64);\n\n}\n", "safe": true }, { "filename": "100 prisoners_158.txt", "content": "31106 / 100000 (31.11%) successes in ordered\n0 / 100000 (0.00%) successes in random", "safe": true }, { "filename": "100 prisoners_159.txt", "content": "class MAIN is\n shuffle (a: ARRAY{INT}) is\n ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);\n end;\n\n try_random (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is\n my_tries\u00a0::= drawers.inds; shuffle(my_tries);\n loop tries.times!;\n if drawers[my_tries.elt!] = n then return true; end;\n end;\n return false;\n end;\n\n try_optimal (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is\n num\u00a0::= n;\n loop tries.times!;\n num\u00a0:= drawers[num];\n if num = n then return true; end;\n end;\n return false;\n end;\n\n stats (label: STR, rounds, successes: INT): STR is\n return #FMT(\"<^###########>: <#######> rounds. Successes: <#######> (<##.###>%%)\\n\",\n label, rounds, successes, (successes.flt / rounds.flt)*100.0).str;\n end;\n\n try (name: STR, nrounds, ndrawers, npris, ntries: INT,\n strategy: ROUT{INT,ARRAY{INT},INT}:BOOL)\n is\n drawers: ARRAY{INT}\u00a0:= #(ndrawers);\n loop drawers.set!(drawers.ind!); end;\n successes\u00a0::= 0;\n loop nrounds.times!;\n shuffle(drawers);\n success\u00a0::= true;\n loop\n n\u00a0::= npris.times!;\n if ~strategy.call(n, drawers, ntries) then\n success\u00a0:= false;\n break!;\n end;\n end;\n if success then successes\u00a0:= successes + 1; end;\n end;\n #OUT + stats(name, nrounds, successes);\n end;\n\n main is\n RND::seed\u00a0:= #TIMES.wall_time;\n #OUT +\"100 prisoners, 100 drawers, 50 tries:\\n\";\n try(\"random\", 100000, 100, 100, 50, bind(try_random(_, _, _)));\n try(\"optimal\", 100000, 100, 100, 50, bind(try_optimal(_, _, _)));\n\n #OUT +\"\\n10 prisoners, 10 drawers, 5 tries:\\n\";\n try(\"random\", 100000, 10, 10, 5, bind(try_random(_, _, _)));\n try(\"optimal\", 100000, 10, 10, 5, bind(try_optimal(_, _, _)));\n end;\nend;", "safe": true }, { "filename": "100 prisoners_16.txt", "content": "Random strategie \u00a0: 0 sur 1000\nOptimal strategie\u00a0: 303 sur 1000\n", "safe": true }, { "filename": "100 prisoners_160.txt", "content": "100 prisoners, 100 drawers, 50 tries:\nrandom \u00a0: 100000 rounds. Successes: 0 ( 0.000%)\noptimal \u00a0: 100000 rounds. Successes: 31378 (31.378%)\n\n10 prisoners, 10 drawers, 5 tries:\nrandom \u00a0: 100000 rounds. Successes: 113 ( 0.113%)\noptimal \u00a0: 100000 rounds. Successes: 35633 (35.633%)", "safe": true }, { "filename": "100 prisoners_161.txt", "content": "import scala.util.Random\nimport scala.util.control.Breaks._\n\nobject Main {\n def playOptimal(n: Int): Boolean = {\n val secretList = Random.shuffle((0 until n).toBuffer)\n\n for (i <- secretList.indices) {\n var prev = i\n breakable {\n for (_ <- 0 until secretList.size / 2) {\n if (secretList(prev) == i) {\n break()\n }\n prev = secretList(prev)\n }\n return false\n }\n }\n\n true\n }\n\n def playRandom(n: Int): Boolean = {\n val secretList = Random.shuffle((0 until n).toBuffer)\n\n for (i <- secretList.indices) {\n val trialList = Random.shuffle((0 until n).toBuffer)\n\n breakable {\n for (j <- 0 until trialList.size / 2) {\n if (trialList(j) == i) {\n break()\n }\n }\n return false\n }\n }\n\n true\n }\n\n def exec(n: Int, p: Int, play: Int => Boolean): Double = {\n var succ = 0.0\n for (_ <- 0 until n) {\n if (play(p)) {\n succ += 1\n }\n }\n (succ * 100.0) / n\n }\n\n def main(args: Array[String]): Unit = {\n val n = 100000\n val p = 100\n printf(\"# of executions:\u00a0%,d\\n\", n)\n printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, playOptimal))\n printf(\"Random play success rate: %f%%\\n\", exec(n, p, playRandom))\n }\n}\n", "safe": true }, { "filename": "100 prisoners_162.txt", "content": "# of executions: 100,000\nOptimal play success rate: 31.201000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100 prisoners_163.txt", "content": "program prisoners;\n setrandom(0);\n \n strategies\u00a0:= {\n [\"Optimal\", routine optimal_strategy],\n [\"Random\", routine random_strategy]\n };\n \n runs\u00a0:= 10000;\n\n loop for strategy = strategies(name) do\n successes\u00a0:= run_simulations(strategy, runs);\n print(rpad(name + \":\", 10), successes * 100 / runs, \"%\");\n end loop;\n \n proc run_simulations(strategy, amount);\n loop for i in [1..amount] do\n successes +:= if simulate(strategy) then 1 else 0 end;\n end loop;\n return successes; \n end proc;\n \n proc simulate(strategy);\n drawers\u00a0:= [1..100];\n shuffle(drawers);\n loop for prisoner in [1..100] do\n if not call(strategy, drawers, prisoner) then\n return false;\n end if;\n end loop;\n return true;\n end proc;\n \n proc optimal_strategy(drawers, prisoner);\n d\u00a0:= prisoner;\n loop for s in [1..50] do\n if (d\u00a0:= drawers(d)) = prisoner then\n return true;\n end if;\n end loop;\n return false;\n end proc;\n \n proc random_strategy(drawers, prisoner);\n loop for s in [1..50] do\n if drawers(1+random(#drawers-1)) = prisoner then\n return true;\n end if;\n end loop;\n return false;\n end proc;\n \n proc shuffle(rw drawers);\n loop for i in [1..#drawers] do\n j\u00a0:= i+random(#drawers-i);\n [drawers(i), drawers(j)]\u00a0:= [drawers(j), drawers(i)];\n end loop;\n end proc;\nend program;", "safe": true }, { "filename": "100 prisoners_164.txt", "content": "Optimal: 31.26\u00a0%\nRandom: 0\u00a0%", "safe": true }, { "filename": "100 prisoners_165.txt", "content": "// ==========================================================================\n// START-SuperCollider solution to Rosetta Code TASK: 100 prisoners\t\t\t\t ## BY: MusicCoder\u00a0: 2024-06-08 ##\n// ==========================================================================\n\n(\n/* ## BY: MusicCoder\u00a0: 2024-06-08 ##\nhttps://rosettacode.org/wiki/100_prisoners\nTHE TASK: Simulate the 100-prisoners game and compare two strategies\n1: random choice, 2: follow the cards.\n\n*** My preferance - make a function to play the game\n ... and feed it a function for each strategy ***\nUse 0..99 rather than 1..100 for player, card and drawer numbers\n\nWhat can a player possibly know?\n1. Player number\n2. Current turn number\n3. Previous drawer picked \u00a0: -1 means no previous as yet\n4. Previous card value \u00a0: -1 means no previous as yet\n5. Number of drawers ( PROBABLY == number of players)\n6. Number of turns\n\n--- These parameters should be good for a lot of different strategies ---\n\nStatergy function will get called with values for these six parameters\nStatergy function should return a drawerNumber\n*/\n// =============================================================================\n// *** THE REQUIRED STRATEGY FUNCTIONS ***\n// =============================================================================\n// strategyRandom: Pick a drawer number at random\nvar strategyRandom = {\n |turnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns|\n\n var drawerPicked = numDrawers.rand;\n drawerPicked;\n};\n// =============================================================================\n// strategyFollow: Start at drawerNumber = playerNumber, then follow the cardNumbers\nvar strategyFollow = {\n |turnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns|\n\n var drawerPicked = if ( (previousCard == -1), {playerNumber}, {previousCard});\n drawerPicked;\n};\n\n// =============================================================================\n/* ### playGame: Function to play the game ###\n// =============================================================================\nTwo loops: outer loop over players, inner loop over turns for each player\nThe core of the inner loop calls the supplied stratergy function\n ... passing in values for the six parameters:\nturnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns\nThe stratergy function responds with the number of the drawer it has picked\n ... for the current turn\n*/\nvar playGame = {\n |strategy, strategyName=\"\", numPlayers=100, numDrawers=100, numTurns=50, numSims=10000|\n var percentWins=0;\n var countWins=0;\n var drawers=Array.iota(numPlayers); // fill array with player numbers 0..99\n\n numSims.do{\n var playerWon = true; // as soon as one player fails - exit this simulation\n var playerNumber = 0; // first player\n\n drawers = drawers.scramble; // randomly reorder the cards in the drawers\n\n while(// loop until the last player or until any player fails\n {playerNumber Bool {\n for num in 1...numPrisoners {\n guard findNumber(num) else {\n return false\n }\n }\n\n return true\n }\n\n private func findNumber(_ num: Int) -> Bool {\n var tries = 0\n var nextDrawer = num - 1\n\n while tries < 50 {\n tries += 1\n\n switch strategy {\n case .random where drawers.randomElement()! == num:\n return true\n case .optimum where drawers[nextDrawer] == num:\n return true\n case .optimum:\n nextDrawer = drawers[nextDrawer] - 1\n case _:\n continue\n }\n }\n\n return false\n }\n\n enum Strategy {\n case random, optimum\n }\n}\n\nlet numGames = 100_000\nlet lock = DispatchSemaphore(value: 1)\nvar done = 0\n\nprint(\"Running \\(numGames) games for each strategy\")\n\nDispatchQueue.concurrentPerform(iterations: 2) {i in\n let strat = i == 0 ? PrisonersGame.Strategy.random : .optimum\n var numPardoned = 0\n\n for _ in 0..= 0\n}\n\n# Runs each of the STRATEGIES and prints a report on how well they\n# worked.\nproc compareStrategies {strategies} {\n global Samples\n set fmt \"Using %s %s strategy, the prisoners were freed in %5.2f%% of the cases.\"\n foreach strategy $strategies {\n set article [expr [startsWithVowel $strategy] ? {\"an\"} : {\"a\"}]\n set pct [expr [sampling ${strategy}Strategy] / $Samples.0 * 100]\n puts [format $fmt $article $strategy $pct]\n }\n}\n\ncompareStrategies $Strategies\n", "safe": true }, { "filename": "100 prisoners_17.txt", "content": "unplanned: function [][\n drawers: shuffle @1..100\n every? 1..100 'x -> some? 1..50 => [x = sample drawers]\n]\n\nplanned: function [][\n drawers: shuffle @1..100\n every? 1..100 'x [\n next: x\n some? 1..50 => [x = next: <= drawers\\[next-1]]\n ]\n]\n\ntest: function [f][\n count: enumerate 10000 => [call f []]\n print [f ~\"|mul fdiv count 10000 100|%\"]\n]\n\ntest 'unplanned\ntest 'planned\n", "safe": true }, { "filename": "100 prisoners_170.txt", "content": "Using a random strategy, the prisoners were freed in 0.00% of the cases.\nUsing an optimal strategy, the prisoners were freed in 32.35% of the cases.", "safe": true }, { "filename": "100 prisoners_171.txt", "content": "USE rosettacode;\nGO\n\nSET NOCOUNT ON;\nGO\n\nCREATE TABLE dbo.numbers (n INT PRIMARY KEY);\nGO\n\n-- NOTE If you want to play more than 10000 games, you need to extend the query generating the numbers table by adding\n-- next cross joins. Now the table contains enough values to solve the task and it takes less processing time.\n\nWITH sample100 AS (\n SELECT TOP(100) object_id\n FROM master.sys.objects\n)\nINSERT numbers\n SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS n\n FROM sample100 AS A\n CROSS JOIN sample100 AS B;\nGO\n\nCREATE TABLE dbo.drawers (drawer INT PRIMARY KEY, card INT);\nGO\n\nCREATE TABLE dbo.results (strategy VARCHAR(10), game INT, result BIT, PRIMARY KEY (game, strategy));\nGO\n\nCREATE PROCEDURE dbo.shuffleDrawers @prisonersCount INT\nAS BEGIN\n SET NOCOUNT ON;\n\n IF NOT EXISTS (SELECT * FROM drawers)\n INSERT drawers (drawer, card)\n SELECT n AS drawer, n AS card\n FROM numbers\n WHERE n <= @prisonersCount;\n\n DECLARE @randoms TABLE (n INT, random INT);\n DECLARE @n INT = 1;\n WHILE @n <= @prisonersCount BEGIN\n INSERT @randoms VALUES (@n, ROUND(RAND() * (@prisonersCount - 1), 0) + 1);\n\n SET @n = @n + 1;\n END;\n\n WITH ordered AS (\n SELECT ROW_NUMBER() OVER (ORDER BY random ASC) AS drawer,\n n AS card\n FROM @randoms\n )\n UPDATE drawers\n SET card = o.card\n FROM drawers AS s\n INNER JOIN ordered AS o\n ON o.drawer = s.drawer;\nEND\nGO\n\nCREATE PROCEDURE dbo.find @prisoner INT, @strategy VARCHAR(10)\nAS BEGIN\n -- A prisoner can open no more than 50 drawers.\n DECLARE @drawersCount INT = (SELECT COUNT(*) FROM drawers);\n DECLARE @openMax INT = @drawersCount / 2;\n\n -- Prisoners start outside the room.\n DECLARE @card INT = NULL;\n DECLARE @open INT = 1;\n WHILE @open <= @openMax BEGIN\n -- A prisoner tries to find his own number.\n IF @strategy = 'random' BEGIN\n DECLARE @random INT = ROUND(RAND() * (@drawersCount - 1), 0) + 1;\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @random);\n END\n IF @strategy = 'optimal' BEGIN\n IF @card IS NULL BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @prisoner);\n END ELSE BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @card);\n END\n END\n\n -- A prisoner finding his own number is then held apart from the others.\n IF @card = @prisoner\n RETURN 1;\n\n SET @open = @open + 1;\n END\n\n RETURN 0;\nEND\nGO\n\nCREATE PROCEDURE dbo.playGame @gamesCount INT, @strategy VARCHAR(10), @prisonersCount INT = 100\nAS BEGIN\n SET NOCOUNT ON;\n\n IF @gamesCount <> (SELECT COUNT(*) FROM results WHERE strategy = @strategy) BEGIN\n DELETE results\n WHERE strategy = @strategy;\n\n INSERT results (strategy, game, result)\n SELECT @strategy AS strategy, n AS game, 0 AS result\n FROM numbers\n WHERE n <= @gamesCount;\n END\n\n UPDATE results\n SET result = 0\n WHERE strategy = @strategy;\n\n DECLARE @game INT = 1;\n WHILE @game <= @gamesCount BEGIN\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 EXECUTE shuffleDrawers @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 DECLARE @prisoner INT = 1;\n DECLARE @found INT = 0;\n WHILE @prisoner <= @prisonersCount BEGIN\n EXECUTE @found = find @prisoner, @strategy;\n IF @found = 1\n SET @prisoner = @prisoner + 1;\n ELSE\n BREAK;\n END;\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 IF @found = 1\n UPDATE results SET result = 1 WHERE strategy = @strategy AND game = @game;\n \n SET @game = @game + 1;\n END\nEND\nGO\n\nCREATE FUNCTION dbo.computeProbability(@strategy VARCHAR(10))\nRETURNS decimal (18, 2)\nAS BEGIN\n RETURN (\n SELECT (SUM(CAST(result AS INT)) * 10000 / COUNT(*)) / 100\n FROM results\n WHERE strategy = @strategy\n );\nEND\nGO\n\n-- Simulate several thousand instances of the game:\nDECLARE @gamesCount INT = 2000;\n\n-- ...where the prisoners randomly open drawers.\nEXECUTE playGame @gamesCount, 'random';\n\n-- ...where the prisoners use the optimal strategy mentioned in the Wikipedia article.\nEXECUTE playGame @gamesCount, 'optimal';\n\n-- Show and compare the computed probabilities of success for the two strategies.\nDECLARE @log VARCHAR(max);\nSET @log = CONCAT('Games count: ', @gamesCount);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"random\" strategy: ', dbo.computeProbability('random'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"optimal\" strategy: ', dbo.computeProbability('optimal'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nGO\n\nDROP FUNCTION dbo.computeProbability;\nDROP PROCEDURE dbo.playGame;\nDROP PROCEDURE dbo.find;\nDROP PROCEDURE dbo.shuffleDrawers;\nDROP TABLE dbo.results;\nDROP TABLE dbo.drawers;\nDROP TABLE dbo.numbers;\nGO", "safe": true }, { "filename": "100 prisoners_172.txt", "content": "Games count: 2000\nProbability of success with \"random\" strategy: 0.00 \nProbability of success with \"optimal\" strategy: 31.00", "safe": true }, { "filename": "100 prisoners_173.txt", "content": "#lang transd\n\nMainModule: {\nsimRandom: (\u03bb numPris Int() nRuns Int()\n locals: nSucc 0.0\n (for n in Range(nRuns) do\n (with draws (for i in Range(numPris) project i) succ 1\n (for prisN in Range(numPris) do\n (shuffle draws)\n (if (not (is-el Range(in: draws 0 (/ numPris 2)) prisN))\n (= succ 0) break))\n (+= nSucc succ)\n ) )\n (ret (* (/ nSucc nRuns) 100))\n),\n\nsimOptimal: (\u03bb numPris Int() nRuns Int()\n locals: nSucc 0.0\n (for n in Range(nRuns) do\n (with draws (for i in Range(numPris) project i) succ 0 nextDraw 0\n (shuffle draws)\n (for prisN in Range(numPris) do (= nextDraw prisN) (= succ 0)\n (for i in Range( (/ numPris 2)) do\n (= nextDraw (get draws nextDraw))\n (if (== nextDraw prisN) (= succ 1) break))\n (if (not succ) break))\n (+= nSucc succ)\n ) )\n (ret (* (/ nSucc nRuns) 100))\n),\n\n_start: (\u03bb\n (lout prec: 4 :fixed \"Random play: \" (simRandom 100 10000) \"% of wins\")\n (lout \"Strategic play: \" (simOptimal 100 10000) \"% of wins\")\n (lout \"Check random play: \" (simRandom 10 100000) \"% of wins\")\n)\n}\n", "safe": true }, { "filename": "100 prisoners_174.txt", "content": "Random play: 0.0000% of wins\nStrategic play: 31.4500% of wins\nCheck random play: 0.1040% of wins\n", "safe": true }, { "filename": "100 prisoners_175.txt", "content": "Sub HundredPrisoners()\n\n NumberOfPrisoners = Int(InputBox(\"Number of Prisoners\", \"Prisoners\", 100))\n Tries = Int(InputBox(\"Numer of Tries\", \"Tries\", 1000))\n Selections = Int(InputBox(\"Number of Selections\", \"Selections\", NumberOfPrisoners / 2))\n\n StartTime = Timer\n\n AllFoundOptimal = 0\n AllFoundRandom = 0\n AllFoundRandomMem = 0\n\n For i = 1 To Tries\n OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections)\n RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections)\n RandomMemCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)\n \n If OptimalCount = NumberOfPrisoners Then\n AllFoundOptimal = AllFoundOptimal + 1\n End If\n If RandomCount = NumberOfPrisoners Then\n AllFoundRandom = AllFoundRandom + 1\n End If\n If RandomMemCount = NumberOfPrisoners Then\n AllFoundRandomMem = AllFoundRandomMem + 1\n End If\n Next i\n\n\n ResultString = \"Optimal: \" & AllFoundOptimal & \" of \" & Tries & \": \" & AllFoundOptimal / Tries * 100 & \"%\"\n ResultString = ResultString & Chr(13) & \"Random: \" & AllFoundRandom & \" of \" & Tries & \": \" & AllFoundRandom / Tries * 100 & \"%\"\n ResultString = ResultString & Chr(13) & \"RandomMem: \" & AllFoundRandomMem & \" of \" & Tries & \": \" & AllFoundRandomMem / Tries * 100 & \"%\"\n\n EndTime = Timer\n\n ResultString = ResultString & Chr(13) & \"Elapsed Time: \" & Round(EndTime - StartTime, 2) & \" s\"\n ResultString = ResultString & Chr(13) & \"Trials/sec: \" & Tries / Round(EndTime - StartTime, 2)\n\n MsgBox ResultString, vbOKOnly, \"Results\"\n\nEnd Sub\n\nFunction HundredPrisoners_Optimal(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n \n ReDim DrawerArray(NrPrisoners - 1)\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n For i = 1 To NrPrisoners\n NumberFromDrawer = DrawerArray(i - 1)\n For j = 1 To NrSelections - 1\n If NumberFromDrawer = i Then\n FoundOwnNumber = FoundOwnNumber + 1\n Exit For\n End If\n NumberFromDrawer = DrawerArray(NumberFromDrawer - 1)\n Next j\n Next i\n HundredPrisoners_Optimal = FoundOwnNumber\nEnd Function\n\nFunction HundredPrisoners_Random(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n ReDim DrawerArray(NrPrisoners - 1)\n \n FoundOwnNumber = 0\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n RandomDrawer = Int(NrPrisoners * Rnd)\n NumberFromDrawer = DrawerArray(RandomDrawer)\n If NumberFromDrawer = i Then\n FoundOwnNumber = FoundOwnNumber + 1\n Exit For\n End If\n Next j\n Next i\n HundredPrisoners_Random = FoundOwnNumber\nEnd Function\n\nFunction HundredPrisoners_Random_Mem(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n Dim SelectionArray() As Long\n ReDim DrawerArray(NrPrisoners - 1)\n ReDim SelectionArray(NrPrisoners - 1)\n \n HundredPrisoners_Random_Mem = 0\n FoundOwnNumberMem = 0\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n \n For Counter = LBound(SelectionArray) To UBound(SelectionArray)\n SelectionArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n For i = 1 To NrPrisoners\n FisherYates SelectionArray\n For j = 1 To NrSelections\n NumberFromDrawer = DrawerArray(SelectionArray(j - 1) - 1)\n If NumberFromDrawer = i Then\n FoundOwnNumberMem = FoundOwnNumberMem + 1\n Exit For\n End If\n Next j\n Next i\n HundredPrisoners_Random_Mem = FoundOwnNumberMem\nEnd Function\n\nSub FisherYates(ByRef InputArray() As Long)\n \n Dim Temp As Long\n Dim PosRandom As Long\n Dim Counter As Long\n Dim Upper As Long\n Dim Lower As Long\n \n Lower = LBound(InputArray)\n Upper = UBound(InputArray)\n \n Randomize\n \n For Counter = Upper To (Lower + 1) Step -1\n PosRandom = CLng(Int((Counter - Lower + 1) * Rnd + Lower))\n Temp = InputArray(Counter)\n InputArray(Counter) = InputArray(PosRandom)\n InputArray(PosRandom) = Temp\n Next Counter\n \nEnd Sub\n", "safe": true }, { "filename": "100 prisoners_176.txt", "content": "Optimal: 29090 of 100000: 29.09%\nRandom: 0 of 100000: 0%\nRandomMem: 0 of 100000: 0%\nElapsed Time: 388.41 s", "safe": true }, { "filename": "100 prisoners_177.txt", "content": "Module Module1\n\n Function PlayOptimal() As Boolean\n Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n For p = 1 To 100\n Dim success = False\n\n Dim choice = p - 1\n For i = 1 To 50\n If secrets(choice) = p - 1 Then\n success = True\n Exit For\n End If\n choice = secrets(choice)\n Next\n\n If Not success Then\n Return False\n End If\n Next\n\n Return True\n End Function\n\n Function PlayRandom() As Boolean\n Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n For p = 1 To 100\n Dim choices = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n Dim success = False\n For i = 1 To 50\n If choices(i - 1) = p Then\n success = True\n Exit For\n End If\n Next\n\n If Not success Then\n Return False\n End If\n Next\n\n Return True\n End Function\n\n Function Exec(n As UInteger, play As Func(Of Boolean))\n Dim success As UInteger = 0\n For i As UInteger = 1 To n\n If play() Then\n success += 1\n End If\n Next\n Return 100.0 * success / n\n End Function\n\n Sub Main()\n Dim N = 1_000_000\n Console.WriteLine(\"# of executions: {0}\", N)\n Console.WriteLine(\"Optimal play success rate: {0:0.00000000000}%\", Exec(N, AddressOf PlayOptimal))\n Console.WriteLine(\" Random play success rate: {0:0.00000000000}%\", Exec(N, AddressOf PlayRandom))\n End Sub\n\nEnd Module\n", "safe": true }, { "filename": "100 prisoners_178.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.12990000000%\n Random play success rate: 0.00000000000%", "safe": true }, { "filename": "100 prisoners_179.txt", "content": "option explicit\nconst npris=100\nconst ntries=50\nconst ntests=1000.\ndim drawer(100),opened(100),i\nfor i=1 to npris: drawer(i)=i:next\nshuffle drawer\nwscript.echo rf(tests(false)/ntests*100,10,\" \") &\"\u00a0% success for random\"\nwscript.echo rf(tests(true) /ntests*100,10,\" \") &\"\u00a0% success for optimal strategy\"\n\nfunction rf(v,n,s) rf=right(string(n,s)& v,n):end function \n\nsub shuffle(d) 'knut's shuffle\ndim i,j,t\nrandomize timer\nfor i=1 to npris\n j=int(rnd()*i+1)\n t=d(i):d(i)=d(j):d(j)=t\nnext\nend sub\n\nfunction tests(strat)\ndim cntp,i,j\ntests=0\nfor i=1 to ntests\n shuffle drawer\n cntp=0\n if strat then\n for j=1 to npris\n\tif not trystrat(j) then exit for\n next\n else\t\t\n for j=1 to npris\n if not tryrand(j) then exit for\n next \n end if\n if j>=npris then tests=tests+1\nnext\nend function \n\t \nfunction tryrand(pris)\n dim i,r \n\terase opened\n for i=1 to ntries\n do \n r=int(rnd*npris+1)\n loop until opened(r)=false\n opened(r)=true\n if drawer(r)= pris then tryrand=true : exit function\n next\n tryrand=false\nend function \n\nfunction trystrat(pris)\n dim i,r\n r=pris\n for i=1 to ntries\n if drawer(r)= pris then trystrat=true\t:exit function\n r=drawer(r)\n next\n trystrat=false\nend function\n", "safe": true }, { "filename": "100 prisoners_18.txt", "content": "unplanned 0.0%\nplanned 31.43%", "safe": true }, { "filename": "100 prisoners_180.txt", "content": " 0\u00a0% success for random\n 32.9\u00a0% success for optimal strategy\n", "safe": true }, { "filename": "100 prisoners_181.txt", "content": "import rand\nimport rand.seed\n// Uses 0-based numbering rather than 1-based numbering throughout.\nfn do_trials(trials int, np int, strategy string) {\n mut pardoned := 0\n for _ in 0..trials {\n mut drawers := []int{len: 100, init: it}\n rand.shuffle(mut drawers) or {panic('shuffle failed')}\n mut next_trial := false\n for p in 0..np {\n mut next_prisoner := false\n if strategy == \"optimal\" {\n mut prev := p\n for _ in 0..50 {\n this := drawers[prev]\n if this == p {\n next_prisoner = true\n break\n }\n prev = this\n }\n } else {\n // Assumes a prisoner remembers previous drawers (s)he opened\n // and chooses at random from the others.\n mut opened := [100]bool{}\n for _ in 0..50 {\n mut n := 0\n for {\n n = rand.intn(100) or {0}\n if !opened[n] {\n opened[n] = true\n break\n }\n }\n if drawers[n] == p {\n next_prisoner = true\n break\n }\n }\n }\n if !next_prisoner {\n next_trial = true\n break\n }\n }\n if !next_trial {\n pardoned++\n }\n }\n rf := f64(pardoned) / f64(trials) * 100\n println(\" strategy = ${strategy:-7} pardoned = ${pardoned:-6} relative frequency = ${rf:-5.2f}%\\n\")\n}\n \nfn main() {\n rand.seed(seed.time_seed_array(2))\n trials := 100000\n for np in [10, 100] {\n println(\"Results from $trials trials with $np prisoners:\\n\")\n for strategy in [\"random\", \"optimal\"] {\n do_trials(trials, np, strategy)\n }\n }\n}\n", "safe": true }, { "filename": "100 prisoners_182.txt", "content": "Results from 100000 trials with 10 prisoners:\n\n strategy = random pardoned = 91 relative frequency = 0.09\u00a0%\n\n strategy = optimal pardoned = 31321 relative frequency = 31.32%\n\nResults from 100000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00\u00a0%\n\n strategy = optimal pardoned = 31318 relative frequency = 31.32%\n", "safe": true }, { "filename": "100 prisoners_183.txt", "content": "import \"random\" for Random\nimport \"./fmt\" for Fmt\n\nvar rand = Random.new()\n\nvar doTrials = Fn.new{ |trials, np, strategy|\n var pardoned = 0\n for (t in 0...trials) {\n var drawers = List.filled(100, 0)\n for (i in 0..99) drawers[i] = i\n rand.shuffle(drawers)\n var nextTrial = false\n for (p in 0...np) {\n var nextPrisoner = false\n if (strategy == \"optimal\") {\n var prev = p\n for (d in 0..49) {\n var curr = drawers[prev]\n if (curr == p) {\n nextPrisoner = true\n break\n }\n prev = curr\n }\n } else {\n var opened = List.filled(100, false)\n for (d in 0..49) {\n var n\n while (true) {\n n = rand.int(100)\n if (!opened[n]) {\n opened[n] = true\n break\n }\n }\n if (drawers[n] == p) {\n nextPrisoner = true\n break\n }\n }\n }\n if (!nextPrisoner) {\n nextTrial = true\n break\n }\n }\n if (!nextTrial) pardoned = pardoned + 1\n }\n var rf = pardoned/trials * 100\n Fmt.print(\" strategy = $-7s pardoned = $,6d relative frequency = $5.2f\\%\\n\", strategy, pardoned, rf)\n}\n\nvar trials = 1e5\nfor (np in [10, 100]) {\n Fmt.print(\"Results from $,d trials with $d prisoners:\\n\", trials, np)\n for (strategy in [\"random\", \"optimal\"]) doTrials.call(trials, np, strategy)\n}\n", "safe": true }, { "filename": "100 prisoners_184.txt", "content": "Results from 100,000 trials with 10 prisoners:\n\n strategy = random pardoned = 98 relative frequency = 0.10%\n\n strategy = optimal pardoned = 31,212 relative frequency = 31.21%\n\nResults from 100,000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00%\n\n strategy = optimal pardoned = 31,139 relative frequency = 31.14%\n", "safe": true }, { "filename": "100 prisoners_185.txt", "content": "int Drawer(100);\n\nproc KShuffle; \\Randomly rearrange the cards in the drawers\n\\(Woe unto thee if Stattolo shuffle is used instead of Knuth shuffle.)\nint I, J, T;\n[for I:= 100-1 downto 1 do\n [J:= Ran(I+1); \\range [0..I]\n T:= Drawer(I); Drawer(I):= Drawer(J); Drawer(J):= T;\n ];\n];\n\nfunc Stategy2; \\Return 'true' if stragegy succeeds\nint Prisoner, Card, Try;\n[for Prisoner:= 1 to 100 do\n [Card:= Drawer(Prisoner-1);\n Try:= 1;\n loop [if Card = Prisoner then quit;\n if Try >= 50 then return false;\n Card:= Drawer(Card-1);\n Try:= Try+1;\n ];\n ];\nreturn true;\n];\n\nfunc Stategy1; \\Return 'true' if stragegy succeeds\nint Prisoner, I, D(100);\n[for Prisoner:= 1 to 100 do\n loop [for I:= 0 to 100-1 do D(I):= I+1;\n KShuffle;\n for I:= 1 to 50 do\n if Drawer(D(I-1)) = Prisoner then quit;\n return false;\n ];\nreturn true;\n];\n\nproc Strategy(S);\nint S, I, Sample;\nreal Successes;\n[Successes:= 0.;\nfor Sample:= 1 to 100_000 do\n [for I:= 0 to 100-1 do Drawer(I):= I+1;\n KShuffle;\n case S of\n 1: if Stategy1 then Successes:= Successes + 1.;\n 2: if Stategy2 then Successes:= Successes + 1.\n other [];\n ];\nRlOut(0, Successes/100_000.*100.); Text(0, \"%^m^j\");\n];\n\n[Format(3, 12);\nText(0, \"Random strategy success rate: \");\nStrategy(1);\nText(0, \"Optimal strategy success rate: \");\nStrategy(2);\n]", "safe": true }, { "filename": "100 prisoners_186.txt", "content": "Random strategy success rate: 0.000000000000%\nOptimal strategy success rate: 31.085000000000%\n", "safe": true }, { "filename": "100 prisoners_187.txt", "content": "// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners\n// by Galileo, 05/2022\n\nsub play(prisoners, iterations, optimal)\n local prisoner, pardoned, found, drawer, drawers(prisoners), i, j, k, p, x\n\n for i = 1 to prisoners\u00a0: drawers(i) = i\u00a0: next\n\n for i = 1 to iterations\n for k = 1 to prisoners\u00a0: x = ran(prisoners) + 1\u00a0: p = drawers(x)\u00a0: drawers(x) = drawers(k)\u00a0: drawers(k) = p\u00a0: next\n for prisoner = 1 to prisoners\n found = false\n if optimal then drawer = prisoner else drawer = ran(prisoners) + 1 end if\n for j = 1 to prisoners / 2\n drawer = drawers(drawer)\n if drawer = prisoner found = true\u00a0: break\n if not optimal drawer = ran(prisoners) + 1\n next\n if not found break\n next\n pardoned = pardoned + found\n next\n\n return 100 * pardoned / iterations\nend sub\n \niterations = 10000\nprint \"Simulation count: \", iterations\nfor prisoners = 10 to 100 step 90\n random = play(prisoners, iterations, false)\n optimal = play(prisoners, iterations, true)\n print \"Prisoners: \", prisoners, \", random: \", random, \", optimal: \", optimal\nnext", "safe": true }, { "filename": "100 prisoners_188.txt", "content": "Simulation count: 10000\nPrisoners: 10, random: 0.01, optimal: 35.83\nPrisoners: 100, random: 0, optimal: 31.2\n---Program done, press RETURN---", "safe": true }, { "filename": "100 prisoners_189.txt", "content": "!yamlscript/v0\n\ndefn main(n=5000):\n :: https://rosettacode.org/wiki/100_prisoners\n\n random-successes optimal-successes run-count =:\n simulate-n-runs(n)\n .slice(q(random-successes optimal-successes run-count))\n\n say: \"Probability of survival with random search: $F(random-successes / run-count)\"\n\n say: \"Probability of survival with ordered search: $F(optimal-successes / run-count)\"\n\ndefn simulate-n-runs(n):\n :: Simulate n runs of the 100 prisoner problem and returns a success count\n for each search method.\n\n loop random-successes 0, optimal-successes 0, run-count 0:\n # If we've done the loop n times\n if n == run-count:\n # return results\n then::\n random-successes \u00a0:: random-successes\n optimal-successes\u00a0:: optimal-successes\n run-count \u00a0:: run-count\n\n # Otherwise, run for another batch of prisoners\n else:\n next-result =: simulate-100-prisoners()\n recur:\n (random-successes + next-result.random)\n (optimal-successes + next-result.optimal)\n run-count.++\n\ndefn simulate-100-prisoners():\n :: Simulates all prisoners searching the same drawers by both strategies,\n returns map showing whether each was successful.\n\n # Create 100 drawers with randomly ordered prisoner numbers:\n drawers =: random-drawers()\n hash-map:\n :random try-luck(drawers search-50-random-drawers)\n :optimal try-luck(drawers search-50-optimal-drawers)\n\ndefn try-luck(drawers drawer-searching-function):\n :: Returns 1 if all prisoners find their number otherwise 0.\n\n loop prisoners range(100):\n if prisoners.?:\n if prisoners.0.drawer-searching-function(drawers):\n recur: rest(prisoners)\n else: 0\n else: 1\n\ndefn search-50-optimal-drawers(prisoner-number drawers):\n :: Open 50 drawers according to the agreed strategy, returning true if\n prisoner's number was found.\n\n loop next-drawer prisoner-number, drawers-opened 0:\n when drawers-opened\u00a0!= 50:\n result =: drawers.$next-drawer\n result == prisoner-number ||:\n recur: result drawers-opened.++\n\ndefn search-50-random-drawers(prisoner-number drawers):\n :: Select 50 random drawers and return true if the prisoner's number was\n found.\n\n drawers:\n .shuffle()\n .take(50)\n .filter(eq(prisoner-number))\n .count()\n .eq(1)\n\ndefn random-drawers():\n :: Returns a list of shuffled numbers.\n\n shuffle: range(100)\n", "safe": true }, { "filename": "100 prisoners_19.txt", "content": "NumOfTrials := 20000\nrandomFailTotal := 0, strategyFailTotal := 0\nprisoners := [], drawers := [], Cards := []\nloop, 100\n\tprisoners[A_Index] := A_Index\t\t\t\t; create prisoners\n\t, drawers[A_Index] := true\t\t\t\t; create drawers\n\nloop, % NumOfTrials\n{\n\tloop, 100\n\t\tCards[A_Index] := A_Index\t\t\t; create cards for this iteration\n\tloop, 100\n\t{\n\t\tRandom, rnd, 1, Cards.count()\n\t\tdrawers[A_Index] := Cards.RemoveAt(rnd)\t\t; randomly place cards in drawers\n\t}\n\t;-------------------------------------------\n\t; randomly open drawers\n\tRandomList := []\n\tloop, 100\n\t\tRandomList[A_Index] := A_Index\n\tFail := false\n\twhile (A_Index <=100) && !Fail\n\t{\n\t\tthisPrisoner := A_Index\n\t\tres := \"\"\n\t\twhile (thisCard <> thisPrisoner) && !Fail\n\t\t{\n\t\t\tRandom, rnd, 1, % RandomList.Count()\t; choose random number\n\t\t\tNextDrawer := RandomList.RemoveAt(rnd)\t; remove drawer from random list (don't choose more than once)\n\t\t\tthisCard := drawers[NextDrawer]\t\t; get card from this drawer\n\t\t\tif (A_Index > 50)\n\t\t\t\tFail := true\n\t\t}\n\t\tif Fail\n\t\t\trandomFailTotal++\n\t}\n\t;-------------------------------------------\n\t; use optimal strategy\n\tFail := false\n\twhile (A_Index <=100) && !Fail\n\t{\n\t\tcounter := 1, thisPrisoner := A_Index\n\t\tNextDrawer := drawers[thisPrisoner]\t\t; 1st trial, drawer whose outside number is prisoner number\n\t\twhile (drawers[NextDrawer] <> thisPrisoner) && !Fail\n\t\t{\t\n\t\t\tNextDrawer := drawers[NextDrawer]\t; drawer with the same number as that of the revealed card\n\t\t\tif ++counter > 50\n\t\t\t\tFail := true\n\t\t}\n\t\tif Fail\n\t\t\tstrategyFailTotal++\n\t}\n}\nMsgBox % \"Number Of Trials = \" NumOfTrials\n\t\t. \"`nOptimal Strategy:`t\" (1 - strategyFailTotal/NumOfTrials) *100 \"\u00a0% success rate\" \n\t\t. \"`nRandom Trials:`t\" (1 - randomFailTotal/NumOfTrials) *100 \"\u00a0% success rate\"\n", "safe": true }, { "filename": "100 prisoners_190.txt", "content": "const std = @import(\"std\");\n\npub const Cupboard = struct {\n comptime {\n std.debug.assert(u7 == std.math.IntFittingRange(0, 100));\n }\n\n pub const Drawer = packed struct(u8) {\n already_visited: bool,\n card: u7,\n };\n\n drawers: [100]Drawer,\n randomizer: std.rand.Random,\n\n /// Cupboard is not shuffled after initialization,\n /// it is shuffled during `play` execution.\n pub fn init(random: std.rand.Random) Cupboard {\n var drawers: [100]Drawer = undefined;\n for (&drawers, 0..) |*drawer, i| {\n drawer.* = .{\n .already_visited = false,\n .card = @intCast(i),\n };\n }\n\n return .{\n .drawers = drawers,\n .randomizer = random,\n };\n }\n\n pub const Decision = enum {\n pardoned,\n sentenced,\n };\n\n pub const Strategy = enum {\n follow_card,\n random,\n\n pub fn decisionOfPrisoner(strategy: Strategy, cupboard: *Cupboard, prisoner_id: u7) Decision {\n switch (strategy) {\n .random => {\n return for (0..50) |_| {\n // If randomly chosen drawer was already opened,\n // throw dice again.\n const drawer = try_throw_random: while (true) {\n const random_i = cupboard.randomizer.uintLessThan(u7, 100);\n const drawer = &cupboard.drawers[random_i];\n\n if (!drawer.already_visited)\n break :try_throw_random drawer;\n };\n std.debug.assert(!drawer.already_visited);\n defer drawer.already_visited = true;\n\n if (drawer.card == prisoner_id)\n break .pardoned;\n } else .sentenced;\n },\n .follow_card => {\n var drawer_i = prisoner_id;\n return for (0..50) |_| {\n const drawer = &cupboard.drawers[drawer_i];\n std.debug.assert(!drawer.already_visited);\n defer drawer.already_visited = true;\n\n if (drawer.card == prisoner_id)\n break .pardoned\n else\n drawer_i = drawer.card;\n } else .sentenced;\n },\n }\n }\n };\n\n pub fn play(cupboard: *Cupboard, strategy: Strategy) Decision {\n cupboard.randomizer.shuffleWithIndex(Drawer, &cupboard.drawers, u7);\n\n // Decisions for all 100 prisoners.\n var all_decisions: [100]Decision = undefined;\n for (&all_decisions, 0..) |*current_decision, prisoner_id| {\n // Make decision for current prisoner\n current_decision.* = strategy.decisionOfPrisoner(cupboard, @intCast(prisoner_id));\n\n // Close all drawers after one step.\n for (&cupboard.drawers) |*drawer|\n drawer.already_visited = false;\n }\n\n // If there is at least one sentenced person, everyone are sentenced.\n return for (all_decisions) |decision| {\n if (decision == .sentenced)\n break .sentenced;\n } else .pardoned;\n }\n\n pub fn runSimulation(cupboard: *Cupboard, strategy: Cupboard.Strategy, total: u32) void {\n var success: u32 = 0;\n for (0..total) |_| {\n const result = cupboard.play(strategy);\n if (result == .pardoned) success += 1;\n }\n\n const ratio = @as(f32, @floatFromInt(success)) / @as(f32, @floatFromInt(total));\n\n const stdout = std.io.getStdOut();\n const stdout_w = stdout.writer();\n\n stdout_w.print(\n \\\\\n \\\\Strategy: {s}\n \\\\Total runs: {d}\n \\\\Successful runs: {d}\n \\\\Failed runs: {d}\n \\\\Success rate: {d:.4}%.\n \\\\\n , .{\n @tagName(strategy),\n total,\n success,\n total - success,\n ratio * 100.0,\n }) catch {}; // Do nothing on error\n }\n};\n", "safe": true }, { "filename": "100 prisoners_191.txt", "content": "const std = @import(\"std\");\n\npub fn main() std.os.GetRandomError!void {\n var prnd = std.rand.DefaultPrng.init(seed: {\n var init_seed: u64 = undefined;\n try std.os.getrandom(std.mem.asBytes(&init_seed));\n break :seed init_seed;\n });\n const random = prnd.random();\n\n var cupboard = Cupboard.init(random);\n\n cupboard.runSimulation(.follow_card, 10_000);\n cupboard.runSimulation(.random, 10_000);\n}\n", "safe": true }, { "filename": "100 prisoners_192.txt", "content": "\n\nStrategy: follow_card\nTotal runs: 10000\nSuccessful runs: 3049\nFailed runs: 6951\nSuccess rate: 30.4900%.\n\nStrategy: random\nTotal runs: 10000\nSuccessful runs: 0\nFailed runs: 10000\nSuccess rate: 0.0000%.\n\n", "safe": true }, { "filename": "100 prisoners_193.txt", "content": "const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000;\nfcn oneHundredJDI{\t// just do it strategy\n cupboard,picks\u00a0:= [0..SLOTS-1].walk().shuffle(), cupboard.copy();\n // if this prisoner can't find their number in TRIES, all fail\n foreach p in (PRISONERS){ if(picks.shuffle().find(p)>=TRIES) return(False); }\n True\t\t// all found their number\n}\nfcn oneHundredO{\t// Optimal strategy\n cupboard\u00a0:= [0..SLOTS-1].walk().shuffle();\n foreach p in (PRISONERS){\n d:=p;\n do(TRIES){ if((d=cupboard[d]) == p) continue(2) } // found my number\n return(False); // this prisoner failed to find their number, all fail\n }\n True\t\t// all found their number\n}", "safe": true }, { "filename": "100 prisoners_194.txt", "content": "s:=N.pump(Ref(0).incN,oneHundredJDI).value.toFloat()/N*100;\nprintln(\"Just do it strategy (%,d simulatations):\u00a0%.2f%%\".fmt(N,s));\n\ns:=N.pump(Ref(0).incN,oneHundredO).value.toFloat()/N*100;\nprintln(\"Optimal strategy (%,d simulatations):\u00a0%.2f%%\".fmt(N,s));", "safe": true }, { "filename": "100 prisoners_195.txt", "content": "Just do it strategy (10,000 simulatations): 0.00%\nOptimal strategy (10,000 simulatations): 31.16%\n", "safe": true }, { "filename": "100 prisoners_196.txt", "content": "const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;", "safe": true }, { "filename": "100 prisoners_197.txt", "content": "Just do it strategy (100,000 simulatations): 0.09%\nOptimal strategy (100,000 simulatations): 31.13%\n", "safe": true }, { "filename": "100 prisoners_2.txt", "content": " Simulation count: 100000\n Random play wins: 0.0% of simulations\nOptimal play wins: 31.1% of simulations\n", "safe": true }, { "filename": "100 prisoners_20.txt", "content": "Number Of Trials = 20000\nOptimal Strategy:\t33.275000\u00a0% success rate\nRandom Trials \u00a0:\t0.000000\u00a0% success rate", "safe": true }, { "filename": "100 prisoners_21.txt", "content": "O = 50\nN = 2*O\niterations = 10000\n\nREM From the numbers 0 to N-1 inclusive, pick O of them.\nfunction shuffle(N, O)\n dim array(N)\n for i = 0 to N-1\n array[i] = i\n next i\n for i = 0 to O-1\n swapindex = i + rand*(N-i)\n swapvalue = array[swapindex]\n array[swapindex] = array[i]\n array[i] = swapvalue\n next i\n return array\nend function\n\nREM given N drawers with O to open, prisoner P chooses randomly: does he choose well?\nfunction chooserandom(drawers, N, O, p)\n choices = shuffle(N, O)\n for i = 0 to O-1\n if drawers[choices[i]] = p then return true\n next i\n return false\nend function\n\nREM N prisoners randomly choose O drawers to open: do they all choose well?\nfunction allchooserandom(N, O)\n drawers = shuffle(N, N)\n for p = 0 to N-1\n goodchoice = chooserandom(drawers, N, O, p)\n if not goodchoice then return false\n next p\n return true\nend function\n\nREM given N drawers with O to open, prisoner P chooses smartly: does he choose well?\nfunction choosesmart(drawers, N, O, p)\n numopened = 0\n i = p\n while numopened < O\n numopened += 1\n if drawers[i] = p then return true\n i = drawers[i]\n end while\n return false\nend function\n\nREM N prisoners smartly choose O drawers to open: do they all choose well?\nfunction allchoosesmart(N, O)\n drawers = shuffle(N, N)\n for p = 0 to N-1\n goodchoice = choosesmart(drawers, N, O, p)\n if not goodchoice then return false\n next p\n return true\nend function\n\ncls\nprint N; \" prisoners choosing \";O;\" drawers, \";iterations;\" iterations:\"\n\ntotal = 0\nfor iteration = 1 to iterations\n if allchooserandom(N, O) then total += 1\nnext iteration\n\nprint \"Random choices: \"; total;\" out of \";iterations\nprint \"Observed ratio: \"; total/iterations; \", expected ratio: \"; (O/N)^N\n\ntotal = 0\nfor iteration = 1 to iterations\n if allchoosesmart(N, O) then total += 1\nnext iteration\n\nprint \"Smart choices: \"; total;\" out of \";iterations\nprint \"Observed ratio: \"; total/iterations; \", expected ratio with N=2*O: greater than about 0.30685\": REM for N=100, O=50 particularly, about 0.3118", "safe": true }, { "filename": "100 prisoners_22.txt", "content": "100 prisoners choosing 50 drawers, 10000 iterations:\nRandom choices: 0 out of 10000\nObserved ratio: 0.0, expected ratio: 0.0\nSmart choices: 3052 out of 10000\nObserved ratio: 0.3052, expected ratio with N=2*O: greater than about 0.30685\n", "safe": true }, { "filename": "100 prisoners_23.txt", "content": "FUNCTION trials(prisoners, iterations, optimal)\n DIM drawers(100)\n FOR i = 1 TO prisoners\n LET drawers(i) = i\n NEXT i\n FOR i = 1 TO iterations\n FOR k = 1 TO prisoners\n LET x = RND+1\n LET p = drawers(x)\n LET drawers(x) = drawers(k)\n LET drawers(k) = p\n NEXT k\n FOR prisoner = 1 TO prisoners\n LET found = false\n IF optimal<>0 THEN LET drawer = prisoner ELSE LET drawer = RND+1\n FOR j = 1 TO prisoners/2\n LET drawer = drawers(drawer)\n IF drawer = prisoner THEN\n LET found = true\n EXIT FOR\n END IF\n IF (NOT optimal<>0) THEN LET drawer = RND+1\n NEXT j\n IF (NOT found<>0) THEN EXIT FOR\n NEXT prisoner\n LET pardoned = pardoned+found\n NEXT i\n LET trials = (100*pardoned/iterations)\nEND FUNCTION\n\nLET false = 0\nLET true = 1\nLET iterations = 10000\nPRINT \"Simulation count: \"; iterations\nFOR prisoners = 10 TO 100 STEP 90\n LET randon = trials(prisoners,iterations,false)\n LET optimal = trials(prisoners,iterations,true)\n PRINT \"Prisoners: \"; prisoners; \", random: \"; randon; \", optimal: \"; optimal\nNEXT prisoners\nEND\n", "safe": true }, { "filename": "100 prisoners_24.txt", "content": "get \"libhdr\"\n\nmanifest $( \n seed = 12345 // for pseudorandom number generator\n size = 100 // amount of drawers and prisoners\n tries = 50 // amount of tries each prisoner may make\n simul = 2000 // amount of simulations to run\n$)\n\nlet randto(n) = valof\n$( static $( state = seed $)\n let mask = 1\n mask\u00a0:= (mask<<1)|1 repeatuntil mask > n\n state\u00a0:= random(state) repeatuntil ((state >> 8) & mask) < n \n resultis (state >> 8) & mask\n$)\n\n// initialize drawers\nlet placeCards(d, n) be\n$( for i=0 to n-1 do d!i\u00a0:= i;\n for i=0 to n-2 do\n $( let j = i+randto(n-i)\n let k = d!i\n d!i\u00a0:= d!j\n d!j\u00a0:= k\n $)\n$)\n\n// random strategy (prisoner 'p' tries to find his own number)\nlet randoms(d, p, t) = valof\n$( for n = 1 to t do\n if d!randto(size) = p then resultis true\n resultis false \n$)\n\n// optimal strategy\nlet optimal(d, p, t) = valof\n$( let last = p\n for n = 1 to t do\n test d!last = p \n then resultis true\n else last\u00a0:= d!last\n resultis false\n$)\n\n// run a simulation given a strategy\nlet simulate(d, strat, n, t) = valof\n$( placeCards(d, n)\n for p = 0 to n-1 do\n if not strat(d, p, t) then resultis false\n resultis true\n$)\n\n// run many simulations and count the successes\nlet runSimulations(d, strat, n, amt, t) = valof\n$( let succ = 0\n for i = 1 to amt do\n if simulate(d, strat, n, t) do\n succ\u00a0:= succ + 1\n resultis succ\n$)\n\nlet run(d, name, strat, n, amt, t) be\n$( let s = runSimulations(d, strat, n, amt, t);\n writef(\"%S: %I5 of %I5, %N percent.*N\", name, s, amt, s*10/(amt/10))\n$)\n\nlet start() be\n$( let d = vec size-1\n run(d, \" Random\", randoms, size, simul, tries)\n run(d, \"Optimal\", optimal, size, simul, tries)\n$)", "safe": true }, { "filename": "100 prisoners_25.txt", "content": " Random: 0 of 2000, 0 percent.\nOptimal: 698 of 2000, 34 percent.", "safe": true }, { "filename": "100 prisoners_26.txt", "content": "#include\n#include\n#include\n#include\n\n#define LIBERTY false\n#define DEATH true\n\ntypedef struct{\n\tint cardNum;\n\tbool hasBeenOpened;\n}drawer;\n\ndrawer *drawerSet;\n\nvoid initialize(int prisoners){\n\tint i,j,card;\n\tbool unique;\n\n\tdrawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -1;\n\n\tcard = rand()%prisoners + 1;\n\tdrawerSet[1] = (drawer){.cardNum = card, .hasBeenOpened = false};\n\n\tfor(i=1 + 1;i \",argv[0]);\n\n\tprisoners = atoi(argv[1]);\n\tchances = atoi(argv[2]);\n\ttrials = strtoull(argv[3],&end,10);\n\n\tsrand(time(NULL));\n\n\tprintf(\"Running random trials...\");\n\tfor(i=0;i Guid.NewGuid()).ToList();\n\n for (int p = 0; p < 100; p++) {\n bool success = false;\n\n var choice = p;\n for (int i = 0; i < 50; i++) {\n if (secrets[choice] == p) {\n success = true;\n break;\n }\n choice = secrets[choice];\n }\n\n if (!success) {\n return false;\n }\n }\n\n return true;\n }\n\n static bool PlayRandom() {\n var secrets = Enumerable.Range(0, 100).OrderBy(a => Guid.NewGuid()).ToList();\n\n for (int p = 0; p < 100; p++) {\n var choices = Enumerable.Range(0, 100).OrderBy(a => Guid.NewGuid()).ToList();\n\n bool success = false;\n for (int i = 0; i < 50; i++) {\n if (choices[i] == p) {\n success = true;\n break;\n }\n }\n\n if (!success) {\n return false;\n }\n }\n\n return true;\n }\n\n static double Exec(uint n, Func play) {\n uint success = 0;\n for (uint i = 0; i < n; i++) {\n if (play()) {\n success++;\n }\n }\n return 100.0 * success / n;\n }\n\n static void Main() {\n const uint N = 1_000_000;\n Console.WriteLine(\"# of executions: {0}\", N);\n Console.WriteLine(\"Optimal play success rate: {0:0.00000000000}%\", Exec(N, PlayOptimal));\n Console.WriteLine(\" Random play success rate: {0:0.00000000000}%\", Exec(N, PlayRandom));\n }\n }\n}\n", "safe": true }, { "filename": "100 prisoners_29.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.21310000000%\n Random play success rate: 0.00000000000%", "safe": true }, { "filename": "100 prisoners_3.txt", "content": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program prisonniex64.s */ \n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBDOORS, 100\n.equ NBLOOP, 1000\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"Random strategie \u00a0: @ sur 1000 \\n\"\nsMessResultOPT: .asciz \"Optimal strategie\u00a0: @ sur 1000 \\n\"\nszCarriageReturn: .asciz \"\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\ntbDoors: .skip 8 * NBDOORS \ntbTest: .skip 8 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: // entry of program \n \n ldr x1,qAdrtbDoors\n mov x2,#0\n1: // loop init doors table\n add x3,x2,#1\n str x3,[x1,x2,lsl #3]\n add x2,x2,#1\n cmp x2,#NBDOORS\n blt 1b\n \n mov x9,#0 // loop counter\n mov x10,#0 // counter successes random strategie\n mov x11,#0 // counter successes optimal strategie\n2:\n ldr x0,qAdrtbDoors\n mov x1,#NBDOORS\n bl knuthShuffle\n \n ldr x0,qAdrtbDoors\n bl aleaStrategie\n cmp x0,#NBDOORS\n cinc x10,x10,eq\n \n ldr x0,qAdrtbDoors\n bl optimaStrategie\n cmp x0,#NBDOORS\n cinc x11,x11,eq\n \n add x9,x9,#1\n cmp x9,#NBLOOP\n blt 2b\n \n mov x0,x10 // result display\n ldr x1,qAdrsZoneConv\n bl conversion10 // call decimal conversion\n ldr x0,qAdrsMessResult\n ldr x1,qAdrsZoneConv // insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n mov x0,x11 // result display\n ldr x1,qAdrsZoneConv\n bl conversion10 // call decimal conversion\n ldr x0,qAdrsMessResultOPT\n ldr x1,qAdrsZoneConv // insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n100: // standard end of the program \n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n \nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsMessResult: .quad sMessResult\nqAdrsMessResultOPT: .quad sMessResultOPT\nqAdrtbDoors: .quad tbDoors\nqAdrtbTest: .quad tbTest\nqAdrsZoneConv: .quad sZoneConv\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* x0 contains the address of table */\naleaStrategie:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n stp x6,x7,[sp,-16]! // save registres\n stp x8,x9,[sp,-16]! // save registres\n ldr x6,qAdrtbTest // table doors tests address\n mov x8,x0 // save table doors address\n mov x4,#0 // counter number of successes\n mov x2,#0 // prisonners indice\n1:\n bl razTable // zero to table doors tests\n mov x5,#0 // counter of door tests \n add x7,x2,#1\n2:\n mov x0,#1\n mov x1,#NBDOORS\n bl extRandom // random test\n ldr x3,[x6,x0,lsl #3] // doors also tested\u00a0?\n cmp x3,#0 \n bne 2b // yes\n ldr x3,[x8,x0,lsl #3] // load N\u00b0 door\n cmp x3,x7 // compar N\u00b0 door N\u00b0 prisonner\n cinc x4,x4,eq\n beq 3f\n mov x3,#1 // top test table item \n str x3,[x6,x0,lsl #3]\n add x5,x5,#1\n cmp x5,#NBDOORS / 2 // number tests maxi\u00a0?\n blt 2b // no -> loop\n3:\n add x2,x2,#1 // other prisonner\n cmp x2,#NBDOORS\n blt 1b\n \n mov x0,x4 // return number of successes \n100:\n ldp x8,x9,[sp],16 // restaur des 2 registres\n ldp x6,x7,[sp],16 // restaur des 2 registres\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* raz test table */ \n/******************************************************************/\nrazTable:\n stp x0,lr,[sp,-16]! // save registres\n stp x1,x2,[sp,-16]! // save registres\n ldr x0,qAdrtbTest\n mov x1,#0 // item indice\n mov x2,#0\n1:\n str x2,[x0,x1,lsl #3] // store zero \u00e0 item\n add x1,x1,#1\n cmp x1,#NBDOORS\n blt 1b\n100:\n ldp x1,x2,[sp],16 // restaur des 2 registres\n ldp x0,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* x0 contains the address of table */\noptimaStrategie:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n mov x4,#0 // counter number of successes\n mov x2,#0 // counter prisonner\n1:\n mov x5,#0 // counter test\n mov x1,x2 // first test = N\u00b0 prisonner\n2:\n ldr x3,[x0,x1,lsl #3] // load N\u00b0 door\n cmp x3,x2\n cinc x4,x4,eq // equal -> succes\n beq 3f\n mov x1,x3 // new test with N\u00b0 door\n add x5,x5,#1 \n cmp x5,#NBDOORS / 2 // test number maxi\u00a0?\n blt 2b\n3:\n add x2,x2,#1 // other prisonner\n cmp x2,#NBDOORS\n blt 1b\n \n mov x0,x4\n100:\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* knuth Shuffle */ \n/******************************************************************/\n/* x0 contains the address of table */\n/* x1 contains the number of elements */\nknuthShuffle:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n stp x6,x7,[sp,-16]! // save registers\n mov x5,x0 // save table address\n mov x6,x1 // save number of elements\n mov x2,0 // start index\n1:\n mov x0,0\n mov x1,x2 // generate aleas\n bl extRandom\n ldr x3,[x5,x2,lsl #3] // swap number on the table\n ldr x4,[x5,x0,lsl #3]\n str x4,[x5,x2,lsl #3]\n str x3,[x5,x0,lsl #3]\n add x2,x2,#1 // next number\n cmp x2,x6 // end\u00a0?\n blt 1b // no -> loop\n100:\n ldp x6,x7,[sp],16 // restaur des 2 registres\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n\n/******************************************************************/\n/* random number */ \n/******************************************************************/\n/* x0 contains inferior value */\n/* x1 contains maxi value */\n/* x0 return random number */\nextRandom:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x8,[sp,-16]! // save registers\n stp x3,x4,[sp,-16]! // save registers\n stp x19,x20,[sp,-16]! // save registers\n sub sp,sp,16 // reserve 16 octets on stack\n mov x19,x0\n add x20,x1,1\n mov x0,sp // store result on stack\n mov x1,8 // length 8 bytes\n mov x2,0\n mov x8,278 // call system Linux 64 bits Urandom\n svc 0\n mov x0,sp // load r\u00e9sult on stack\n ldr x0,[x0]\n sub x2,x20,x19 // calculation of the range of values \n udiv x1,x0,x2 // calculation range modulo\n msub x0,x1,x2,x0\n add x0,x0,x19 // and add inferior value\n100:\n add sp,sp,16 // alignement stack \n ldp x19,x20,[sp],16 // restaur 2 registers\n ldp x3,x4,[sp],16 // restaur 2 registers\n ldp x2,x8,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"", "safe": true }, { "filename": "100 prisoners_30.txt", "content": "#include // for rand\n#include // for random_shuffle\n#include // for output\n\nusing namespace std;\n\nclass cupboard {\npublic:\n cupboard() {\n for (int i = 0; i < 100; i++)\n drawers[i] = i;\n random_shuffle(drawers, drawers + 100);\n }\n\n bool playRandom();\n bool playOptimal();\n\nprivate:\n int drawers[100];\n};\n\nbool cupboard::playRandom() {\n bool openedDrawers[100] = { 0 };\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { // loops through prisoners numbered 0 through 99\n bool prisonerSuccess = false;\n for (int i = 0; i < 100 / 2; i++) { // loops through 50 draws for each prisoner\n int drawerNum = rand() % 100;\n if (!openedDrawers[drawerNum]) {\n openedDrawers[drawerNum] = true;\n break;\n }\n if (drawers[drawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n }\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\nbool cupboard::playOptimal() {\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) {\n bool prisonerSuccess = false;\n int checkDrawerNum = prisonerNum;\n for (int i = 0; i < 100 / 2; i++) {\n if (drawers[checkDrawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n } else\n checkDrawerNum = drawers[checkDrawerNum];\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\ndouble simulate(char strategy) {\n int numberOfSuccesses = 0;\n for (int i = 0; i < 10000; i++) {\n cupboard d;\n if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) // will run playRandom or playOptimal but not both because of short-circuit evaluation\n numberOfSuccesses++;\n }\n\n return numberOfSuccesses * 100.0 / 10000;\n}\n\nint main() {\n cout << \"Random strategy: \" << simulate('R') << \"\u00a0%\" << endl;\n cout << \"Optimal strategy: \" << simulate('O') << \"\u00a0%\" << endl;\n system(\"PAUSE\"); // for Windows\n return 0;\n}\n", "safe": true }, { "filename": "100 prisoners_31.txt", "content": "Random strategy: 0\u00a0%\nOptimal strategy: 31.54\u00a0%", "safe": true }, { "filename": "100 prisoners_32.txt", "content": "(ns clojure-sandbox.prisoners)\n\n(defn random-drawers []\n \"Returns a list of shuffled numbers\"\n (-> 100\n range\n shuffle))\n\n(defn search-50-random-drawers [prisoner-number drawers]\n \"Select 50 random drawers and return true if the prisoner's number was found\"\n (->> drawers\n shuffle ;; Put drawer contents in random order\n (take 50) ;; Select first 50, equivalent to selecting 50 random drawers\n (filter (fn [x] (= x prisoner-number))) ;; Filter to include only those that match prisoner number\n count\n (= 1))) ;; Returns true if the number of matching numbers is 1\n\n(defn search-50-optimal-drawers [prisoner-number drawers]\n \"Open 50 drawers according to the agreed strategy, returning true if prisoner's number was found\"\n (loop [next-drawer prisoner-number ;; The drawer index to start on is the prisoner's number\n drawers-opened 0] ;; To keep track of how many have been opened as 50 is the maximum\n (if (= drawers-opened 50)\n false ;; If 50 drawers have been opened, the prisoner's number has not been found\n (let [result (nth drawers next-drawer)] ;; Open the drawer given by next number\n (if (= result prisoner-number) ;; If prisoner number has been found\n true ;; No need to keep opening drawers - return true\n (recur result (inc drawers-opened))))))) ;; Restart the loop using the resulting number as the drawer number\n\n(defn try-luck [drawers drawer-searching-function]\n \"Returns 1 if all prisoners find their number otherwise 0\"\n (loop [prisoners (range 100)] ;; Start with 100 prisoners\n (if (empty? prisoners) ;; If they've all gone and found their number\n 1 ;; Return true- they'll all live\n (let [res (-> prisoners\n first\n (drawer-searching-function drawers))] ;; Otherwise, have the first prisoner open drawers according to the specified method\n (if (false? res) ;; If this prisoner didn't find their number\n 0 ;; no prisoners will be freed so we can return false and stop\n (recur (rest prisoners))))))) ;; Otherwise they've found the number, so we remove them from the queue and repeat with the others\n\n(defn simulate-100-prisoners []\n \"Simulates all prisoners searching the same drawers by both strategies, returns map showing whether each was successful\"\n (let [drawers (random-drawers)] ;; Create 100 drawers with randomly ordered prisoner numbers\n {:random (try-luck drawers search-50-random-drawers) ;; True if all prisoners found their number using random strategy\n :optimal (try-luck drawers search-50-optimal-drawers)})) ;; True if all prisoners found their number using optimal strategy\n\n(defn simulate-n-runs [n]\n \"Simulate n runs of the 100 prisoner problem and returns a success count for each search method\"\n (loop [random-successes 0\n optimal-successes 0\n run-count 0]\n (if (= n run-count) ;; If we've done the loop n times\n {:random-successes random-successes ;; return results\n :optimal-successes optimal-successes\n :run-count run-count}\n (let [next-result (simulate-100-prisoners)] ;; Otherwise, run for another batch of prisoners\n (recur (+ random-successes (:random next-result)) ;; Add result of run to the total successs count\n (+ optimal-successes (:optimal next-result))\n (inc run-count)))))) ;; increment run count and run again\n\n(defn -main [& args]\n \"For 5000 runs, print out the success frequency for both search methods\"\n (let [{:keys [random-successes optimal-successes run-count]} (simulate-n-runs 5000)]\n (println (str \"Probability of survival with random search: \" (float (/ random-successes run-count))))\n (println (str \"Probability of survival with ordered search: \" (float (/ optimal-successes run-count))))))\n", "safe": true }, { "filename": "100 prisoners_33.txt", "content": "Probability of survival with random search: 0.0\nProbability of survival with ordered search: 0.3062\n", "safe": true }, { "filename": "100 prisoners_34.txt", "content": "% This program needs to be merged with PCLU's \"misc\" library\n% to use the random number generator.\n%\n% pclu -merge $CLUHOME/lib/misc.lib -compile prisoners.clu\n\n% Seed the random number generator with the current time\ninit_rng = proc ()\n d: date\u00a0:= now()\n seed: int\u00a0:= ((d.hour*60) + d.minute)*60 + d.second\n random$seed(seed)\nend init_rng\n\n% Place cards in drawers randomly\nmake_drawers = proc (n: int) returns (sequence[int])\n d: array[int]\u00a0:= array[int]$predict(1,n)\n \n \u00a0% place each card in its own drawer\n for i: int in int$from_to(1,n) do\n array[int]$addh(d,i)\n end\n \n \u00a0% shuffle the cards\n for i: int in int$from_to_by(n,2,-1) do\n j: int\u00a0:= random$next(i)+1\n t: int\u00a0:= d[i]\n d[i]\u00a0:= d[j]\n d[j]\u00a0:= t\n end\n return(sequence[int]$a2s(d))\nend make_drawers\n\n% Random strategy\nrand_strat = proc (p, tries: int, d: sequence[int]) returns (bool)\n n: int\u00a0:= sequence[int]$size(d)\n for i: int in int$from_to(1,tries) do\n if p = d[random$next(n)+1] then return(true) end\n end\n return(false)\nend rand_strat\n\n% Optimal strategy\nopt_strat = proc (p, tries: int, d: sequence[int]) returns (bool)\n last: int\u00a0:= p\n for i: int in int$from_to(1,tries) do\n if d[last]=p then return(true) end\n last\u00a0:= d[last]\n end\n return(false)\nend opt_strat\n\n% Run one simulation given a strategy\nsimulate = proc (n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n returns (bool)\n d: sequence[int]\u00a0:= make_drawers(n)\n for p: int in int$from_to(1,n) do\n \u00a0% If one prisoner fails, they all hang\n if ~strat(p,tries,d) then return(false) end\n end\n return(true)\nend simulate\n\n% Run many simulations and count the successes\nrun_simulations = proc (amount, n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n returns (int)\n ok: int\u00a0:= 0\n for i: int in int$from_to(1,amount) do\n if simulate(n,tries,strat) then\n ok\u00a0:= ok + 1\n end\n end\n return(ok)\nend run_simulations\n\n% Run simulations and show the results\nshow = proc (title: string,\n amount, n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n po: stream\u00a0:= stream$primary_output()\n stream$puts(po, title || \": \")\n \n ok: int\u00a0:= run_simulations(amount, n, tries, strat)\n perc: real\u00a0:= real$i2r(ok)*100.0/real$i2r(amount)\n \n stream$putright(po, int$unparse(ok), 7)\n stream$puts(po, \" out of \")\n stream$putright(po, int$unparse(amount), 7)\n stream$putl(po, \", \" || f_form(perc, 3, 2) || \"%\")\nend show \n\nstart_up = proc ()\n prisoners = 100\n tries = 50\n simulations = 50000\n \n init_rng()\n\n show(\" Random\", simulations, prisoners, tries, rand_strat)\n show(\"Optimal\", simulations, prisoners, tries, opt_strat)\nend start_up", "safe": true }, { "filename": "100 prisoners_35.txt", "content": " Random: 0 out of 50000, 0.00%\nOptimal: 15541 out of 50000, 31.08%", "safe": true }, { "filename": "100 prisoners_36.txt", "content": "10 rem 100 prisoners\n20 rem set arrays\n30 rem dr = drawers containing card values\n40 rem ig = a list of numbers 1 through 100, shuffled to become the \n41 rem guess sequence for each inmate - method 1\n50 dim dr(100),ig(100)\n55 rem initialize drawers with own card in each drawer\n60 for i=1 to 100:dr(i)=i:next \n\n1000 print chr$(147);\"how many trials for each method\";:input tt\n1010 for m=1 to 2:su(m)=0:fa(m)=0\n1015 for tn=1 to tt\n1020 on m gosub 2000,3000\n1025 rem ip = number of inmates who passed\n1030 if ip=100 then su(m)=su(m)+1\n1040 if ip<100 then fa(m)=fa(m)+1\n1045 next tn\n1055 next m\n\n1060 print chr$(147);\"Results:\":print\n1070 print \"Out of\";tt;\"trials, the results are\"\n1071 print \"as follows...\":print\n1072 print \"1. Random Guessing:\"\n1073 print \" \";su(1);\"successes\"\n1074 print \" \";fa(1);\"failures\"\n1075 print \" \";su(1)/tn;\"{left-crsr}% success rate.\":print\n1077 print \"2. Chained Number Picking:\"\n1078 print \" \";su(2);\"successes\"\n1079 print \" \";fa(2);\"failures\"\n1080 print \" \";(su(2)/tn)*100;\"{left-crsr}% success rate.\":print\n1100 print:print \"Again?\"\n1110 get k$:if k$=\"\" then 1110\n1120 if k$=\"y\" then 1000\n1500 end\n\n2000 rem random guessing method\n2005 for x=1 to 100:ig(x)=x:next:ip=0:gosub 4000\n2007 for i=1 to 100\n2010 for x=1 to 100:t=ig(x):np=int(rnd(1)*100)+1:ig(x)=ig(np):ig(np)=t:next\n2015 for g=1 to 50\n2020 if dr(ig(g))=i then ip=ip+1:next i:return\n2025 next g\n2030 return\n\n3000 rem chained method\n3005 ip=0:gosub 4000\n3007 rem iterate through each inmate\n3010 fori=1to100\n3015 ng=i:forg=1to50\n3020 cd=dr(ng)\n3025 ifcd=ithenip=ip+1:nexti:return\n3030 ifcd<>ithenng=cd\n3035 nextg:return\n\n4000 rem shuffle the drawer cards randomly\n4010 x=rnd(-ti)\n4020 for i=1 to 100\n4030 r=int(rnd(1)*100)+1:t=dr(i):dr(i)=dr(r):dr(r)=t:next\n4040 return\n", "safe": true }, { "filename": "100 prisoners_37.txt", "content": "Results:\n\nOut of 4000 trials the percentage of\nsuccess is as follows...\n\n1. Random Guessing:\n 0 successes\n 4000 failures\n 0% success rate.\n\n2. Chained Number Picking:\n 1274 successes\n 2726 failures\n 31.85% success rate.\n", "safe": true }, { "filename": "100 prisoners_38.txt", "content": "(defparameter *samples* 10000)\n(defparameter *prisoners* 100)\n(defparameter *max-guesses* 50)\n\n(defun range (n)\n \"Returns a list from 0 to N.\"\n (loop\n for i below n\n collect i))\n\n(defun nshuffle (list)\n \"Returns a shuffled LIST.\"\n (loop\n for i from (length list) downto 2\n do (rotatef (nth (random i) list)\n (nth (1- i) list)))\n list)\n\n(defun build-drawers ()\n \"Returns a list of shuffled drawers.\"\n (nshuffle (range *prisoners*)))\n\n(defun strategy-1 (drawers p)\n \"Returns T if P is found in DRAWERS under *MAX-GUESSES* using a random strategy.\"\n (loop\n for i below *max-guesses*\n thereis (= p (nth (random *prisoners*) drawers))))\n\n(defun strategy-2 (drawers p)\n \"Returns T if P is found in DRAWERS under *MAX-GUESSES* using an optimal strategy.\"\n (loop\n for i below *max-guesses*\n for j = p then (nth j drawers)\n thereis (= p (nth j drawers))))\n\n(defun 100-prisoners-problem (strategy &aux (drawers (build-drawers)))\n \"Returns T if all prisoners find their number using the given STRATEGY.\"\n (every (lambda (e) (eql T e))\n (mapcar (lambda (p) (funcall strategy drawers p)) (range *prisoners*))))\n\n(defun sampling (strategy)\n (loop\n repeat *samples*\n for result = (100-prisoners-problem strategy) \n count result))\n\n(defun compare-strategies ()\n (format t \"Using a random strategy in ~4,2F\u00a0% of the cases the prisoners are free.~%\" (* (/ (sampling #'strategy-1) *samples*) 100))\n (format t \"Using an optimal strategy in ~4,2F\u00a0% of the cases the prisoners are free.~%\" (* (/ (sampling #'strategy-2) *samples*) 100)))\n", "safe": true }, { "filename": "100 prisoners_39.txt", "content": "CL-USER> (compare-strategies)\nUsing a random strategy in 0.00\u00a0% of the cases the prisoners are free.\nUsing an optimal strategy in 31.34\u00a0% of the cases the prisoners are free.", "safe": true }, { "filename": "100 prisoners_4.txt", "content": "Random strategie \u00a0: 0 sur 1000\nOptimal strategie\u00a0: 305 sur 1000\n", "safe": true }, { "filename": "100 prisoners_40.txt", "content": "include \"cowgol.coh\";\ninclude \"argv.coh\";\n\n# Parameters\nconst Drawers \u00a0:= 100; # Amount of drawers (and prisoners)\nconst Attempts \u00a0:= 50; # Amount of attempts a prisoner may make\nconst Simulations\u00a0:= 2000; # Amount of simulations to run\n\ntypedef NSim is int(0, Simulations);\n\n# Random number generator\nrecord RNG is\n x: uint8;\n a: uint8;\n b: uint8;\n c: uint8;\n state @at(0): int32;\nend record;\n\nsub RandomByte(r: [RNG]): (byte: uint8) is \n r.x\u00a0:= r.x + 1;\n r.a\u00a0:= r.a ^ r.c ^ r.x;\n r.b\u00a0:= r.b + r.a;\n r.c\u00a0:= r.c + (r.b >> 1) ^ r.a;\n byte\u00a0:= r.c;\nend sub;\n\nsub RandomUpTo(r: [RNG], limit: uint8): (rslt: uint8) is\n var x: uint8\u00a0:= 1;\n while x < limit loop\n x\u00a0:= x << 1;\n end loop;\n x\u00a0:= x - 1;\n \n loop\n rslt\u00a0:= RandomByte(r) & x;\n if rslt < limit then\n break;\n end if;\n end loop;\nend sub;\n\n# Drawers (though marked 0..99 instead of 1..100)\nvar drawers: uint8[Drawers];\ntypedef Drawer is @indexof drawers;\ntypedef Prisoner is Drawer;\n\n# Place cards randomly in drawers\nsub InitDrawers(r: [RNG]) is\n var x: Drawer\u00a0:= 0;\n while x < Drawers loop\n drawers[x]\u00a0:= x;\n x\u00a0:= x + 1;\n end loop;\n \n x\u00a0:= 0;\n while x < Drawers - 1 loop\n var y\u00a0:= x + RandomUpTo(r, Drawers-x);\n var t\u00a0:= drawers[x];\n drawers[x]\u00a0:= drawers[y];\n drawers[y]\u00a0:= t;\n x\u00a0:= x + 1;\n end loop;\nend sub;\n\n# A prisoner can apply a strategy and either succeed or not\ninterface Strategy(p: Prisoner, r: [RNG]): (success: uint8);\n\n# The stupid strategy: open drawers randomly.\nsub Stupid implements Strategy is\n # Let's assume the prisoner is smart enough not to reopen an open drawer\n var opened: Drawer[Drawers];\n MemZero(&opened[0], @bytesof opened);\n \n # Open random drawers\n success\u00a0:= 0;\n var triesLeft: uint8\u00a0:= Attempts;\n while triesLeft\u00a0!= 0 loop\n var d\u00a0:= RandomUpTo(r, Drawers); # grab a random drawer\n if opened[d]\u00a0!= 0 then\n continue; # Ignore it if a drawer was already open\n else\n triesLeft\u00a0:= triesLeft - 1;\n opened[d]\u00a0:= 1;\n if drawers[d] == p then # found it!\n success\u00a0:= 1;\n return;\n end if;\n end if;\n end loop;\nend sub;\n \n# The optimal strategy: open the drawer for each number\nsub Optimal implements Strategy is\n var current\u00a0:= p;\n var triesLeft: uint8\u00a0:= Attempts;\n success\u00a0:= 0;\n while triesLeft\u00a0!= 0 loop\n current\u00a0:= drawers[current];\n if current == p then\n success\u00a0:= 1;\n return;\n end if;\n triesLeft\u00a0:= triesLeft - 1;\n end loop;\nend sub;\n\n# Run a simulation\nsub Simulate(s: Strategy, r: [RNG]): (success: uint8) is\n InitDrawers(r); # place cards randomly in drawer\n var p: Prisoner\u00a0:= 0;\n success\u00a0:= 1; # if they all succeed the simulation succeeds\n while p < Drawers loop # but for each prisoner... \n if s(p, r) == 0 then # if he fails, the simulation fails\n success\u00a0:= 0;\n return;\n end if;\n p\u00a0:= p + 1;\n end loop;\nend sub;\n\n# Run an amount of simulations and report the amount of successes\nsub Run(n: NSim, s: Strategy, r: [RNG]): (successes: NSim) is\n successes\u00a0:= 0;\n while n > 0 loop\n successes\u00a0:= successes + Simulate(s, r) as NSim;\n n\u00a0:= n - 1;\n end loop;\nend sub;\n\n# Initialize RNG with number given on command line (defaults to 0)\nvar rng: RNG; rng.state\u00a0:= 0;\nArgvInit();\nvar arg\u00a0:= ArgvNext();\nif arg\u00a0!= 0 as [uint8] then\n (rng.state, arg)\u00a0:= AToI(arg);\nend if;\n\nsub RunAndPrint(name: [uint8], strat: Strategy) is\n print(name);\n print(\" strategy: \");\n var succ\u00a0:= Run(Simulations, strat, &rng) as uint32;\n print_i32(succ);\n print(\" out of \");\n print_i32(Simulations);\n print(\" - \");\n print_i32(succ * 100 / Simulations);\n print(\"%\\n\");\nend sub;\n\nRunAndPrint(\"Stupid\", Stupid);\nRunAndPrint(\"Optimal\", Optimal);", "safe": true }, { "filename": "100 prisoners_41.txt", "content": "Stupid strategy: 0 out of 2000 - 0%\nOptimal strategy: 634 out of 2000 - 31%", "safe": true }, { "filename": "100 prisoners_42.txt", "content": "prisoners = (1..100).to_a\nN = 100_000\ngenerate_rooms = ->{ (1..100).to_a.shuffle }\n\nres = N.times.count do\n rooms = generate_rooms.call\n prisoners.all? { |pr| rooms[1, 100].sample(50).includes?(pr) }\nend\nputs \"Random strategy\u00a0: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n\nres = N.times.count do\n rooms = generate_rooms.call\n prisoners.all? do |pr|\n cur_room = pr\n 50.times.any? do\n cur_room = rooms[cur_room - 1]\n found = (cur_room == pr)\n found\n end\n end\nend\nputs \"Optimal strategy: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n", "safe": true }, { "filename": "100 prisoners_43.txt", "content": "Random strategy\u00a0: 0.0000\u00a0%\nOptimal strategy: 31.3190\u00a0%", "safe": true }, { "filename": "100 prisoners_44.txt", "content": "import std.array;\nimport std.random;\nimport std.range;\nimport std.stdio;\nimport std.traits;\n\nbool playOptimal() {\n auto secrets = iota(100).array.randomShuffle();\n\n prisoner:\n foreach (p; 0..100) {\n auto choice = p;\n foreach (_; 0..50) {\n if (secrets[choice] == p) continue prisoner;\n choice = secrets[choice];\n }\n return false;\n }\n\n return true;\n}\n\nbool playRandom() {\n auto secrets = iota(100).array.randomShuffle();\n\n prisoner:\n foreach (p; 0..100) {\n auto choices = iota(100).array.randomShuffle();\n foreach (i; 0..50) {\n if (choices[i] == p) continue prisoner;\n }\n return false;\n }\n\n return true;\n}\n\ndouble exec(const size_t n, bool function() play) {\n size_t success = 0;\n for (int i = n; i > 0; i--) {\n if (play()) {\n success++;\n }\n }\n return 100.0 * success / n;\n}\n\nvoid main() {\n enum N = 1_000_000;\n writeln(\"# of executions: \", N);\n writefln(\"Optimal play success rate: %11.8f%%\", exec(N, &playOptimal));\n writefln(\" Random play success rate: %11.8f%%\", exec(N, &playRandom));\n}\n", "safe": true }, { "filename": "100 prisoners_45.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.16100000%\n Random play success rate: 0.00000000%", "safe": true }, { "filename": "100 prisoners_46.txt", "content": "import 'dart:math';\n\nint playRandom(int n) {\n var rnd = Random();\n int pardoned = 0;\n List inDrawer = List.generate(100, (i) => i);\n List sampler = List.generate(100, (i) => i);\n for (int round = 0; round < n; round++) {\n inDrawer.shuffle();\n bool found = false;\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n found = false;\n sampler.shuffle(rnd);\n for (int i = 0; i < 50; i++) {\n int reveal = sampler[i];\n int card = inDrawer[reveal];\n if (card == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n break;\n }\n }\n if (found) {\n pardoned++;\n }\n }\n return (pardoned / n * 100).round();\n}\n\nint playOptimal(int n) {\n var rnd = Random();\n int pardoned = 0;\n bool found = false;\n List inDrawer = List.generate(100, (i) => i);\n for (int round = 0; round < n; round++) {\n inDrawer.shuffle(rnd);\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n int reveal = prisoner;\n found = false;\n for (int go = 0; go < 50; go++) {\n int card = inDrawer[reveal];\n if (card == prisoner) {\n found = true;\n break;\n }\n reveal = card;\n }\n if (!found) {\n break;\n }\n }\n if (found) {\n pardoned++;\n }\n }\n return (pardoned / n * 100).round();\n}\n\nvoid main() {\n int n = 100000;\n print(\" Simulation count: $n\");\n print(\" Random play wins: ${playRandom(n).toStringAsFixed(2)}% of simulations\");\n print(\"Optimal play wins: ${playOptimal(n).toStringAsFixed(2)}% of simulations\");\n}\n", "safe": true }, { "filename": "100 prisoners_47.txt", "content": " Simulation count: 100000\n Random play wins: 0.00% of simulations\nOptimal play wins: 31.00% of simulations\n\n", "safe": true }, { "filename": "100 prisoners_48.txt", "content": "for i = 1 to 100\n drawer[] &= i\n sampler[] &= i\n.\nsubr shuffle_drawer\n for i = len drawer[] downto 2\n r = random i\n swap drawer[r] drawer[i]\n .\n.\nsubr play_random\n shuffle_drawer\n for prisoner = 1 to 100\n found = 0\n for i = 1 to 50\n r = random (100 - i)\n card = drawer[sampler[r]]\n swap sampler[r] sampler[100 - i - 1]\n if card = prisoner\n found = 1\n break 1\n .\n .\n if found = 0\n break 1\n .\n .\n.\nsubr play_optimal\n shuffle_drawer\n for prisoner = 1 to 100\n reveal = prisoner\n found = 0\n for i = 1 to 50\n card = drawer[reveal]\n if card = prisoner\n found = 1\n break 1\n .\n reveal = card\n .\n if found = 0\n break 1\n .\n .\n.\nn = 10000\nwin = 0\nfor _ = 1 to n\n play_random\n win += found\n.\nprint \"random: \" & 100.0 * win / n & \"%\"\n#\nwin = 0\nfor _ = 1 to n\n play_optimal\n win += found\n.\nprint \"optimal: \" & 100.0 * win / n & \"%\"\n", "safe": true }, { "filename": "100 prisoners_49.txt", "content": "random: 0.000%\noptimal: 30.800%\n", "safe": true }, { "filename": "100 prisoners_5.txt", "content": "HOW TO FILL drawers:\n PUT {} IN drawers\n FOR i IN {1..100}: PUT i IN drawers[i]\n FOR i IN {1..100}:\n PUT choice {i..100} IN j\n PUT drawers[i], drawers[j] IN drawers[j], drawers[i]\n\nHOW TO REPORT prisoner random.strat drawers:\n PUT {1..100} IN available\n FOR turn IN {1..50}:\n PUT choice available IN drawer\n IF drawers[drawer] = prisoner: SUCCEED\n REMOVE drawer FROM available\n FAIL\n\nHOW TO REPORT prisoner optimal.strat drawers:\n PUT prisoner IN drawer\n FOR turn IN {1..50}:\n IF drawers[drawer] = prisoner: SUCCEED\n PUT drawers[drawer] IN drawer\n FAIL\n\nHOW TO REPORT simulate strategy:\n FILL drawers\n FOR prisoner IN {1..100}:\n SELECT:\n strategy = \"Random\":\n IF NOT prisoner random.strat drawers: FAIL\n strategy = \"Optimal\":\n IF NOT prisoner optimal.strat drawers: FAIL\n SUCCEED\n\nHOW TO RETURN n.sim chance.of.success strategy:\n PUT 0 IN success\n FOR n IN {1..n.sim}:\n IF simulate strategy: PUT success+1 IN success\n RETURN success * 100 / n.sim\n\nFOR strategy IN {\"Random\"; \"Optimal\"}:\n WRITE strategy, \": \", 10000 chance.of.success strategy, '%'/", "safe": true }, { "filename": "100 prisoners_50.txt", "content": "module OneHundredPrisoners {\n @Inject Console console;\n\n void run() {\n console.print($\"# of executions: {attempts}\");\n console.print($\"Optimal play success rate: {simulate(tryOpt)}%\");\n console.print($\" Random play success rate: {simulate(tryRnd)}%\");\n }\n\n Int attempts = 10000;\n\n Dec simulate(function Boolean(Int[]) allFoundNumber) {\n Int[] drawers = new Int[100](i->i);\n Int pardoned = 0;\n for (Int i\u00a0: 1..attempts) {\n if (allFoundNumber(drawers.shuffled())) {\n ++pardoned;\n }\n }\n return (pardoned * 1000000 / attempts).toDec() / 10000;\n }\n\n Boolean tryRnd(Int[] drawers) {\n Inmates: for (Int inmate\u00a0: 0..<100) {\n Int[] choices = drawers.shuffled();\n for (Int attempt\u00a0: 0..<50) {\n if (drawers[choices[attempt]] == inmate) {\n continue Inmates;\n }\n }\n return False;\n }\n return True;\n }\n\n Boolean tryOpt(Int[] drawers) {\n Inmates: for (Int inmate\u00a0: 0..<100) {\n Int choice = inmate;\n for (Int attempt\u00a0: 0..<50) {\n if (drawers[choice] == inmate) {\n continue Inmates;\n }\n choice = drawers[choice];\n }\n return False;\n }\n return True;\n }\n}", "safe": true }, { "filename": "100 prisoners_51.txt", "content": "# of executions: 10000\nOptimal play success rate: 30.1%\n Random play success rate: 0%\n", "safe": true }, { "filename": "100 prisoners_52.txt", "content": "defmodule HundredPrisoners do\n def optimal_room(_, _, _, []), do: []\n def optimal_room(prisoner, current_room, rooms, [_ | tail]) do\n found = Enum.at(rooms, current_room - 1) == prisoner\n next_room = Enum.at(rooms, current_room - 1)\n [found] ++ optimal_room(prisoner, next_room, rooms, tail)\n end\n\n def optimal_search(prisoner, rooms) do\n Enum.any?(optimal_room(prisoner, prisoner, rooms, Enum.to_list(1..50)))\n end\nend\n\nprisoners = 1..100\nn = 1..10_000\ngenerate_rooms = fn -> Enum.shuffle(1..100) end\n\nrandom_strategy = Enum.count(n, \n fn _ -> \n rooms = generate_rooms.()\n Enum.all?(prisoners, fn pr -> pr in (rooms |> Enum.take_random(50)) end)\nend)\n\nIO.puts \"Random strategy: #{random_strategy} / #{n |> Range.size}\"\n\noptimal_strategy = Enum.count(n,\n fn _ ->\n rooms = generate_rooms.()\n Enum.all?(prisoners, \n fn pr -> HundredPrisoners.optimal_search(pr, rooms) end)\nend)\n\nIO.puts \"Optimal strategy: #{optimal_strategy} / #{n |> Range.size}\"\n", "safe": true }, { "filename": "100 prisoners_53.txt", "content": "Random strategy: 0 / 10000\nOptimal strategy: 3110 / 10000\n", "safe": true }, { "filename": "100 prisoners_54.txt", "content": "let rnd = System.Random()\nlet shuffled min max =\n [|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))\n\nlet drawers () = shuffled 1 100\n\n// strategy randomizing drawer opening\nlet badChoices (drawers' : int array) =\n Seq.init 100 (fun _ -> shuffled 1 100 |> Array.take 50) // selections for each prisoner\n |> Seq.map (fun indexes -> indexes |> Array.map(fun index -> drawers'.[index-1])) // transform to cards\n |> Seq.mapi (fun i cards -> cards |> Array.contains i) // check if any card matches prisoner number\n |> Seq.contains false // true means not all prisoners got their cards\nlet outcomeOfRandom runs =\n let pardons = Seq.init runs (fun _ -> badChoices (drawers ()))\n |> Seq.sumBy (fun badChoice -> if badChoice |> not then 1.0 else 0.0)\n pardons/ float runs\n \n// strategy optimizing drawer opening\nlet smartChoice max prisoner (drawers' : int array) =\n prisoner\n |> Seq.unfold (fun selection ->\n let card = drawers'.[selection-1]\n Some (card, card))\n |> Seq.take max\n |> Seq.contains prisoner\nlet smartChoices (drawers' : int array) =\n seq { 1..100 }\n |> Seq.map (fun prisoner -> smartChoice 50 prisoner drawers')\n |> Seq.filter (fun result -> result |> not) // remove all but false results\n |> Seq.isEmpty // empty means all prisoners got their cards\nlet outcomeOfOptimize runs =\n let pardons = Seq.init runs (fun _ -> smartChoices (drawers()))\n |> Seq.sumBy (fun smartChoice' -> if smartChoice' then 1.0 else 0.0)\n pardons/ float runs\n \nprintfn $\"Using Random Strategy: {(outcomeOfRandom 20000):p2}\"\nprintfn $\"Using Optimum Strategy: {(outcomeOfOptimize 20000):p2}\"\n", "safe": true }, { "filename": "100 prisoners_55.txt", "content": "Using Random Strategy: 0.00%\nUsing Optimum Strategy: 31.06%\n", "safe": true }, { "filename": "100 prisoners_56.txt", "content": "USING: arrays formatting fry io kernel math random sequences ;\n\n: setup ( -- seq seq ) 100 dup >array randomize ;\n\n: rand ( -- ? )\n setup [ 50 sample member? not ] curry find nip >boolean not ;\n\n: trail ( m seq -- n )\n 50 pick '[ [ nth ] keep over _ = ] replicate [ t = ] any?\n 2nip ;\n\n: optimal ( -- ? ) setup [ trail ] curry [ and ] map-reduce ;\n\n: simulate ( m quot -- x )\n dupd replicate [ t = ] count swap /f 100 * ; inline\n\n\"Simulation count: 10,000\" print\n10,000 [ rand ] simulate \"Random play success: \"\n10,000 [ optimal ] simulate \"Optimal play success: \"\n[ write \"%.2f%%\\n\" printf ] 2bi@\n", "safe": true }, { "filename": "100 prisoners_57.txt", "content": "Simulation count: 10,000\nRandom play success: 0.00%\nOptimal play success: 31.11%\n", "safe": true }, { "filename": "100 prisoners_58.txt", "content": "01.10 T %5.02,\" RANDOM\";S CU=0\n01.20 F Z=1,2000;D 5;S CU=CU+SU\n01.30 T CU/20,!,\"OPTIMAL\";S CU=0\n01.40 F Z=1,2000;D 6;S CU=CU+SU\n01.50 T CU/20,!\n01.60 Q\n\n02.01 C-- PUT CARDS IN RANDOM DRAWERS\n02.10 F X=1,100;S D(X)=X\n02.20 F X=1,99;D 2.3;S B=D(X);S D(X)=D(A);S D(A)=B\n02.30 D 2.4;S A=X+FITR(A*(101-X))\n02.40 S A=FABS(FRAN()*10);S A=A-FITR(A)\n\n03.01 C-- PRISONER X TRIES UP TO 50 RANDOM DRAWERS\n03.10 S TR=50;S SU=0\n03.20 D 2.4;I (X-D(A))3.3,3.4,3.3\n03.30 S TR=TR-1;I (TR),3.5,3.2\n03.40 S SU=1;R\n03.50 S SU=0\n\n04.01 C-- PRISONER X TRIES OPTIMAL METHOD\n04.10 S TR=50;S SU=0;S A=X\n04.20 I (X-D(A))4.3,4.4,4.3\n04.30 S TR=TR-1;S A=D(A);I (TR),4.5,4.2\n04.40 S SU=1;R\n04.50 S SU=0\n\n05.01 C-- PRISONERS TRY RANDOM METHOD UNTIL ONE FAILS\n05.10 D 2;S X=1\n05.20 I (X-101)5.3,5.4\n05.30 D 3;S X=X+1;I (SU),5.4,5.2\n05.40 R\n\n06.01 C-- PRISONERS TRY OPTIMAL METHOD UNTIL ONE FAILS\n06.10 D 2;S X=1\n06.20 I (X-101)6.3,6.4\n06.30 D 4;S X=X+1;I (SU),6.4,6.2\n06.40 R", "safe": true }, { "filename": "100 prisoners_59.txt", "content": " RANDOM= 0.00\nOPTIMAL= 30.10", "safe": true }, { "filename": "100 prisoners_6.txt", "content": "Optimal: 32.01\u00a0%\nRandom: 0\u00a0%", "safe": true }, { "filename": "100 prisoners_60.txt", "content": "INCLUDE ran4.seq\n\n100 CONSTANT #drawers\n#drawers CONSTANT #players\n100000 CONSTANT #tries\n\nCREATE drawers #drawers CELLS ALLOT \\ index 0..#drawers-1\n\n: drawer[] ( n -- addr ) \\ return address of drawer n\n CELLS drawers +\n;\n\n: random_drawer ( -- n ) \\ n=0..#drawers-1 random drawer \n RAN4 ( d ) XOR ( n ) #drawers MOD\n;\n\n: random_drawer[] ( -- addr ) \\ return address of random drawer\n random_drawer drawer[]\n;\n\n: swap_indirect ( addr1 addr2 -- ) \\ swaps the values at the two addresses\n 2DUP @ SWAP @ ( addr1 addr2 n2 n1 )\n ROT ! SWAP ! \\ store n1 at addr2 and n2 at addr1\n;\n\n: init_drawers ( -- ) \\ shuffle cards into drawers\n #drawers 0 DO\n I I drawer[] ! \\ store cards in order\n LOOP\n #drawers 0 DO\n I drawer[] random_drawer[] ( addr-drawer-i addr-drawer-rnd )\n swap_indirect\n LOOP\n;\n\n: random_turn ( player - f )\n #drawers 2 / 0 DO\n\t\trandom_drawer \n\t\tdrawer[] @ \n\t\tOVER = IF\n\t\t\tDROP TRUE UNLOOP EXIT\t\\ found his number\n\t\tTHEN\n\tLOOP \n\tDROP FALSE\n;\n\n0 VALUE player\n\n: cycle_turn ( player - f )\n\tDUP TO player\t\t\t( next-drawer )\n #drawers 2 / 0 DO\n\t\tdrawer[] @\n\t\tDUP player = IF \n\t\t\tDROP TRUE UNLOOP EXIT\t\\ found his number\n\t\tTHEN\n\tLOOP \n\tDROP FALSE\n;\n\n: turn ( strategy player - f )\n SWAP 0= IF \\ random play \n random_turn\n ELSE\n cycle_turn\n THEN\n;\n\n: play ( strategy -- f ) \\ return true if prisioners survived\n init_drawers\n #players 0 DO\n DUP I turn\n 0= IF\n DROP FALSE UNLOOP EXIT \t\\ this player did not survive, UNLOOP, return false\n THEN\n LOOP \n DROP TRUE \\ all survived, return true\n;\n\n: trie\t\t\t\t\t( strategy - nr-saved )\n\t0\t\t\t\t( strategy nr-saved )\n\t#tries 0 DO\n\t\tOVER play IF 1+ THEN\n\tLOOP\n\tNIP\n;\n\n0 trie . CR\t\\ random strategy\n1 trie . CR\t\\ follow the card number strategy\n", "safe": true }, { "filename": "100 prisoners_61.txt", "content": "0 \n30009 \n", "safe": true }, { "filename": "100 prisoners_62.txt", "content": "SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)\n ! Takes an input array and shuffles the elements by swapping them\n ! in pairs in turn 10 times\n IMPLICIT NONE\n\n INTEGER, DIMENSION(100), INTENT(INOUT) :: INT_ARRAY\n INTEGER, PARAMETER :: N_PASSES = 10\n ! Local Variables\n\n INTEGER :: TEMP_1, TEMP_2 ! Temporaries for swapping elements\n INTEGER :: I, J, PASS ! Indices variables\n REAL :: R ! Randomly generator value\n\n CALL RANDOM_SEED() ! Seed the random number generator\n\n DO PASS=1, N_PASSES\n DO I=1, SIZE(INT_ARRAY)\n\n ! Get a random index to swap with\n CALL RANDOM_NUMBER(R)\n J = CEILING(R*SIZE(INT_ARRAY))\n\n ! In case generated index value\n ! exceeds array size\n DO WHILE (J > SIZE(INT_ARRAY))\n J = CEILING(R*SIZE(INT_ARRAY))\n END DO\n\n ! Swap the two elements\n TEMP_1 = INT_ARRAY(I)\n TEMP_2 = INT_ARRAY(J)\n INT_ARRAY(I) = TEMP_2\n INT_ARRAY(J) = TEMP_1\n ENDDO\n ENDDO\nEND SUBROUTINE SHUFFLE_ARRAY\n\nSUBROUTINE RUN_RANDOM(N_ROUNDS)\n ! Run the 100 prisoner puzzle simulation N_ROUNDS times\n ! in the scenario where each prisoner selects a drawer at random\n IMPLICIT NONE\n\n INTEGER, INTENT(IN) :: N_ROUNDS ! Number of simulations to run in total\n\n INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables\n INTEGER :: N_SUCCESSES ! Number of successful trials\n REAL(8) :: TOTAL ! Total number of trials as real\n LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number\n\n INTEGER, DIMENSION(100) :: CARDS, CHOICES ! Arrays representing card allocations\n ! to draws and drawer choice order\n\n ! Both cards and choices are randomly assigned.\n ! This being the drawer (allocation represented by index),\n ! and what drawer to pick for Nth/50 choice\n ! (take first 50 elements of 100 element array)\n CARDS = (/(I, I=1, 100, 1)/)\n CHOICES = (/(I, I=1, 100, 1)/)\n\n N_SUCCESSES = 0\n TOTAL = REAL(N_ROUNDS)\n\n ! Run the simulation for N_ROUNDS rounds\n ! when a prisoner fails to find their number\n ! after 50 trials, set that simulation to fail\n ! and start the next round\n ROUNDS_LOOP: DO ROUND=1, N_ROUNDS\n CALL SHUFFLE_ARRAY(CARDS)\n PRISONERS_LOOP: DO PRISONER=1, 100\n NUM_FOUND = .FALSE.\n CALL SHUFFLE_ARRAY(CHOICES)\n CHOICE_LOOP: DO CHOICE=1, 50\n IF(CARDS(CHOICE) == PRISONER) THEN\n NUM_FOUND = .TRUE.\n EXIT CHOICE_LOOP\n ENDIF\n ENDDO CHOICE_LOOP\n IF(.NOT. NUM_FOUND) THEN\n EXIT PRISONERS_LOOP\n ENDIF\n ENDDO PRISONERS_LOOP\n IF(NUM_FOUND) THEN\n N_SUCCESSES = N_SUCCESSES + 1\n ENDIF\n ENDDO ROUNDS_LOOP\n\n WRITE(*, '(A, F0.3, A)') \"Random drawer selection method success rate: \", &\n 100*N_SUCCESSES/TOTAL, \"%\"\n\nEND SUBROUTINE RUN_RANDOM\n\nSUBROUTINE RUN_OPTIMAL(N_ROUNDS)\n ! Run the 100 prisoner puzzle simulation N_ROUNDS times in the scenario\n ! where each prisoner selects firstly the drawer with their number and then\n ! subsequently the drawer matching the number of the card present \n ! within that current drawer\n IMPLICIT NONE\n\n INTEGER, INTENT(IN) :: N_ROUNDS\n\n INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables\n INTEGER :: CURRENT_DRAW ! ID of the current draw\n INTEGER :: N_SUCCESSES ! Number of successful trials\n REAL(8) :: TOTAL ! Total number of trials as real\n LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number \n INTEGER, DIMENSION(100) :: CARDS ! Array representing card allocations\n\n ! Cards are randomly assigned to a drawer \n ! (allocation represented by index),\n CARDS = (/(I, I=1, 100, 1)/)\n\n N_SUCCESSES = 0\n TOTAL = REAL(N_ROUNDS)\n\n ! Run the simulation for N_ROUNDS rounds\n ! when a prisoner fails to find their number\n ! after 50 trials, set that simulation to fail\n ! and start the next round\n ROUNDS_LOOP: DO ROUND=1, N_ROUNDS\n CARDS = (/(I, I=1, 100, 1)/)\n CALL SHUFFLE_ARRAY(CARDS)\n PRISONERS_LOOP: DO PRISONER=1, 100\n CURRENT_DRAW = PRISONER\n NUM_FOUND = .FALSE.\n CHOICE_LOOP: DO CHOICE=1, 50\n IF(CARDS(CURRENT_DRAW) == PRISONER) THEN\n NUM_FOUND = .TRUE.\n EXIT CHOICE_LOOP\n ELSE\n CURRENT_DRAW = CARDS(CURRENT_DRAW)\n ENDIF\n ENDDO CHOICE_LOOP\n IF(.NOT. NUM_FOUND) THEN\n EXIT PRISONERS_LOOP\n ENDIF\n ENDDO PRISONERS_LOOP\n IF(NUM_FOUND) THEN\n N_SUCCESSES = N_SUCCESSES + 1\n ENDIF\n ENDDO ROUNDS_LOOP\n WRITE(*, '(A, F0.3, A)') \"Optimal drawer selection method success rate: \", &\n 100*N_SUCCESSES/TOTAL, \"%\"\n\nEND SUBROUTINE RUN_OPTIMAL\n\nPROGRAM HUNDRED_PRISONERS\n ! Run the two scenarios for the 100 prisoners puzzle of random choice\n ! and optimal choice (choice based on drawer contents)\n IMPLICIT NONE\n INTEGER, PARAMETER :: N_ROUNDS = 50000\n WRITE(*,'(A, I0, A)') \"Running simulation for \", N_ROUNDS, \" trials...\"\n CALL RUN_RANDOM(N_ROUNDS)\n CALL RUN_OPTIMAL(N_ROUNDS)\nEND PROGRAM HUNDRED_PRISONERS\n", "safe": true }, { "filename": "100 prisoners_63.txt", "content": "Running simulation for 50000 trials...\nRandom drawer selection method success rate: .000%\nOptimal drawer selection method success rate: 31.360%\n", "safe": true }, { "filename": "100 prisoners_64.txt", "content": "#include once \"knuthshuf.bas\" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC\n\nfunction gus( i as long, strat as boolean ) as long\n if strat then return i\n return 1+int(rnd*100)\nend function\n\nsub trials( byref c_success as long, byref c_fail as long, byval strat as boolean )\n dim as long i, j, k, guess, drawer(1 to 100)\n for i = 1 to 100\n drawer(i) = i\n next i\n for j = 1 to 1000000 'one million trials of prisoners\n knuth_up( drawer() ) 'shuffles the cards in the drawers\n for i = 1 to 100 'prisoner number\n guess = gus(i, strat)\n for k = 1 to 50 'each prisoner gets 50 tries\n if drawer(guess) = i then goto next_prisoner\n guess = gus(drawer(guess), strat)\n next k\n c_fail += 1\n goto next_trial\n next_prisoner:\n next i\n c_success += 1\n next_trial:\n next j\nend sub\n\nrandomize timer\ndim as long c_fail=0, c_success=0\n\ntrials( c_success, c_fail, false )\n\nprint using \"For prisoners guessing randomly we had ####### successes and ####### failures.\";c_success;c_fail\n\nc_success = 0\nc_fail = 0\n\ntrials( c_success, c_fail, true )\n\nprint using \"For prisoners using the strategy we had ####### successes and ####### failures.\";c_success;c_fail\n", "safe": true }, { "filename": "100 prisoners_65.txt", "content": "include \"Tlbx GameplayKit.incl\"\n\n_prisoners = 100\n_instances = 10000\n\nlocal fn DrawersArray as CFArrayRef\n long index\n CFMutableArrayRef temp = fn MutableArrayWithCapacity(100)\n for index = 0 to 99\n MutableArrayAddObject( temp, @(index) )\n next\nend fn = fn ArrayShuffledArray( temp )\n\n\nlocal fn RandomResult( drawers as CFArrayRef ) as BOOL\n long prisoner, i, drawer, total = 0\n MutableIndexSetRef set\n \n for prisoner = 0 to _prisoners - 1\n set = fn MutableIndexSetInit\n for i = 1 to _prisoners/2\n drawer = rnd(_prisoners)-1\n while ( fn IndexSetContainsIndex( set, intVal( drawers[drawer] ) ) )\n drawer = rnd(_prisoners)-1\n wend\n MutableIndexSetAddIndex( set, intVal( drawers[drawer] ) )\n if ( fn IndexSetContainsIndex( set, prisoner ) )\n total++\n break\n end if\n next\n next\nend fn = ( total == _prisoners )\n\n\nlocal fn OptimalResult( drawers as CFArrayRef ) as BOOL\n long prisoner, drawer, i, card, total = 0\n \n for prisoner = 0 to _prisoners - 1\n drawer = prisoner\n for i = 1 to _prisoners/2\n card = intVal( drawers[drawer] )\n if ( card == prisoner )\n total++\n break\n end if\n drawer = card\n next\n next\nend fn = ( total == _prisoners )\n\n\nvoid local fn DoIt\n static double sTime = 0.0\n \n block TimerRef timer = timerbegin , 0.001, YES\n sTime += 0.001\n cls\n printf @\"Compute time:\u00a0%.3f\\n\",sTime\n timerend\n \n dispatchglobal\n long instance, randomTotal = 0, optimalTotal = 0\n CFArrayRef drawers\n \n for instance = 1 to _instances\n drawers = fn DrawersArray\n if ( fn RandomResult( drawers ) ) then randomTotal++\n if ( fn OptimalResult( drawers ) ) then optimalTotal++\n next\n \n dispatchmain\n TimerInvalidate( timer )\n \n cls\n print @\"Prisoners: \"_prisoners\n print @\"Instances: \"_instances\n printf @\"Random - fail: %ld, success: %ld (%.2f%%)\",_instances-randomTotal,randomTotal,(double)randomTotal/(double)_instances*100.0\n printf @\"Optimal - fail: %ld, success: %ld (%.2f%%)\\n\",_instances-optimalTotal,optimalTotal,(double)optimalTotal/(double)_instances*100.0\n \n printf @\"Compute time:\u00a0%.3f\\n\",sTime\n dispatchend\n \n dispatchend\nend fn\n\nrandom\n\nwindow 1, @\"100 Prisoners\"\n\nfn DoIt\n\nHandleEvents", "safe": true }, { "filename": "100 prisoners_66.txt", "content": "Prisoners: 100\nInstances: 10000\nRandom - fail: 10000, success: 0 (0.00%)\nOptimal - fail: 6896, success: 3104 (31.04%)\n\nCompute time: 7.856\n", "safe": true }, { "filename": "100 prisoners_67.txt", "content": "' Gambas module file\n\nPublic DrawerArray As Long[]\nPublic NumberFromDrawer As Long\nPublic FoundOwnNumber As Long\n\nPublic Sub Main()\n \n Dim NumberOfPrisoners As Long\n Dim Selections As Long\n Dim Tries As Long\n \n Print \"Number of prisoners (default, 100)?\"\n Try Input NumberOfPrisoners\n If Error Then NumberOfPrisoners = 100\n \n Print \"Number of selections (default, half of prisoners)?\" \n Try Input Selections\n If Error Then Selections = NumberOfPrisoners / 2\n \n Print \"Number of tries (default, 1000)?\"\n Try Input Tries\n If Error Then Tries = 1000\n \n Dim AllFoundOptimal As Long = 0\n Dim AllFoundRandom As Long = 0\n Dim AllFoundRandomMem As Long = 0\n \n Dim i As Long\n Dim OptimalCount As Long\n Dim RandomCount As Long\n Dim RandomMenCount As Long\n \n Dim fStart As Float = Timer\n \n For i = 1 To Tries\n OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections)\n RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections)\n RandomMenCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)\n \n If OptimalCount = NumberOfPrisoners Then AllFoundOptimal += 1\n If RandomCount = NumberOfPrisoners Then AllFoundRandom += 1\n If RandomMenCount = NumberOfPrisoners Then AllFoundRandomMem += 1\n Next\n \n Dim fTime As Float = Timer - fStart\n fTime = Round(ftime, -1)\n \n Print\n Print \"Result with \" & NumberOfPrisoners & \" prisoners, \" & Selections & \" selections and \" & Tries & \" tries. \"\n Print\n Print \"Optimal: \" & AllFoundOptimal & \" of \" & Tries & \": \" & Str(AllFoundOptimal / Tries * 100) & \"\u00a0%\"\n Print \"Random: \" & AllFoundRandom & \" of \" & Tries & \": \" & Str(AllFoundRandom / Tries * 100) & \"\u00a0%\"\n Print \"RandomMem: \" & AllFoundRandomMem & \" of \" & Tries & \": \" & Str(AllFoundRandomMem / Tries * 100) & \"\u00a0%\"\n Print\n Print \"Elapsed Time: \" & fTime & \" sec\"\n Print\n Print \"Trials/sec: \" & Round(Tries / fTime, -1)\n \nEnd\n\nFunction HundredPrisoners_Optimal(NrPrisoners As Long, NrSelections As Long) As Long\n \n DrawerArray = New Long[NrPrisoners]\n Dim Counter As Long\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n If j = 1 Then NumberFromDrawer = DrawerArray[i - 1]\n \n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n\nFunction HundredPrisoners_Random(NrPrisoners As Long, NrSelections As Long) As Long\n \n Dim RandomDrawer As Long\n Dim Counter As Long\n \n DrawerArray = New Long[NrPrisoners]\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n Randomize\n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n RandomDrawer = CLong(Rand(NrPrisoners - 1))\n NumberFromDrawer = DrawerArray[RandomDrawer]\n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n\nFunction HundredPrisoners_Random_Mem(NrPrisoners As Long, NrSelections As Long) As Long\n \n Dim SelectionArray As New Long[NrPrisoners]\n Dim Counter As Long\n \n DrawerArray = New Long[NrPrisoners]\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n \n Next\n \n For Counter = 0 To SelectionArray.Max\n SelectionArray[Counter] = Counter + 1\n \n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n For i = 1 To NrPrisoners\n SelectionArray.Shuffle()\n For j = 1 To NrSelections\n NumberFromDrawer = DrawerArray[SelectionArray[j - 1] - 1]\n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n", "safe": true }, { "filename": "100 prisoners_68.txt", "content": "Number of prisoners (default, 100)?\n100\nNumber of selections (default, half of prisoners)?\n50\nNumber of tries (default, 1000)?\n\n\nResult with 100 prisoners, 50 selections and 1000 tries. \n\nOptimal: 311 of 1000: 31,1\u00a0%\nRandom: 0 of 1000: 0\u00a0%\nRandomMem: 0 of 1000: 0\u00a0%\n\nElapsed Time: 8.7 sec\n\nTrials/sec: 114.9", "safe": true }, { "filename": "100 prisoners_69.txt", "content": "extends MainLoop\n\n\nenum Strategy {Random, Optimal}\n\nconst prisoner_count := 100\n\n\nfunc get_random_drawers() -> Array[int]:\n\tvar drawers: Array[int] = []\n\tdrawers.resize(prisoner_count)\n\tfor i in range(0, prisoner_count):\n\t\tdrawers[i] = i + 1\n\tdrawers.shuffle()\n\treturn drawers\n\n\nvar random_strategy = func(drawers: Array[int], prisoner: int) -> bool:\n\t# Randomly selecting 50 drawers is equivalent to shuffling and picking the first 50\n\tvar drawerCopy: Array[int] = drawers.duplicate()\n\tdrawerCopy.shuffle()\n\tfor i in range(50):\n\t\tif drawers[drawerCopy[i]-1] == prisoner:\n\t\t\treturn true\n\treturn false\n\n\nvar optimal_strategy = func(drawers: Array[int], prisoner: int) -> bool:\n\tvar choice: int = prisoner\n\tfor _i in range(50):\n\t\tvar drawer_value: int = drawers[choice-1]\n\t\tif drawer_value == prisoner:\n\t\t\treturn true\n\t\tchoice = drawer_value\n\treturn false\n\n\nfunc play_all(drawers: Array[int], strategy: Callable) -> bool:\n\tfor prisoner in range(1, prisoner_count+1):\n\t\tif not strategy.call(drawers, prisoner):\n\t\t\treturn false\n\treturn true\n\n\nfunc _process(_delta: float) -> bool:\n\t# Constant seed for reproducibility, call randomize() in real use\n\tseed(1234)\n\n\tconst SAMPLE_SIZE: int = 10_000\n\n\tvar random_successes: int = 0\n\tfor i in range(SAMPLE_SIZE):\n\t\tif play_all(get_random_drawers(), random_strategy):\n\t\t\trandom_successes += 1\n\n\tvar optimal_successes: int = 0\n\tfor i in range(SAMPLE_SIZE):\n\t\tif play_all(get_random_drawers(), optimal_strategy):\n\t\t\toptimal_successes += 1\n\n\tprint(\"Random play: %%%f\" % (100.0 * random_successes/SAMPLE_SIZE))\n\tprint(\"Optimal play: %%%f\" % (100.0 * optimal_successes/SAMPLE_SIZE))\n\n\treturn true # Exit\n", "safe": true }, { "filename": "100 prisoners_7.txt", "content": "package Prisoners is\n\n type Win_Percentage is digits 2 range 0.0 .. 100.0;\n type Drawers is array (1 .. 100) of Positive;\n\n function Play_Game\n (Repetitions : in Positive;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Win_Percentage;\n -- Play the game with a specified number of repetitions, the chosen strategy\n -- is passed to this function\n\n function Optimal_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean;\n\n function Random_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean;\n\nend Prisoners;\n", "safe": true }, { "filename": "100 prisoners_70.txt", "content": "Random play: %0.000000\nOptimal play: %31.700000\n", "safe": true }, { "filename": "100 prisoners_71.txt", "content": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// Uses 0-based numbering rather than 1-based numbering throughout.\nfunc doTrials(trials, np int, strategy string) {\n pardoned := 0\ntrial:\n for t := 0; t < trials; t++ {\n var drawers [100]int\n for i := 0; i < 100; i++ {\n drawers[i] = i\n }\n rand.Shuffle(100, func(i, j int) {\n drawers[i], drawers[j] = drawers[j], drawers[i]\n })\n prisoner:\n for p := 0; p < np; p++ {\n if strategy == \"optimal\" {\n prev := p\n for d := 0; d < 50; d++ {\n this := drawers[prev]\n if this == p {\n continue prisoner\n }\n prev = this\n }\n } else {\n // Assumes a prisoner remembers previous drawers (s)he opened\n // and chooses at random from the others.\n var opened [100]bool\n for d := 0; d < 50; d++ {\n var n int\n for {\n n = rand.Intn(100)\n if !opened[n] {\n opened[n] = true\n break\n }\n }\n if drawers[n] == p {\n continue prisoner\n }\n }\n }\n continue trial\n }\n pardoned++\n }\n rf := float64(pardoned) / float64(trials) * 100\n fmt.Printf(\" strategy =\u00a0%-7s pardoned =\u00a0%-6d relative frequency = %5.2f%%\\n\\n\", strategy, pardoned, rf)\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n const trials = 100000\n for _, np := range []int{10, 100} {\n fmt.Printf(\"Results from %d trials with %d prisoners:\\n\\n\", trials, np)\n for _, strategy := range [2]string{\"random\", \"optimal\"} {\n doTrials(trials, np, strategy)\n }\n }\n}\n", "safe": true }, { "filename": "100 prisoners_72.txt", "content": "Results from 100000 trials with 10 prisoners:\n\n strategy = random pardoned = 99 relative frequency = 0.10%\n\n strategy = optimal pardoned = 31205 relative frequency = 31.20%\n\nResults from 100000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00%\n\n strategy = optimal pardoned = 31154 relative frequency = 31.15%\n", "safe": true }, { "filename": "100 prisoners_73.txt", "content": "import java.util.function.Function\nimport java.util.stream.Collectors\nimport java.util.stream.IntStream\n\nclass Prisoners {\n private static boolean playOptimal(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(secretList)\n\n prisoner:\n for (int i = 0; i < secretList.size(); ++i) {\n int prev = i\n for (int j = 0; j < secretList.size() / 2; ++j) {\n if (secretList.get(prev) == i) {\n continue prisoner\n }\n prev = secretList.get(prev)\n }\n return false\n }\n return true\n }\n\n private static boolean playRandom(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(secretList)\n\n prisoner:\n for (Integer i\u00a0: secretList) {\n List trialList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(trialList)\n\n for (int j = 0; j < trialList.size() / 2; ++j) {\n if (Objects.equals(trialList.get(j), i)) {\n continue prisoner\n }\n }\n\n return false\n }\n return true\n }\n\n private static double exec(int n, int p, Function play) {\n int succ = 0\n for (int i = 0; i < n; ++i) {\n if (play.apply(p)) {\n succ++\n }\n }\n return (succ * 100.0) / n\n }\n\n static void main(String[] args) {\n final int n = 100_000\n final int p = 100\n System.out.printf(\"# of executions: %d\\n\", n)\n System.out.printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, Prisoners.&playOptimal))\n System.out.printf(\"Random play success rate: %f%%\\n\", exec(n, p, Prisoners.&playRandom))\n }\n}\n", "safe": true }, { "filename": "100 prisoners_74.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.215000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100 prisoners_75.txt", "content": "import System.Random\nimport Control.Monad.State\n\nnumRuns = 10000\nnumPrisoners = 100\nnumDrawerTries = 50\ntype Drawers = [Int]\ntype Prisoner = Int\ntype Prisoners = [Int]\n\nmain = do\n gen <- getStdGen\n putStrLn $ \"Chance of winning when choosing randomly: \" ++ (show $ evalState runRandomly gen)\n putStrLn $ \"Chance of winning when choosing optimally: \" ++ (show $ evalState runOptimally gen)\n\n\nrunRandomly :: State StdGen Double\nrunRandomly =\n let runResults = replicateM numRuns $ do\n drawers <- state $ shuffle [1..numPrisoners]\n allM (\\prisoner -> openDrawersRandomly drawers prisoner numDrawerTries) [1..numPrisoners]\n in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults\n\nopenDrawersRandomly :: Drawers -> Prisoner -> Int -> State StdGen Bool\nopenDrawersRandomly drawers prisoner triesLeft = go triesLeft []\n where go 0 _ = return False\n go triesLeft seenDrawers = do\n try <- state $ randomR (1, numPrisoners)\n case try of\n x | x == prisoner -> return True\n | x `elem` seenDrawers -> go triesLeft seenDrawers\n | otherwise -> go (triesLeft - 1) (x:seenDrawers)\n\nrunOptimally :: State StdGen Double\nrunOptimally =\n let runResults = replicateM numRuns $ do\n drawers <- state $ shuffle [1..numPrisoners]\n return $ all (\\prisoner -> openDrawersOptimally drawers prisoner numDrawerTries) [1..numPrisoners]\n in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults\n\nopenDrawersOptimally :: Drawers -> Prisoner -> Int -> Bool\nopenDrawersOptimally drawers prisoner triesLeft = go triesLeft prisoner\n where go 0 _ = False\n go triesLeft drawerToTry =\n let thisDrawer = drawers !! (drawerToTry - 1)\n in if thisDrawer == prisoner then True else go (triesLeft - 1) thisDrawer\n\n\n-- Haskel stdlib is lacking big time, so here some necessary 'library' functions\n\n-- make a list of 'len' random values in range 'range' from 'gen'\nrandomLR :: Integral a => Random b => a -> (b, b) -> StdGen -> ([b], StdGen)\nrandomLR 0 range gen = ([], gen)\nrandomLR len range gen =\n let (x, newGen) = randomR range gen\n (xs, lastGen) = randomLR (len - 1) range newGen\n in (x : xs, lastGen)\n\n\n-- shuffle a list by a generator\nshuffle :: [a] -> StdGen -> ([a], StdGen)\nshuffle list gen = (shuffleByNumbers numbers list, finalGen)\n where\n n = length list\n (numbers, finalGen) = randomLR n (0, n-1) gen\n shuffleByNumbers :: [Int] -> [a] -> [a]\n shuffleByNumbers [] _ = []\n shuffleByNumbers _ [] = []\n shuffleByNumbers (i:is) xs = let (start, x:rest) = splitAt (i `mod` length xs) xs\n in x : shuffleByNumbers is (start ++ rest)\n\n-- short-circuit monadic all\nallM :: Monad m => (a -> m Bool) -> [a] -> m Bool\nallM func [] = return True\nallM func (x:xs) = func x >>= \\res -> if res then allM func xs else return False\n", "safe": true }, { "filename": "100 prisoners_76.txt", "content": "Chance of winning when choosing randomly: 0.0\nChance of winning when choosing optimally: 0.3188", "safe": true }, { "filename": "100 prisoners_77.txt", "content": "NB. game is solvable by optimal strategy when the length (#) of the\nNB. longest (>./) cycle (C.) is at most 50.\nopt=: 50 >: [: >./ [: > [: #&.> C.\n\nNB. for each prisoner randomly open 50 boxes ((50?100){y) and see if \nNB. the right card is there (p&e.). if not return 0.\nrand=: monad define\nfor_p. i.100 do. if. -.p e.(50?100){y do. 0 return. end.\nend. 1\n)\n\nNB. use both strategies on the same shuffles y times.\nsimulate=: monad define\n'o r'=. y %~ 100 * +/ ((rand,opt)@?~)\"0 y # 100\n('strategy';'win rate'),('random';(\":o),'%'),:'optimal';(\":r),'%'\n)\n", "safe": true }, { "filename": "100 prisoners_78.txt", "content": " simulate 10000000\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502strategy\u2502win rate\u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502random \u25020% \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502optimal \u250231.1816%\u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n", "safe": true }, { "filename": "100 prisoners_79.txt", "content": "(math/seedrandom (os/cryptorand 8))\n\n(defn drawers\n \"create list and shuffle it\"\n [prisoners]\n (var x (seq [i :range [0 prisoners]] i))\n (loop [i :down [(- prisoners 1) 0]]\n (var j (math/floor (* (math/random) (+ i 1))))\n (var k (get x i))\n (put x i (get x j))\n (put x j k))\n x)\n\n(defn optimal-play\n \"optimal decision path\"\n [prisoners drawers]\n (var result 0)\n (loop [i :range [0 prisoners]]\n (var choice i)\n (loop [j :range [0 50] :until (= (get drawers choice) i)]\n (set choice (get drawers choice)))\n (cond\n (= (get drawers choice) i) (++ result)\n (break)))\n result)\n\n(defn random-play\n \"random decision path\"\n [prisoners d]\n (var result 0)\n (var options (drawers prisoners))\n (loop [i :range [0 prisoners]]\n (var choice 0)\n (loop [j :range [0 (/ prisoners 2)] :until (= (get d j) (get options i))]\n (set choice j))\n (cond\n (= (get d choice) (get options i)) (++ result)\n (break)))\n result)\n\n(defn main [& args]\n (def prisoners 100)\n (var optimal-success 0)\n (var random-success 0)\n (var sims 10000)\n (for i 0 sims\n (var d (drawers prisoners))\n (if (= (optimal-play prisoners d) prisoners)\n (++ optimal-success))\n (if (= (random-play prisoners d) prisoners)\n (++ random-success)))\n (printf \"Simulation count: %d\" sims)\n (printf \"Optimal play wins:\u00a0%.1f%%\" (* (/ optimal-success sims) 100))\n (printf \"Random play wins: \u00a0%.1f%%\" (* (/ random-success sims) 100)))", "safe": true }, { "filename": "100 prisoners_8.txt", "content": "pragma Ada_2012;\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO; use Ada.Text_IO;\n\npackage body Prisoners is\n\n subtype Drawer_Range is Positive range 1 .. 100;\n package Random_Drawer is new Ada.Numerics.Discrete_Random (Drawer_Range);\n use Random_Drawer;\n \n -- Helper procedures to initialise and shuffle the drawers\n \n procedure Swap (A, B : Positive; Cupboard : in out Drawers) is\n Temp : Positive;\n begin\n Temp := Cupboard (B);\n Cupboard (B) := Cupboard (A);\n Cupboard (A) := Temp;\n end Swap;\n\n procedure Shuffle (Cupboard : in out Drawers) is\n G : Generator;\n begin\n Reset (G);\n for I in Cupboard'Range loop\n Swap (I, Random (G), Cupboard);\n end loop;\n end Shuffle;\n\n procedure Initialise_Drawers (Cupboard : in out Drawers) is\n begin\n for I in Cupboard'Range loop\n Cupboard (I) := I;\n end loop;\n Shuffle (Cupboard);\n end Initialise_Drawers;\n \n -- The two strategies for playing the game\n\n function Optimal_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean\n is\n Current_Card : Positive;\n begin\n Current_Card := Cupboard (Prisoner_Number);\n if Current_Card = Prisoner_Number then\n return True;\n else\n for I in Integer range 1 .. Max_Attempts loop\n Current_Card := Cupboard (Current_Card);\n if Current_Card = Prisoner_Number then\n return True;\n end if;\n end loop;\n end if;\n return False;\n end Optimal_Strategy;\n\n function Random_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean\n is\n Current_Card : Positive;\n G : Generator;\n begin\n Reset (G);\n Current_Card := Cupboard (Prisoner_Number);\n if Current_Card = Prisoner_Number then\n return True;\n else\n for I in Integer range 1 .. Max_Attempts loop\n Current_Card := Cupboard (Random (G));\n if Current_Card = Prisoner_Number then\n return True;\n end if;\n end loop;\n end if;\n return False;\n end Random_Strategy;\n\n function Prisoners_Attempts\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Boolean\n is\n begin\n for Prisoner_Number in Integer range 1 .. Max_Prisoners loop\n if not Strategy\n (Cupboard, Max_Prisoners, Max_Attempts, Prisoner_Number)\n then\n return False;\n end if;\n end loop;\n return True;\n end Prisoners_Attempts;\n \n -- The function to play the game itself\n\n function Play_Game\n (Repetitions : in Positive;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Win_Percentage\n is\n Cupboard : Drawers;\n Win, Game_Count : Natural := 0;\n Number_Of_Prisoners : constant Integer := 100;\n Max_Attempts : constant Integer := 50;\n begin\n loop\n Initialise_Drawers (Cupboard);\n if Prisoners_Attempts\n (Cupboard => Cupboard, Max_Prisoners => Number_Of_Prisoners,\n Max_Attempts => Max_Attempts, Strategy => Strategy)\n then\n Win := Win + 1;\n end if;\n Game_Count := Game_Count + 1;\n exit when Game_Count = Repetitions;\n end loop;\n return Win_Percentage ((Float (Win) / Float (Repetitions)) * 100.0);\n end Play_Game;\n\nend Prisoners;\n", "safe": true }, { "filename": "100 prisoners_80.txt", "content": "Simulation count: 10000\nOptimal play wins: 33.1%\nRandom play wins: 0.0%\n", "safe": true }, { "filename": "100 prisoners_81.txt", "content": "import java.util.Collections;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n private static boolean playOptimal(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (int i = 0; i < secretList.size(); ++i) {\n int prev = i;\n for (int j = 0; j < secretList.size() / 2; ++j) {\n if (secretList.get(prev) == i) {\n continue prisoner;\n }\n prev = secretList.get(prev);\n }\n return false;\n }\n return true;\n }\n\n private static boolean playRandom(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (Integer i : secretList) {\n List trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(trialList);\n\n for (int j = 0; j < trialList.size() / 2; ++j) {\n if (Objects.equals(trialList.get(j), i)) {\n continue prisoner;\n }\n }\n\n return false;\n }\n return true;\n }\n\n private static double exec(int n, int p, Function play) {\n int succ = 0;\n for (int i = 0; i < n; ++i) {\n if (play.apply(p)) {\n succ++;\n }\n }\n return (succ * 100.0) / n;\n }\n\n public static void main(String[] args) {\n final int n = 100_000;\n final int p = 100;\n System.out.printf(\"# of executions: %d\\n\", n);\n System.out.printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, Main::playOptimal));\n System.out.printf(\"Random play success rate: %f%%\\n\", exec(n, p, Main::playRandom));\n }\n}\n", "safe": true }, { "filename": "100 prisoners_82.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.343000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100 prisoners_83.txt", "content": "const _ = require('lodash');\n\nconst numPlays = 100000;\n\nconst setupSecrets = () => {\n\t// setup the drawers with random cards\n\tlet secrets = [];\n\n\tfor (let i = 0; i < 100; i++) {\n\t\tsecrets.push(i);\n\t}\n\n\treturn _.shuffle(secrets);\n}\n\nconst playOptimal = () => {\n\t\n\tlet secrets = setupSecrets();\n\t\n\n\t// Iterate once per prisoner\n\tloop1:\n\tfor (let p = 0; p < 100; p++) {\n\t\t\n\t\t// whether the prisoner succeedss\n\t\tlet success = false;\n\t\t\n\t\t// the drawer number the prisoner chose\n\t\tlet choice = p;\n\t\t\n\t\t\n\t\t// The prisoner can choose up to 50 cards\n\t\tloop2:\n\t\tfor (let i = 0; i < 50; i++) {\n\t\t\t\n\t\t\t// if the card in the drawer that the prisoner chose is his card\n\t\t\tif (secrets[choice] === p){\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak loop2;\n\t\t\t}\n\n\t\t\t// the next drawer the prisoner chooses will be the number of the card he has.\n\t\t\tchoice = secrets[choice];\n\t\t\n\t\t}\t// each prisoner gets 50 chances\n\n\t\t\n\t\tif (!success) return false;\n\n\t} // iterate for each prisoner \n\n\treturn true;\n}\n\nconst playRandom = () => {\n\n\tlet secrets = setupSecrets();\n\n\t// iterate for each prisoner \n\tfor (let p = 0; p < 100; p++) {\n\n\t\tlet choices = setupSecrets();\n\t\t\n\t\tlet success = false;\n\t\t\n\t\tfor (let i = 0; i < 50; i++) {\n\n\t\t\tif (choices[i] === p) {\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!success) return false;\n\t}\n\n\treturn true;\n}\n\nconst execOptimal = () => {\n\n\tlet success = 0;\n\t\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playOptimal()) success++;\n\t\t\t\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconst execRandom = () => {\n\n\tlet success = 0;\n\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playRandom()) success++;\n\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconsole.log(\"# of executions: \" + numPlays);\nconsole.log(\"Optimal Play Success Rate: \" + execOptimal());\nconsole.log(\"Random Play Success Rate: \" + execRandom());\n", "safe": true }, { "filename": "100 prisoners_84.txt", "content": "\"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}\n", "safe": true }, { "filename": "100 prisoners_85.txt", "content": "Games count: 2000\nProbability of success with \"random\" strategy: 0\nProbability of success with \"optimal\" strategy: 33.2", "safe": true }, { "filename": "100 prisoners_86.txt", "content": "export LC_ALL=C\n< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq\n", "safe": true }, { "filename": "100 prisoners_87.txt", "content": "def count(s): reduce s as $x (0; .+1);\n\n# Output: a PRN in range(0;$n) where $n is .\ndef prn:\n if . == 1 then 0\n else . as $n\n | (($n-1)|tostring|length) as $w\n | [limit($w; inputs)] | join(\"\") | tonumber\n | if . < $n then . else ($n | prn) end\n end;\n\ndef knuthShuffle:\n length as $n\n | if $n <= 1 then .\n else {i: $n, a: .}\n | until(.i == 0;\n .i += -1\n | (.i + 1 | prn) as $j\n | .a[.i] as $t\n | .a[.i] = .a[$j]\n | .a[$j] = $t)\n | .a \n end;", "safe": true }, { "filename": "100 prisoners_88.txt", "content": "# Output: if all the prisoners succeed, emit true, otherwise false\ndef optimalStrategy($drawers; np):\n # Does prisoner $p succeed?\n def succeeds($p):\n first( foreach range(0; np/2) as $d ({prev: $p};\n .curr = ($drawers[.prev])\n | if .curr == $p\n then .success = true\n else .prev = .curr\n end;\n select(.success))) // false;\n \n all( range(0; np); succeeds(.) );\n \n# Output: if all the prisoners succeed, emit true, otherwise false\ndef randomStrategy($drawers; np):\n (np/2) as $maxd\n # Does prisoner $p succeed?\n | def succeeds($p):\n {success: false }\n | first(.d = 0\n | .opened = []\n | until( (.d >= $maxd) or .success;\n (np|prn) as $n\n | if .opened[$n] then .\n else .opened[$n] = true\n | .d += 1\n | .success = $drawers[$n] == $p\n end )\n | select(.success) ) // false;\n\n all( range(0; np); succeeds(.) );\n\n\ndef run(strategy; trials; np):\n count(range(0; trials)\n | ([range(0;np)] | knuthShuffle) as $drawers\n | select (if strategy == \"optimal\"\n then optimalStrategy($drawers; np)\n else randomStrategy($drawers; np)\n end ) );\n\ndef task($trials):\n def percent: \"\\(10000 * . | round / 100)%\";\n def summary(strategy):\n \"With \\(strategy) strategy: pardoned = \\(.), relative frequency = \\(./$trials | percent)\";\n\n (10, 100) as $np\n | \"Results from \\($trials) trials with \\($np) prisoners:\",\n (run(\"random\"; $trials; $np) | summary(\"random\")),\n (run(\"optimal\"; $trials; $np) | summary(\"optimal\")),\n \"\"\n;\n\ntask(100000)", "safe": true }, { "filename": "100 prisoners_89.txt", "content": "Results from 100000 trials with 10 prisoners:\nWith random strategy: pardoned = 92, relative frequency = 0.09%\nWith optimal strategy: pardoned = 31212, relative frequency = 31.21%\n\nResults from 100000 trials with 100 prisoners:\nWith random strategy: pardoned = 0, relative frequency = 0%\nWith optimal strategy: pardoned = 31026, relative frequency = 31.03%\n", "safe": true }, { "filename": "100 prisoners_9.txt", "content": "with Prisoners; use Prisoners;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Main is\n Wins : Win_Percentage;\n package Win_Percentage_IO is new Float_IO (Win_Percentage);\nbegin\n Wins := Play_Game (100_000, Optimal_Strategy'Access);\n Put (\"Optimal Strategy = \");\n Win_Percentage_IO.Put (Wins, 2, 2, 0);\n Put (\"%\");\n New_Line;\n Wins := Play_Game (100_000, Random_Strategy'Access);\n Put (\"Random Strategy = \");\n Win_Percentage_IO.Put (Wins, 2, 2, 0);\n Put (\"%\");\nend Main;\n", "safe": true }, { "filename": "100 prisoners_90.txt", "content": "using Random, Formatting\n\nfunction randomplay(n, numprisoners=100)\n pardoned, indrawer, found = 0, collect(1:numprisoners), false\n for i in 1:n\n shuffle!(indrawer)\n for prisoner in 1:numprisoners\n found = false\n for reveal in randperm(numprisoners)[1:div(numprisoners, 2)]\n indrawer[reveal] == prisoner && (found = true) && break\n end\n !found && break\n end\n found && (pardoned += 1)\n end\n return 100.0 * pardoned / n\nend\n\nfunction optimalplay(n, numprisoners=100)\n pardoned, indrawer, found = 0, collect(1:numprisoners), false\n for i in 1:n\n shuffle!(indrawer)\n for prisoner in 1:numprisoners\n reveal = prisoner\n found = false\n for j in 1:div(numprisoners, 2)\n card = indrawer[reveal]\n card == prisoner && (found = true) && break\n reveal = card\n end\n !found && break\n end\n found && (pardoned += 1)\n end\n return 100.0 * pardoned / n\n end\n\nconst N = 100_000\nprintln(\"Simulation count: $N\")\nprintln(\"Random play wins: \", format(randomplay(N), precision=8), \"% of simulations.\")\nprintln(\"Optimal play wins: \", format(optimalplay(N), precision=8), \"% of simulations.\")\n", "safe": true }, { "filename": "100 prisoners_91.txt", "content": "Simulation count: 100000\nRandom play wins: 0.00000000% of simulations.\nOptimal play wins: 31.18100000% of simulations.\n", "safe": true }, { "filename": "100 prisoners_92.txt", "content": "import std/num/random\n\nvalue struct drawer\n num: int\n open: bool = False\n\ninline extern unsafe-assign : forall ( v : vector, i : ssize_t, x : a ) -> total ()\n c \"kk_vector_unsafe_assign\"\n\nfun createDrawers()\n val drawers = vector(100, Drawer(0,open=True))\n for(0, 99) fn(i)\n var found := False\n while {!found}\n val r = random-int() % 100\n if drawers[r].open then\n drawers.unsafe-assign(r.ssize_t, Drawer(i))\n found := True\n else\n ()\n drawers\n\nfun closeAll(d:vector)\n for(0,99) fn(i)\n d.unsafe-assign(i.ssize_t, d[i](open=False))\n\neffect fail\n final ctl failed(): a \n\nfun open-random(drawers: vector)\n val r = random-int() % 100\n val opened = drawers[r]\n if opened.open then\n open-random(drawers)\n else\n drawers.unsafe-assign(r.ssize_t, opened(open=True))\n opened.num\n\nfun random-approach(drawers: vector)\n for(0, 99) fn(i)\n var found := False\n for(0, 49) fn(j)\n val opened = open-random(drawers)\n if opened == i then\n found := True\n else\n ()\n if !found then\n failed()\n else\n drawers.closeAll()\n\nfun optimal-approach(drawers: vector)\n for(0, 99) fn(i)\n var found := False\n var drawer := i;\n for(0, 49) fn(j)\n val opened = drawers[drawer]\n if opened.open then\n failed()\n if opened.num == i then\n found := True\n else\n drawers.unsafe-assign(drawer.ssize_t, opened(open=True))\n drawer := opened.num\n if !found then\n failed()\n else\n drawers.closeAll()\n ()\n\nfun run-trials(f, num-trials)\n var num_success := 0\n for(0,num-trials - 1) fn(i)\n val drawers = createDrawers()\n with handler\n return(x) -> \n num_success := num_success + 1\n final ctl failed() -> \n ()\n f(drawers)\n num_success\n\nfun main()\n val num_trials = 1000\n val num_success_random = run-trials(random-approach, num_trials)\n val num_success_optimal = run-trials(optimal-approach, num_trials)\n println(\"Number of trials: \" ++ num_trials.show)\n println(\"Random approach: wins \" ++ num_success_random.show ++ \" (\" ++ (num_success_random.float64 * 100.0 / num_trials.float64).show(2) ++ \"%)\")\n println(\"Optimal approach: wins \" ++ num_success_optimal.show ++ \" (\" ++ (num_success_optimal.float64 * 100.0 / num_trials.float64).show(2) ++ \"%)\")\n", "safe": true }, { "filename": "100 prisoners_93.txt", "content": "Number of trials: 1000\nRandom approach: wins 0 (0.00%)\nOptimal approach: wins 319 (31.90%)\n", "safe": true }, { "filename": "100 prisoners_94.txt", "content": "val playOptimal: () -> Boolean = {\n val secrets = (0..99).toMutableList()\n var ret = true\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n var prev = i\n draw@ for(j in 0 until 50){\n if (secrets[prev] == i) continue@prisoner\n prev = secrets[prev]\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nval playRandom: ()->Boolean = {\n var ret = true\n val secrets = (0..99).toMutableList()\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n val opened = mutableListOf()\n val genNum : () ->Int = {\n var r = (0..99).random()\n while (opened.contains(r)) {\n r = (0..99).random()\n }\n r\n }\n for(j in 0 until 50){\n val draw = genNum()\n if ( secrets[draw] == i) continue@prisoner\n opened.add(draw)\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nfun exec(n:Int, play:()->Boolean):Double{\n var succ = 0\n for (i in IntRange(0, n-1)){\n succ += if(play()) 1 else 0\n }\n return (succ*100.0)/n\n}\n\nfun main() {\n val N = 100_000\n println(\"# of executions: $N\")\n println(\"Optimal play success rate: ${exec(N, playOptimal)}%\")\n println(\"Random play success rate: ${exec(N, playRandom)}%\")\n}\n", "safe": true }, { "filename": "100 prisoners_95.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.451%\nRandom play success rate: 0.0%\n", "safe": true }, { "filename": "100 prisoners_96.txt", "content": "function shuffle(tbl)\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\n return tbl\nend\n\nfunction playOptimal()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local success = false\n\n local choice = p\n for i=1,50 do\n if secrets[choice] == p then\n success = true\n break\n end\n choice = secrets[choice]\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction playRandom()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local choices = {}\n for i=1,100 do\n choices[i] = i\n end\n shuffle(choices)\n\n local success = false\n for i=1,50 do\n if choices[i] == p then\n success = true\n break\n end\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction exec(n,play)\n local success = 0\n for i=1,n do\n if play() then\n success = success + 1\n end\n end\n return 100.0 * success / n\nend\n\nfunction main()\n local N = 1000000\n print(\"# of executions: \"..N)\n print(string.format(\"Optimal play success rate: %f\", exec(N, playOptimal)))\n print(string.format(\"Random play success rate: %f\", exec(N, playRandom)))\nend\n\nmain()\n", "safe": true }, { "filename": "100 prisoners_97.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.237500\nRandom play success rate: 0.000000", "safe": true }, { "filename": "100 prisoners_98.txt", "content": "p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));\n# p=1/2", "safe": true }, { "filename": "100 prisoners_99.txt", "content": "p^100;\nevalf(%);\n\n# 1/1267650600228229401496703205376\n# 7.888609052e-31", "safe": true }, { "filename": "100_doors_1.txt", "content": "V doors = [0B] * 100\nL(i) 100\n L(j) (i .< 100).step(i + 1)\n doors[j] = !doors[j]\n print(\u2018Door \u2019(i + 1)\u2018: \u2019(I doors[i] {\u2018open\u2019} E \u2018close\u2019))", "safe": true }, { "filename": "100_doors_10.txt", "content": "page:\tequ\t2\t; Store doors in page 2\ndoors:\tequ\t100\t; 100 doors\nputs:\tequ\t9\t; CP/M string output\n\torg\t100h\n\txra\ta\t; Set all doors to zero\n\tlxi\th,256*page\n\tmvi\tc,doors\nzero:\tmov\tm,a\n\tinx\th\n\tdcr\tc\n\tjnz\tzero\n\tmvi\tm,'$'\t; CP/M string terminator (for easier output later)\n\tmov\td,a\t; D=0 so that DE=E=pass counter\n\tmov\te,a\t; E=0, first pass\n\tmvi\ta,doors-1\t; Last pass and door\npass:\tmov\tl,e\t; L=door counter, start at first door in pass\ndoor:\tinr\tm\t; Incrementing always toggles the low bit\n\tdad\td\t; Go to next door in pass\n\tinr\tl\n\tcmp\tl\t; Was this the last door?\n\tjnc\tdoor\t; If not, do the next door\n\tinr\te\t; Next pass\n\tcmp\te\t; Was this the last pass?\n\tjnc\tpass\t; If not, do the next pass\n\tlxi\th,256*page\n\tmvi\tc,doors\t; Door counter\n\tlxi\td,130h\t; D=1 (low bit), E=30h (ascii 0)\nchar:\tmov\ta,m\t; Get door\t\n\tana\td\t; Low bit gives door status\n\tora\te\t; ASCII 0 or 1\n\tmov\tm,a\t; Write character back\n\tinx\th\t; Next door\n\tdcr\tc\t; Any doors left?\n\tjnz\tchar\t; If so, next door\n\tlxi\td,256*page\n\tmvi\tc,puts\t; CP/M system call to print the string\n\tjmp\t5", "safe": true }, { "filename": "100_doors_100.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=I TO 100 STEP I\n40 LET D(J)=NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I,\n90 NEXT I\n", "safe": true }, { "filename": "100_doors_101.txt", "content": "@echo off\nsetlocal enableDelayedExpansion\n:: 0 = closed\n:: 1 = open\n:: SET /A treats undefined variable as 0\n:: Negation operator\u00a0! must be escaped because delayed expansion is enabled\nfor /l %%p in (1 1 100) do for /l %%d in (%%p %%p 100) do set /a \"door%%d=^!door%%d\"\nfor /l %%d in (1 1 100) do if !door%%d!==1 (\n echo door %%d is open\n) else echo door %%d is closed\n", "safe": true }, { "filename": "100_doors_102.txt", "content": "@echo off\nsetlocal enableDelayedExpansion\nset /a square=1, incr=3\nfor /l %%d in (1 1 100) do (\n if %%d neq !square! (echo door %%d is closed) else (\n echo door %%d is open\n set /a square+=incr, incr+=2\n )\n)\n", "safe": true }, { "filename": "100_doors_103.txt", "content": "DIM doors%(100)\nFOR pass% = 1 TO 100\n FOR door% = pass% TO 100 STEP pass%\n doors%(door%) = NOT doors%(door%)\n NEXT door%\nNEXT pass% \nFOR door% = 1 TO 100\n IF doors%(door%) PRINT \"Door \" ; door% \" is open\"\nNEXT door%\n", "safe": true }, { "filename": "100_doors_104.txt", "content": "/* 0 means door is closed, 1 means door is open */\nfor (i = 0; i < 100; i++) {\n for (j = i; j < 100; j += (i + 1)) {\n d[j] = 1 - d[j] /* Toggle door */\n }\n}\n\n\"Open doors:\n\"\nfor (i = 0; i < 100; i++) {\n if (d[i] == 1) (i + 1)\n}\n", "safe": true }, { "filename": "100_doors_105.txt", "content": "get \"libhdr\"\n\nlet start() be \n$( let doors = vec 100\n\n // close all doors\n for n = 1 to 100 do doors!n\u00a0:= 0\n\n // make 100 passes\n for pass = 1 to 100 do\n $( let n = pass\n while n <= 100 do\n $( doors!n\u00a0:= ~doors!n\n n\u00a0:= n + pass\n $)\n $)\n \n // report which doors are open\n for n = 1 to 100 do\n if doors!n then\n writef(\"Door %N is open.*N\", n)\n$)", "safe": true }, { "filename": "100_doors_106.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_107.txt", "content": ">\"d\">:00p1-:>:::9%\\9/9+g2%!\\:9v\n$.v_^#!$::$_^#`\"c\":+g00p+9/9\\%<\n::<_@#`$:\\*:+55:+1p27g1g+9/9\\%9\n", "safe": true }, { "filename": "100_doors_108.txt", "content": "1+:::*.9`#@_\n", "safe": true }, { "filename": "100_doors_109.txt", "content": "108p0>:18p;;>:9g!18g9p08g]\n*`!0\\|+relet|-1`*aap81::+]\n;::+1$08g1+:08paa[\n*`#@_^._aa\n", "safe": true }, { "filename": "100_doors_11.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100_doors_110.txt", "content": "0001000100010101000110100000010110000011001110110010100011010000000000101111111000000101111101011001011001000110100001111100110100101111101111000000001011111111110110011001111111011100000000101111110000001011111010110011011100101011000000101111011001011110011110011110110100000000001011011100111011110000000001000000111001110100000000101101110110", "safe": true }, { "filename": "100_doors_111.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100_doors_112.txt", "content": "var doors = [false] * 100\nfor i in 0..100 {\n iter var j = i; j < 100; j += i + 1 {\n doors[j] = !doors[j]\n }\n var state = doors[i]\u00a0? 'open'\u00a0: 'closed'\n echo 'Door ${i + 1} is ${state}'\n}", "safe": true }, { "filename": "100_doors_113.txt", "content": "for i in 1..101 {\n echo 'Door ${i} is ${i ** 0.5\u00a0% 1 > 0\u00a0? \"closed\"\u00a0: \"open\"}'\n}", "safe": true }, { "filename": "100_doors_114.txt", "content": "for i in 1..11 echo 'Door ${i**2} is open'", "safe": true }, { "filename": "100_doors_115.txt", "content": "Graphics 640,480\ni=1\nWhile ((i*i)<=100)\n\ta$=i*i\n\tDrawText a$,10,20*i\n\tPrint i*i\n\ti=i+1 \nWend\nFlip \nWaitKey\n", "safe": true }, { "filename": "100_doors_116.txt", "content": "DEFINE PROCEDURE ''DIVIDE'' [A,B]:\nBLOCK 0: BEGIN\n IF A < B, THEN:\n QUIT BLOCK 0;\n CELL(0) <= 1;\n OUTPUT <= 1;\n LOOP AT MOST A TIMES:\n BLOCK 2: BEGIN\n IF OUTPUT * B = A, THEN:\n QUIT BLOCK 0;\n OUTPUT <= OUTPUT + 1;\n IF OUTPUT * B > A, THEN:\n BLOCK 3: BEGIN\n OUTPUT <= CELL(0);\n QUIT BLOCK 0;\n BLOCK 3: END;\n CELL(0) <= OUTPUT;\n BLOCK 2: END;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''MINUS'' [A,B]:\nBLOCK 0: BEGIN\n IF A < B, THEN:\n QUIT BLOCK 0;\n LOOP AT MOST A TIMES:\n BLOCK 1: BEGIN\n IF OUTPUT + B = A, THEN:\n QUIT BLOCK 0;\n OUTPUT <= OUTPUT + 1;\n BLOCK 1: END;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''MODULUS'' [A,B]:\nBLOCK 0: BEGIN\n CELL(0) <= DIVIDE[A,B];\n OUTPUT <= MINUS[A,CELL(0) * B];\nBLOCK 0: END.\n\n\n\nDEFINE PROCEDURE ''TOGGLE'' [DOOR]:\nBLOCK 0: BEGIN\n IF DOOR = 1, THEN:\n QUIT BLOCK 0;\n OUTPUT <= 1;\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''NUMBERS'' [DOOR, COUNT]:\nBLOCK 0: BEGIN\n CELL(0) <= 1; /*each number*/\n OUTPUT <= 0; /*current door state*/\n \n LOOP COUNT TIMES:\n BLOCK 1: BEGIN\n\n IF MODULUS[DOOR, CELL(0)] = 0, THEN:\n OUTPUT <= TOGGLE[OUTPUT];\n \n CELL(0) <= CELL(0) + 1;\n\n BLOCK 1: END;\n\nBLOCK 0: END.\n\nDEFINE PROCEDURE ''DOORS'' [COUNT]:\nBLOCK 0: BEGIN\n\n CELL(0) <= 1; /*each door*/\n LOOP COUNT TIMES:\n BLOCK 1: BEGIN\n\n CELL(1) <= NUMBERS[CELL(0), COUNT]; /*iterate over the states of this door to get its final state*/\n IF CELL(1) = 1, THEN: /*door state = open*/\n PRINT[CELL(0), ' '];\n \n CELL(0) <= CELL(0) + 1;\n\n BLOCK 1: END;\nBLOCK 0: END.\n\nDOORS[100];", "safe": true }, { "filename": "100_doors_117.txt", "content": " > 1 \n > 4 \n > 9 \n > 16 \n > 25 \n > 36 \n > 49 \n > 64 \n > 81 \n > 100 \n", "safe": true }, { "filename": "100_doors_118.txt", "content": "( 100doors-tbl\n= door step\n . tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }\n & 0:?step\n & whl\n ' ( 1+!step:~>100:?step { ~> means 'not greater than', i.e. 'less than or equal' }\n & 0:?door\n & whl\n ' ( !step+!door:~>100:?door\n & 1+-1*!(!door$doors):?doors { $ sets the current index, which stays the same until explicitly changed. }\n )\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & out\n $ ( door\n !door\n is\n (\u00a0!(!door$doors):1&open\n | closed\n )\n )\n )\n & tbl$(doors.0) { clean up the array }\n)", "safe": true }, { "filename": "100_doors_119.txt", "content": "( 100doors-var\n= step door\n . 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & closed:?!door { this creates a variable and assigns a value 'closed' to it }\n )\n & 0:?step\n & whl\n ' ( 1+!step:~>100:?step\n & 0:?door\n & whl\n ' ( !step+!door:~>100:?door\n & (\u00a0!!door:closed&open\n | closed\n )\n \u00a0:\u00a0?!door \n )\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & out$(door !door is\u00a0!!door)\n )\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & tbl$(!door.0) { cleanup the variable }\n )\n)", "safe": true }, { "filename": "100_doors_12.txt", "content": "\\ Array of doors; init to empty; accessing a non-extant member will return\n\\ 'null', which is treated as 'false', so we don't need to initialize it:\n[] var, doors \n\n\\ given a door number, get the value and toggle it:\n: toggle-door \\ n --\n\tdoors @ over a:@\n\tnot rot swap a:! drop ;\n\n\\ print which doors are open:\n: .doors\n\t( \n\t\tdoors @ over a:@ nip\n\t\tif . space else drop then\n\t) 1 100 loop ;\n\n\\ iterate over the doors, skipping 'n':\n: main-pass \\ n --\n\t0\n\ttrue\n\trepeat\n\t\tdrop\n\t\tdup toggle-door\n\t\tover n:+\n\t\tdup 101 <\n\twhile 2drop drop ;\n\n\\ calculate the first 100 doors:\n' main-pass 1 100 loop\n\\ print the results:\n.doors cr bye\n", "safe": true }, { "filename": "100_doors_120.txt", "content": "( 100doors-list\n= doors door doorIndex step\n . \u00a0:?doors\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & closed !doors:?doors\n )\n & 0:?skip\n & whl\n ' (\u00a0:?ndoors\n & whl\n ' ( !doors:?skipped [!skip\u00a0%?door ?doors { the [ pattern only succeeds when the scanning cursor is at position }\n & !ndoors\n !skipped\n ( !door:open&closed\n | open\n )\n \u00a0: ?ndoors\n )\n & !ndoors !doors:?doors\n & 1+!skip:<100:?skip\n )\n & out$!doors\n)", "safe": true }, { "filename": "100_doors_121.txt", "content": "( 100doors-obj\n= doors door doorIndex step\n . \u00a0:?doors\n & 0:?door\n & whl\n ' ( 1+!door:~>100:?door\n & new$(=closed) !doors:?doors\n )\n & 0:?skip\n & whl\n ' ( !doors:?tododoors\n & whl\n ' ( !tododoors:? [!skip\u00a0%?door ?tododoors\n & (\u00a0!(door.):open&closed\n | open\n )\n \u00a0:\u00a0?(door.)\n )\n & 1+!skip:<100:?skip\n )\n & out$!doors\n)", "safe": true }, { "filename": "100_doors_122.txt", "content": "100doors-tbl$\n& 100doors-var$\n& 100doors-list$\n& 100doors-obj$;", "safe": true }, { "filename": "100_doors_123.txt", "content": "blsq ) 10ro2?^\n{1 4 9 16 25 36 49 64 81 100}", "safe": true }, { "filename": "100_doors_124.txt", "content": "swch \u2190 \u2260\u00b4{100\u294a1\u00ab\ud835\udd69\u294a0}\u00a81+\u2195100\n\u00af1\u2193\u223e{\ud835\udd69\u223e@+10}\u00a8\u2022Fmt\u00a8\u27e8swch,/swch\u27e9\n", "safe": true }, { "filename": "100_doors_125.txt", "content": "\"\u27e8 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \u27e9\n\u27e8 0 3 8 15 24 35 48 63 80 99 \u27e9\"\n", "safe": true }, { "filename": "100_doors_126.txt", "content": "swch\n", "safe": true }, { "filename": "100_doors_127.txt", "content": "#include \n\nint main()\n{\n char is_open[100] = { 0 };\n int pass, door;\n\n /* do the 100 passes */\n for (pass = 0; pass < 100; ++pass)\n for (door = pass; door < 100; door += pass+1)\n is_open[door] = !is_open[door];\n\n /* output the result */\n for (door = 0; door < 100; ++door)\n printf(\"door #%d is %s.\\n\", door+1, (is_open[door]? \"open\" : \"closed\"));\n\n return 0;\n}\n", "safe": true }, { "filename": "100_doors_128.txt", "content": "#include \n\n#define NUM_DOORS 100\n\nint main(int argc, char *argv[])\n{\n int is_open[NUM_DOORS] = { 0 } ;\n int * doorptr, * doorlimit = is_open + NUM_DOORS ;\n int pass ;\n\n /* do the N passes, go backwards because the order is not important */\n for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) {\n for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) {\n ( * doorptr ) ^= 1 ;\n }\n }\n\n /* output results */\n for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) {\n printf(\"door #%lld is %s\\n\", ( doorptr - is_open ) + 1, ( * doorptr ) ? \"open\" : \"closed\" ) ;\n }\n}\n", "safe": true }, { "filename": "100_doors_129.txt", "content": "#include \n\nint main()\n{\n int square = 1, increment = 3, door;\n for (door = 1; door <= 100; ++door)\n {\n printf(\"door #%d\", door);\n if (door == square)\n {\n printf(\" is open.\\n\");\n square += increment;\n increment += 2;\n }\n else\n printf(\" is closed.\\n\");\n }\n return 0;\n}\n", "safe": true }, { "filename": "100_doors_13.txt", "content": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program 100doors64.s */\n \n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"The door @ is open.\\n\"\n \n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \nstTableDoors: .skip 8 * NBDOORS\nsZoneConv: .skip 24\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: // entry of program \n // display first line\n ldr x3,qAdrstTableDoors // table address\n mov x5,1 \n1:\n mov x4,x5\n2: // begin loop\n ldr x2,[x3,x4,lsl #3] // read doors index x4\n cmp x2,#0\n cset x2,eq\n //moveq x2,#1 // if x2 = 0 1 -> x2\n //movne x2,#0 // if x2 = 1 0 -> x2\n str x2,[x3,x4,lsl #3] // store value of doors\n add x4,x4,x5 // increment x4 with x5 value\n cmp x4,NBDOORS // number of doors\u00a0?\n ble 2b // no -> loop\n add x5,x5,#1 // increment the increment\u00a0!!\n cmp x5,NBDOORS // number of doors\u00a0?\n ble 1b // no -> loop\n \n // loop display state doors\n mov x4,#0 \n3:\n ldr x2,[x3,x4,lsl #3] // read state doors x4 index\n cmp x2,#0\n beq 4f\n mov x0,x4 // open -> display message\n ldr x1,qAdrsZoneConv // display value index\n bl conversion10 // call function\n ldr x0,qAdrsMessResult\n ldr x1,qAdrsZoneConv \n bl strInsertAtCharInc // insert result at first @ character\n bl affichageMess // display message\n4:\n add x4,x4,1\n cmp x4,NBDOORS\n ble 3b // loop\n \n \n100: // standard end of the program \n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n \nqAdrstTableDoors: .quad stTableDoors\nqAdrsMessResult: .quad sMessResult\nqAdrsZoneConv: .quad sZoneConv\n/***********************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"", "safe": true }, { "filename": "100_doors_130.txt", "content": "#include \n\nint main()\n{\n int door, square, increment;\n for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2))\n printf(\"door #%d is %s.\\n\", door, (door == square? \"open\" : \"closed\"));\n return 0;\n}\n", "safe": true }, { "filename": "100_doors_131.txt", "content": "#include \n\nint main()\n{\n\tint i;\n\tfor (i = 1; i * i <= 100; i++)\n\t\tprintf(\"door %d open\\n\", i * i);\n\n\treturn 0;\n}\n", "safe": true }, { "filename": "100_doors_132.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main(string[] args)\n {\n bool[] doors = new bool[100];\n\n //Close all doors to start.\n for (int d = 0; d < 100; d++) doors[d] = false;\n\n //For each pass...\n for (int p = 0; p < 100; p++)//number of passes\n {\n //For each door to toggle...\n for (int d = 0; d < 100; d++)//door number\n {\n if ((d + 1) % (p + 1) == 0)\n {\n doors[d] = !doors[d];\n }\n }\n }\n\n //Output the results.\n Console.WriteLine(\"Passes Completed!!! Here are the results: \\r\\n\");\n for (int d = 0; d < 100; d++)\n {\n if (doors[d])\n {\n Console.WriteLine(String.Format(\"Door #{0}: Open\", d + 1));\n }\n else\n {\n Console.WriteLine(String.Format(\"Door #{0}: Closed\", d + 1));\n }\n }\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100_doors_133.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main(string[] args)\n {\n //Perform the operation.\n bool[] doors = new bool[100];\n int n = 0;\n int d;\n while ((d = (++n * n)) <= 100)\n doors[d - 1] = true;\n\n //Perform the presentation.\n for (d = 0; d < doors.Length; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d + 1, doors[d] ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100_doors_134.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main()\n {\n bool[] doors = new bool[100];\n\n //The number of passes can be 1-based, but the number of doors must be 0-based.\n for (int p = 1; p <= 100; p++)\n for (int d = p - 1; d < 100; d += p)\n doors[d] = !doors[d];\n for (int d = 0; d < 100; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d + 1, doors[d] ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100_doors_135.txt", "content": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main()\n {\n double n;\n\n //If the current door number is the perfect square of an integer, say it is open, else say it is closed.\n for (int d = 1; d <= 100; d++)\n Console.WriteLine(\"Door #{0}: {1}\", d, (n = Math.Sqrt(d)) == (int)n ? \"Open\" : \"Closed\");\n Console.ReadKey(true);\n }\n }\n}\n", "safe": true }, { "filename": "100_doors_136.txt", "content": "using System;\nusing System.IO;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n Console.Clear();\n Console.WriteLine(\"Input a number of doors to calculate, then press enter\");\n StartCalculator();\n }\n \n static void StartCalculator()\n {\n //The number to calculate is input here\n string input = Console.ReadLine();\n Console.Clear();\n \n try\n {\n //The program attempts to convert the string to an int\n //Exceptions will be caught on this line\n int numberOfDoors = Convert.ToInt32(input);\n \n //Will call method recursively if input number is less than 1\n if (numberOfDoors <= 0)\n {\n Console.WriteLine(\"Please use a number greater than 0\");\n StartCalculator();\n }\n \n //The program then starts the calculation process\n Calculate(numberOfDoors);\n \n //After calculation process is finished, restart method is called\n RestartCalculator();\n }\n catch(FormatException)\n {\n //Code will be executed if the number has a decimal or has an unrecognizable symbol\n Console.WriteLine(\"Unable to read. Please use a real number without a decimal\");\n StartCalculator();\n }\n catch (OverflowException)\n {\n //Code will be executed if number is too long\n Console.WriteLine(\"You number is too long\");\n StartCalculator();\n }\n }\n \n static void Calculate(int numberOfDoors)\n {\n //Increases numberOfDoors by 1 since array starts at 0\n numberOfDoors++;\n \n //Dictionary key represents door number, value represents if the door is open\n //if value == true, the door is open\n Dictionary doors = new Dictionary();\n \n //Creates Dictionary size of numberOfDoors, all initialized at false\n for(int i = 0; i < numberOfDoors; i++)\n {\n doors.Add(i, false);\n }\n \n //Creates interval between doors, starting at 0, while less than numberOfDoors\n for (int doorInterval = 0; doorInterval < numberOfDoors; doorInterval++)\n {\n //Will alter every cubby at doorInterval\n //1 needs to be added since doorInterval will start at 0 and end when equal to numberOfDoors\n for(int i = 0; i < numberOfDoors; i += doorInterval + 1)\n {\n //Changes a false value to true and vice versa\n doors[i] = doors[i] ? false: true;\n }\n }\n \n //Writes each door and whether it is open or closed\n for(int i = 0; i < numberOfDoors; i++)\n {\n //Skips over door 0\n if (i == 0) continue;\n //Writes open if door value is true, writes closed if door value is false\n Console.WriteLine(\"Door \" + (i) + \" is \" + (doors[i] ? \"open\" : \"closed\"));\n }\n }\n \n static void RestartCalculator()\n { \n Console.WriteLine(\"Press any key to restart\");\n Console.ReadKey(true);\n Main();\n }\n}\n", "safe": true }, { "filename": "100_doors_137.txt", "content": "#include \n\nint main()\n{\n bool is_open[100] = { false };\n\n // do the 100 passes\n for (int pass = 0; pass < 100; ++pass)\n for (int door = pass; door < 100; door += pass+1)\n is_open[door] = !is_open[door];\n\n // output the result\n for (int door = 0; door < 100; ++door)\n std::cout << \"door #\" << door+1 << (is_open[door]? \" is open.\" : \" is closed.\") << std::endl;\n return 0;\n}\n", "safe": true }, { "filename": "100_doors_138.txt", "content": "#include \n\nint main()\n{\n int square = 1, increment = 3;\n for (int door = 1; door <= 100; ++door)\n {\n std::cout << \"door #\" << door;\n if (door == square)\n {\n std::cout << \" is open.\" << std::endl;\n square += increment;\n increment += 2;\n }\n else\n std::cout << \" is closed.\" << std::endl;\n }\n return 0;\n}\n", "safe": true }, { "filename": "100_doors_139.txt", "content": "#include //compiled with \"Dev-C++\" , from RaptorOne\n\nint main()\n{\n for(int i=1; i*i<=100; i++)\n std::cout<<\"Door \"< // compiled with clang (tags/RELEASE_600/final)\n#include // or g++ (GCC) 7.3.1 20180406 -- from hare1039\nnamespace functional_list // basic building block for template meta programming\n{\nstruct NIL\n{\n\tusing head = NIL;\n\tusing tail = NIL;\n\tfriend std::ostream& operator << (std::ostream& os, NIL const) { return os; }\n};\n\ntemplate \nstruct list\n{\n\tusing head = H;\n\tusing tail = T;\n};\n\ntemplate \nstruct integer\n{\n\tstatic constexpr int value = i;\n\tfriend std::ostream& operator << (std::ostream& os, integer const) { os << integer::value; return os;}\n};\n\ntemplate constexpr\nauto at()\n{\n\tif constexpr (nTH == 0)\n\t\treturn (typename L::head){};\n\telse if constexpr (not std::is_same_v) \n\t\treturn at();\n\telse\n\t\treturn NIL{};\n}\ntemplate \nusing at_t = decltype(at());\n\ntemplate constexpr\nauto prepend() { return list{}; }\n\ntemplate \nusing prepend_t = decltype(prepend());\n\t\ntemplate > constexpr\nauto gen_list()\n{\n\tif constexpr (Size == 0)\n\t\treturn NIL{};\n\telse\n\t{\n\t\tusing next = decltype(gen_list());\n\t\treturn prepend();\n\t}\n}\ntemplate >\nusing gen_list_t = decltype(gen_list());\n\t\n} namespace fl = functional_list;\n\nconstexpr int door_amount = 101; // index from 1 to 100\n\ntemplate constexpr\nauto construct_loop()\n{\n\tusing val_t = fl::at_t;\n\tif constexpr (std::is_same_v)\n\t\treturn fl::NIL{};\n\telse\n\t{\n\t\tconstexpr int val = val_t::value;\n\t\tusing val_add_t = fl::integer;\n\t\tusing val_old_t = fl::integer;\n\t\n\t\tif constexpr (current == door_amount)\n\t\t{\n\t\t\tif constexpr(current % moder == 0)\n\t\t\t\treturn fl::list{};\n\t\t\telse\n\t\t\t\treturn fl::list{};\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusing sub_list = decltype(construct_loop());\n\t\t\tif constexpr(current % moder == 0)\n\t\t\t\treturn fl::prepend();\n\t\t\telse\n\t\t\t\treturn fl::prepend();\n\t\t}\n\t}\n}\n\ntemplate constexpr\nauto construct()\n{\n\tif constexpr (iteration == 1) // door index = 1\n\t{\n\t\tusing l = fl::gen_list_t;\n\t\treturn construct_loop();\n\t}\n\telse\n\t{\n\t\tusing prev_iter_list = decltype(construct());\n\t\treturn construct_loop();\n\t}\n}\n\ntemplate constexpr\nvoid show_ans()\n{\n\tif constexpr (std::is_same_v)\n\t\treturn;\n\telse\n\t{\n\t\tif constexpr (L::head::value % 2 == 1)\n\t\t\tstd::cout << \"Door \" << pos << \" is opened.\\n\";\n\t\tshow_ans();\n\t}\n}\n\nint main()\n{\n\tusing result = decltype(construct<100>());\n\tshow_ans();\n}\n", "safe": true }, { "filename": "100_doors_141.txt", "content": "100_doors\n", "safe": true }, { "filename": "100_doors_142.txt", "content": " for i=1:1:100 {\n\t set doors(i) = 0\n }\n for i=1:1:100 {\n\t for door=i:i:100 {\n\t\t Set doors(door)='doors(door)\n\t }\n }\n for i = 1:1:100\n {\n\tif doors(i)=1 write i_\": open\",!\n }\n", "safe": true }, { "filename": "100_doors_143.txt", "content": "1: open\n4: open\n9: open\n16: open\n25: open\n36: open\n49: open\n64: open\n81: open\n100: open\n", "safe": true }, { "filename": "100_doors_144.txt", "content": "shared void run() {\n print(\"Open doors (naive): ``naive()``\n Open doors (optimized): ``optimized()``\");\n \n}\n\nshared {Integer*} naive(Integer count = 100) {\n variable value doors = [ for (_ in 1..count) closed ];\n for (step in 1..count) {\n doors = [for (i->door in doors.indexed) let (index = i+1) if (step == 1 || step.divides(index)) then door.toggle() else door ];\n }\n return doors.indexesWhere((door) => door == opened).map(1.plusInteger);\n}\n\nshared {Integer*} optimized(Integer count = 100) =>\n { for (i in 1..count) i*i }.takeWhile(count.notSmallerThan);\n\n\nshared abstract class Door(shared actual String string) of opened | closed {\n shared formal Door toggle();\n}\nobject opened extends Door(\"opened\") { toggle() => closed; }\nobject closed extends Door(\"closed\") { toggle() => opened; }\n", "safe": true }, { "filename": "100_doors_145.txt", "content": "Open doors (naive): { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }\nOpen doors (optimized): { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }", "safe": true }, { "filename": "100_doors_146.txt", "content": " program\n\n map\n end\n\nMAX_DOOR_NUMBER equate(100)\nCRLF equate('<13,10>')\n\nDoors byte,dim(MAX_DOOR_NUMBER)\nPass byte\nDoorNumber byte\nDisplayString cstring(2000)\n\nResultWindow window('Result'),at(,,133,291),center,double,auto\n prompt('Door states:'),at(8,4),use(?PromptTitle)\n text,at(8,16,116,266),use(DisplayString),boxed,vscroll,font('Courier New',,,,CHARSET:ANSI),readonly\n end\n\n code\n\n Doors\u00a0:=: false\n loop Pass = 1 to MAX_DOOR_NUMBER\n loop DoorNumber = Pass to MAX_DOOR_NUMBER by Pass\n Doors[DoorNumber] = choose(Doors[DoorNumber], false, true)\n end\n end\n\n clear(DisplayString)\n loop DoorNumber = 1 to MAX_DOOR_NUMBER\n DisplayString = DisplayString & format(DoorNumber, @n3) & ' is ' & choose(Doors[DoorNumber], 'opened', 'closed') & CRLF\n end\n open(ResultWindow)\n accept\n end\n close(ResultWindow)\n\n return", "safe": true }, { "filename": "100_doors_147.txt", "content": "fn visit-doors doors step:\n if step > 100: doors\n else:\n [1:100]\n -> * fn index:\n if index\u00a0% step: doors[(index - 1)]\n else: not doors[(index - 1)]\n -> visit-doors (step + 1)\n\n[1:100] -> * n: false -> visit-doors 1 => doors\n[1:100] -> * (@eager) fn i:\n doors[(i - 1)]\n -> if = true: #open\n else: #closed\n -> print #Door i #is @", "safe": true }, { "filename": "100_doors_148.txt", "content": "[1:100] -> * (@eager) fn i:\n i ^ 0.5\n -> eq @ (transform i: floor)\n -> if = true: #open\n else: #closed\n -> print #Door i #is @", "safe": true }, { "filename": "100_doors_149.txt", "content": "(deffacts initial-state\n (door-count 100)\n)\n\n(deffunction toggle\n (?state)\n (switch ?state\n (case \"open\" then \"closed\")\n (case \"closed\" then \"open\")\n )\n)\n\n(defrule create-doors-and-visits\n (door-count ?count)\n =>\n (loop-for-count (?num 1 ?count) do\n (assert (door ?num \"closed\"))\n (assert (visit-from ?num ?num))\n )\n (assert (doors initialized))\n)\n\n(defrule visit\n (door-count ?max)\n ?visit <- (visit-from ?num ?step)\n ?door <- (door ?num ?state)\n =>\n (retract ?visit)\n (retract ?door)\n (assert (door ?num (toggle ?state)))\n (if\n (<= (+ ?num ?step) ?max)\n then\n (assert (visit-from (+ ?num ?step) ?step))\n )\n)\n\n(defrule start-printing\n (doors initialized)\n (not (visit-from\u00a0?\u00a0?))\n =>\n (printout t \"These doors are open:\" crlf)\n (assert (print-from 1))\n)\n\n(defrule print-door\n (door-count ?max)\n ?pf <- (print-from ?num)\n (door ?num ?state)\n =>\n (retract ?pf)\n (if\n (= 0 (str-compare \"open\" ?state))\n then\n (printout t ?num \" \")\n )\n (if\n (< ?num ?max)\n then\n (assert (print-from (+ ?num 1)))\n else\n (printout t crlf \"All other doors are closed.\" crlf)\n )\n)", "safe": true }, { "filename": "100_doors_15.txt", "content": "form open_doors_unopt.\n data: lv_door type i,\n lv_count type i value 1.\n data: lt_doors type standard table of c initial size 100.\n field-symbols: type c.\n do 100 times.\n append initial line to lt_doors assigning .\n = 'X'.\n enddo.\n\n while lv_count < 100.\n lv_count = lv_count + 1.\n lv_door = lv_count.\n while lv_door < 100.\n read table lt_doors index lv_door assigning .\n if = ' '.\n = 'X'.\n else.\n = ' '.\n endif.\n add lv_count to lv_door.\n endwhile.\n endwhile.\n\n loop at lt_doors assigning .\n if = 'X'.\n write : / 'Door', (4) sy-tabix right-justified, 'is open' no-gap.\n endif.\n endloop.\nendform.\n", "safe": true }, { "filename": "100_doors_150.txt", "content": "(deffacts initial-state\n (door-count 100)\n)\n\n(deffunction is-square\n (?num)\n (= (sqrt ?num) (integer (sqrt ?num)))\n)\n\n(defrule check-doors\n (door-count ?count)\n =>\n (printout t \"These doors are open:\" crlf)\n (loop-for-count (?num 1 ?count) do\n (if (is-square ?num) then\n (printout t ?num \" \")\n )\n )\n (printout t crlf \"All other doors are closed.\" crlf)\n)", "safe": true }, { "filename": "100_doors_151.txt", "content": "(defn doors []\n (let [doors (into-array (repeat 100 false))]\n (doseq [pass (range 1 101) \n i (range (dec pass) 100 pass) ]\n (aset doors i (not (aget doors i))))\n doors)) \n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100_doors_152.txt", "content": "(defn doors []\n (reduce (fn [doors toggle-idx] (update-in doors [toggle-idx] not))\n (into [] (repeat 100 false))\n (for [pass (range 1 101)\n i (range (dec pass) 100 pass) ]\n i)))\n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100_doors_153.txt", "content": "(defn open-doors []\n (->> (for [step (range 1 101), occ (range step 101 step)] occ)\n frequencies\n (filter (comp odd? val))\n keys\n sort))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100_doors_154.txt", "content": "(defn doors []\n\t(reduce (fn [doors idx] (assoc doors idx true)) \n\t (into [] (repeat 100 false))\n\t (map #(dec (* % %)) (range 1 11))))\n\n(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100_doors_155.txt", "content": "(defn open-doors [] (->> (iterate inc 1) (map #(* % %)) (take-while #(<= % 100))))\n\n(defn print-open-doors []\n (println \n \"Open doors after 100 passes:\"\n (apply str (interpose \", \" (open-doors)))))\n", "safe": true }, { "filename": "100_doors_156.txt", "content": "start_up = proc ()\n max = 100\n po: stream\u00a0:= stream$primary_output()\n open: array[bool]\u00a0:= array[bool]$fill(1, max, false)\n\n for pass: int in int$from_to(1, max) do\n for door: int in int$from_to_by(pass, max, pass) do\n open[door]\u00a0:= ~open[door]\n end\n end\n\n for door: int in array[bool]$indexes(open) do\n if open[door] then\n stream$putl(po, \"Door \" || int$unparse(door) || \" is open.\")\n end\n end\nend start_up", "safe": true }, { "filename": "100_doors_157.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_158.txt", "content": " IDENTIFICATION DIVISION.\n PROGRAM-ID. 100Doors.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 Current-n PIC 9(3).\n 01 StepSize PIC 9(3).\n 01 DoorTable.\n 02 Doors PIC 9(1) OCCURS 100 TIMES.\n 88 ClosedDoor VALUE ZERO.\n 01 Idx PIC 9(3).\n\n PROCEDURE DIVISION.\n Begin.\n INITIALIZE DoorTable\n PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100\n PERFORM VARYING Current-n FROM StepSize BY StepSize\n UNTIL Current-n > 100\n SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n)\n END-PERFORM\n END-PERFORM\n\n PERFORM VARYING Idx FROM 1 BY 1\n UNTIL Idx > 100\n IF ClosedDoor (Idx)\n DISPLAY Idx \" is closed.\"\n ELSE\n DISPLAY Idx \" is open.\"\n END-IF\n END-PERFORM\n\n STOP RUN\n .\n", "safe": true }, { "filename": "100_doors_159.txt", "content": "doors = [false] * 100\n\nfor pass til doors.length\n for i from pass til doors.length by pass + 1\n \u00a0! = doors[i]\n\nfor i til doors.length\n console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed'", "safe": true }, { "filename": "100_doors_16.txt", "content": "cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab\n aux TYPE i\n FOR door = 1 WHILE door <= 100\n FOR pass = 1 WHILE pass <= 100\n NEXT aux = COND #( WHEN pass = 1 THEN 1\n WHEN door MOD pass = 0 THEN aux + 1 ELSE aux )\n list = COND #( WHEN pass = 100\n THEN COND #( WHEN aux MOD 2 <> 0 THEN VALUE #( BASE list ( CONV #( door ) ) )\n ELSE list ) ELSE list ) ) ).\n", "safe": true }, { "filename": "100_doors_160.txt", "content": "doors = []\n \nfor pass in [1..100]\n for i in [pass..100] by pass\n doors[i] = !doors[i]\n \nconsole.log \"Doors #{index for index, open of doors when open} are open\"\n \n# matrix output\nconsole.log doors.map (open) -> +open\n", "safe": true }, { "filename": "100_doors_161.txt", "content": "isInteger = (i) -> Math.floor(i) == i\n\nconsole.log door for door in [1..100] when isInteger Math.sqrt door\n", "safe": true }, { "filename": "100_doors_162.txt", "content": "console.log Math.pow(i,2) for i in [1..10]\n", "safe": true }, { "filename": "100_doors_163.txt", "content": "\tdoorCount = 1;\n\tdoorList = \"\";\n\t// create all doors and set all doors to open\n\twhile (doorCount LTE 100) {\n\t\tdoorList = ListAppend(doorList,\"1\");\n\t\tdoorCount = doorCount + 1;\n\t}\n\tloopCount = 2;\n\tdoorListLen = ListLen(doorList);\n\twhile (loopCount LTE 100) {\n\t\tloopDoorListCount = 1;\n\t\twhile (loopDoorListCount LTE 100) {\n\t\t\ttestDoor = loopDoorListCount / loopCount;\n\t\t\tif (testDoor EQ Int(testDoor)) {\n\t\t\t\tcheckOpen = ListGetAt(doorList,loopDoorListCount);\n\t\t\t\tif (checkOpen EQ 1) {\n\t\t\t\t\tdoorList = ListSetAt(doorList,loopDoorListCount,\"0\");\n\t\t\t\t} else {\n\t\t\t\t\tdoorList = ListSetAt(doorList,loopDoorListCount,\"1\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tloopDoorListCount = loopDoorListCount + 1;\n\t\t}\n\t\tloopCount = loopCount + 1;\n\t}", "safe": true }, { "filename": "100_doors_164.txt", "content": "\tdoorCount = 1;\n\tdoorList = \"\";\n\tloopCount = 1;\n\twhile (loopCount LTE 100) {\n\t\tif (Sqr(loopCount) NEQ Int(Sqr(loopCount))) {\n\t\t\tdoorList = ListAppend(doorList,0);\n\t\t} else {\n\t\t\tdoorList = ListAppend(doorList,1);\n\t\t}\n\t\tloopCount = loopCount + 1;\n\t}", "safe": true }, { "filename": "100_doors_165.txt", "content": "// Display all doors\n\n Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#
\n
\n\n// Output only open doors\n\n \n #x#
\n
\n
\n", "safe": true }, { "filename": "100_doors_166.txt", "content": "\n\n \n\n\n \n \n \n \n \n \n \n\n#doorlist#\n", "safe": true }, { "filename": "100_doors_167.txt", "content": "0010 DIM doors#(100)\n0020 FOR pass#:=1 TO 100 DO\n0030 FOR door#:=pass# TO 100 STEP pass# DO doors#(door#):=NOT doors#(door#)\n0040 ENDFOR pass#\n0050 FOR door#:=1 TO 100 DO\n0060 IF doors#(door#) THEN PRINT \"Door \",door#,\" is open.\"\n0070 ENDFOR door#\n0080 END\n", "safe": true }, { "filename": "100_doors_168.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_169.txt", "content": "10 D=100: DIMD(D): P=1\n20 PRINT CHR$(147);\"PASS: \";P\n22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT\n30 IF P=100 THEN 40\n32 P=P+1: GOTO20\n40 PRINT: PRINT\"THE FOLLOWING DOORS ARE OPEN: \"\n42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI;\n44 NEXT\n", "safe": true }, { "filename": "100_doors_17.txt", "content": "form open_doors_opt.\n data: lv_square type i value 1,\n lv_inc type i value 3.\n data: lt_doors type standard table of c initial size 100.\n field-symbols: type c.\n do 100 times.\n append initial line to lt_doors assigning .\n if sy-index = lv_square.\n = 'X'.\n add: lv_inc to lv_square, 2 to lv_inc.\n write : / 'Door', (4) sy-index right-justified, 'is open' no-gap.\n endif.\n enddo.\nendform.\n", "safe": true }, { "filename": "100_doors_170.txt", "content": "(defun visit-door (doors doornum value1 value2)\n \"visits a door, swapping the value1 to value2 or vice-versa\"\n (let ((d (copy-list doors))\n (n (- doornum 1)))\n (if (eql (nth n d) value1)\n (setf (nth n d) value2)\n (setf (nth n d) value1))\n d))\n\n(defun visit-every (doors num iter value1 value2)\n \"visits every 'num' door in the list\"\n (if (> (* iter num) (length doors))\n doors\n (visit-every (visit-door doors (* num iter) value1 value2)\n num\n (+ 1 iter)\n value1\n value2)))\n\n(defun do-all-visits (doors cnt value1 value2)\n \"Visits all doors changing the values accordingly\"\n (if (< cnt 1)\n doors\n (do-all-visits (visit-every doors cnt 1 value1 value2)\n (- cnt 1)\n value1\n value2)))\n\n(defun print-doors (doors)\n \"Pretty prints the doors list\"\n (format T \"~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%\" doors))\n\n(defun start (&optional (size 100))\n \"Start the program\"\n (let* ((open \"_\")\n (shut \"#\")\n (doors (make-list size :initial-element shut)))\n (print-doors (do-all-visits doors size open shut))))\n", "safe": true }, { "filename": "100_doors_171.txt", "content": "(define-modify-macro toggle () not)\n\n(defun 100-doors ()\n (let ((doors (make-array 100)))\n (dotimes (i 100)\n (loop for j from i below 100 by (1+ i)\n\t do (toggle (svref doors j))))\n (dotimes (i 100)\n (format t \"door ~a: ~:[closed~;open~]~%\" (1+ i) (svref doors i)))))\n", "safe": true }, { "filename": "100_doors_172.txt", "content": "(defun doors (z &optional (w (make-list z)) (n 1))\n (if (> n z) w (doors z (toggle w n z) (1+ n))))\n\n(defun toggle (w m z)\n (loop for a in w for n from 1 to z\n collect (if (zerop (mod n m)) (not a) a)))\n\n> (doors 100)\n(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)\n", "safe": true }, { "filename": "100_doors_173.txt", "content": "(defun doors (n)\n (loop for a from 1 to n collect\n (zerop (mod (sqrt a) 1))))\n \n> (doors 100)\n(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)\n", "safe": true }, { "filename": "100_doors_174.txt", "content": "(defun 100-doors ()\n (let ((doors (make-array 100)))\n (dotimes (i 10)\n (setf (svref doors (* i i)) t))\n (dotimes (i 100)\n (format t \"door ~a: ~:[closed~;open~]~%\" (1+ i) (svref doors i)))))\n", "safe": true }, { "filename": "100_doors_175.txt", "content": "(defun perfect-square-list (n) \n \"Generates a list of perfect squares from 0 up to n\"\n (loop for i from 1 to (isqrt n) collect (expt i 2))) \n \n(defun print-doors (doors)\n \"Pretty prints the doors list\"\n (format T \"~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%\" doors))\n\n(defun open-door (doors num open)\n \"Sets door at num to open\"\n (setf (nth (- num 1) doors) open)) \n\n(defun visit-all (doors vlist open)\n \"Visits and opens all the doors indicated in vlist\"\n (dolist (dn vlist doors)\n (open-door doors dn open)))\n\n(defun start2 (&optional (size 100)) \n \"Start the program\"\n (print-doors\n (visit-all (make-list size :initial-element '\\#)\n (perfect-square-list size)\n '_)))\n", "safe": true }, { "filename": "100_doors_176.txt", "content": "(let ((i 0))\n (mapcar (lambda (x)\n (if (zerop (mod (sqrt (incf i)) 1))\n \"_\" \"#\"))\n (make-list 100)))\n", "safe": true }, { "filename": "100_doors_177.txt", "content": "MODULE Doors100;\nIMPORT StdLog;\n\nPROCEDURE Do*;\nVAR\n\ti,j: INTEGER;\n\tclosed: ARRAY 101 OF BOOLEAN;\nBEGIN\n\t(* initialization of closed to true *)\n\tFOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END;\n\t(* process *)\n\tFOR i := 1 TO LEN(closed) DO;\n\t\tj := 1;\n\t\tWHILE j < LEN(closed) DO\n\t\t\tIF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j)\n\t\tEND\n\tEND;\n\t(* print results *)\n\ti := 1;\n\tWHILE i < LEN(closed) DO\n\t\tIF (i - 1) MOD 10 = 0 THEN StdLog.Ln END;\n\t\tIF closed[i] THEN StdLog.String(\"C \") ELSE StdLog.String(\"O \") END;\n\t\tINC(i) \n\tEND;\nEND Do;\nEND Doors100.\n", "safe": true }, { "filename": "100_doors_178.txt", "content": "O C C O C C C C O C \nC C C C C O C C C C \nC C C C O C C C C C \nC C C C C O C C C C \nC C C C C C C C O C \nC C C C C C C C C C \nC C C O C C C C C C \nC C C C C C C C C C \nO C C C C C C C C C \nC C C C C C C C C O \n", "safe": true }, { "filename": "100_doors_179.txt", "content": "Require Import List.\n\nFixpoint rep {A} (a : A) n :=\n match n with\n | O => nil\n | S n' => a::(rep a n')\n end.\n\nFixpoint flip (l : list bool) (n k : nat) : list bool :=\n match l with\n | nil => nil\n | cons h t => match k with\n | O => (negb h) :: (flip t n n)\n | S k' => h :: (flip t n k')\n end\n end.\n\nDefinition flipeach l n := flip l n n.\n\nFixpoint flipwhile l n :=\n match n with\n | O => flipeach l 0\n | S n' => flipwhile (flipeach l (S n')) n'\n end.\n\nDefinition prison cells := flipwhile (rep false cells) cells.\n", "safe": true }, { "filename": "100_doors_18.txt", "content": "DO 10 TIMES.\n DATA(val) = sy-index * sy-index.\n WRITE: / val.\nENDDO.\n", "safe": true }, { "filename": "100_doors_180.txt", "content": "Require Import List.\n\nFixpoint prisoo' nd n k accu :=\n match nd with\n | O => rev accu\n | S nd' => let ra := match k with\n | O => (true, S n, (n + n))\n | S k' => (false, n, k')\n end in\n prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu)\n end.\n\nDefinition prisoo cells := prisoo' cells 1 0 nil.\n", "safe": true }, { "filename": "100_doors_181.txt", "content": "Goal prison 100 = prisoo 100. compute. reflexivity. Qed.", "safe": true }, { "filename": "100_doors_182.txt", "content": "Goal forall n, prison n = prisoo n. Abort.", "safe": true }, { "filename": "100_doors_183.txt", "content": "include \"cowgol.coh\";\n\nvar doors: uint8[101]; # one extra so we can start at 1\nvar pass: @indexof doors;\nvar door: @indexof doors;\n\nMemZero(&doors as [uint8], @bytesof doors);\n\npass\u00a0:= 1;\nwhile pass <= 100 loop\n door\u00a0:= pass;\n while door <= 100 loop\n doors[door]\u00a0:= 1-doors[door];\n door\u00a0:= door + pass;\n end loop;\n pass\u00a0:= pass + 1;\nend loop;\n\ndoor\u00a0:= 1;\nwhile door <= 100 loop\n if doors[door] == 1 then\n print_i8(door);\n print(\" is open\\n\");\n end if;\n door\u00a0:= door + 1;\nend loop;", "safe": true }, { "filename": "100_doors_184.txt", "content": "1 is open\n4 is open\n9 is open\n16 is open\n25 is open\n36 is open\n49 is open\n64 is open\n81 is open\n100 is open", "safe": true }, { "filename": "100_doors_185.txt", "content": "do\n\n\tlet i = i + 1\n\tprint i * i, \" \",\n\nloop i * i < 100", "safe": true }, { "filename": "100_doors_186.txt", "content": "1 4 9 16 25 36 49 64 81 100 ", "safe": true }, { "filename": "100_doors_187.txt", "content": "doors = Array.new(100, false)\n\n1.upto(100) do |i|\n i.step(by: i, to: 100) do |j|\n doors[j - 1] = !doors[j - 1]\n end\nend\n\ndoors.each_with_index do |open, i|\n puts \"Door #{i + 1} is #{open\u00a0? \"open\"\u00a0: \"closed\"}\"\nend", "safe": true }, { "filename": "100_doors_188.txt", "content": "import std.stdio;\nconst N = 101; // #doors + 1\nvoid main() {\n bool[N] doors = false;\n for(auto door=1; doordisplay( REDUCE stringtab( INIT list TYPE stringtab\n FOR i = 1 WHILE i <= 10\n NEXT list = VALUE #( BASE list ( i * i ) ) ) ).\n", "safe": true }, { "filename": "100_doors_190.txt", "content": "import std.stdio;\nconst N = 101; // #doors + 1\nvoid main() {\n for( auto door=1,s=3; door open[i - 1]).writeln;\n}", "safe": true }, { "filename": "100_doors_193.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_194.txt", "content": "import std.stdio;\n\nvoid printAllDoors(bool[] doors)\n{\n // Prints the state of all the doors\n foreach(i, door; doors)\n {\n writeln(\"#: \", i + 1, (door)\u00a0? \" open\"\u00a0: \" closed\");\n }\n}\nvoid main()\n{\n bool[100] doors = false; //Create 100 closed doors\n for(int a = 0; a < 100; ++a) {\n writefln(\"Pass #%s; visiting every %s door.\", a + 1, a + 1); // Optional\n\t for(int i = a; i < 100; i += (a + 1)) {\n\t writefln(\"Visited door %s\", i + 1); //Optional\n\t doors[i] = !doors[i];\n\t }\n writeln(); // Optional\n }\n printAllDoors(doors); // Prints the state of each door\n}", "safe": true }, { "filename": "100_doors_195.txt", "content": "datatype Door = Closed | Open\n\nmethod InitializeDoors(n:int) returns (doors:array)\n // Precondition: n must be a valid array size.\n requires n >= 0\n // Postcondition: doors is an array, which is not an alias for any other\n // object, with a length of n, all of whose elements are Closed. The \"fresh\"\n // (non-alias) condition is needed to allow doors to be modified by the\n // remaining code.\n ensures doors\u00a0!= null && fresh(doors) && doors.Length == n\n ensures forall j\u00a0:: 0 <= j < doors.Length ==> doors[j] == Closed;\n{\n doors\u00a0:= new Door[n];\n var i\u00a0:= 0;\n // Invariant: i is always a valid index inside the loop, and all doors less\n // than i are Closed. These invariants are needed to ensure the second\n // postcondition.\n while i < doors.Length\n invariant i <= doors.Length\n invariant forall j\u00a0:: 0 <= j < i ==> doors[j] == Closed;\n {\n doors[i]\u00a0:= Closed;\n i\u00a0:= i + 1;\n }\n}\n\nmethod Main ()\n{\n var doors\u00a0:= InitializeDoors(100);\n\n var pass\u00a0:= 1;\n while pass <= doors.Length\n {\n var door\u00a0:= pass;\n while door < doors.Length\n {\n doors[door]\u00a0:= if doors[door] == Closed then Open else Closed;\n door\u00a0:= door + pass;\n }\n pass\u00a0:= pass + 1;\n }\n var i\u00a0:= 0;\n while i < doors.Length\n {\n print i, \" is \", if doors[i] == Closed then \"closed\\n\" else \"open\\n\";\n i\u00a0:= i + 1;\n }\n}", "safe": true }, { "filename": "100_doors_196.txt", "content": "main() {\n for (var k = 1, x = new List(101); k <= 100; k++) {\n for (int i = k; i <= 100; i += k)\n x[i] = !x[i];\n if (x[k]) print(\"$k open\");\n }\n}", "safe": true }, { "filename": "100_doors_197.txt", "content": "main() {\n for(int i=1,s=3;i<=100;i+=s,s+=2)\n print(\"door $i is open\");\n}", "safe": true }, { "filename": "100_doors_198.txt", "content": "import 'dart:io';\n\nfinal numDoors = 100;\nfinal List doorClosed = List(numDoors);\n\nString stateToString(String message) {\n var res = '';\n for (var i = 0; i < numDoors; i++) {\n res += (doorClosed[i]\u00a0? 'X'\u00a0: '\\u2610');\n }\n return res + \" \" + message;\n}\n\nmain() {\n for (var i = 0; i < numDoors; i++) {\n doorClosed[i] = true;\n }\n stdout.writeln(stateToString(\"after initialization\"));\n for (var step = 1; step <= numDoors; step++) {\n final start = step - 1;\n for (var i = start; i < numDoors; i += step) {\n doorClosed[i] = !doorClosed[i];\n }\n stdout.writeln(stateToString(\"after toggling with step = $step\"));\n }\n}", "safe": true }, { "filename": "100_doors_199.txt", "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX after initialization\n\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610 after toggling with step = 1\n\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X after toggling with step = 2\n\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX after toggling with step = 3\n\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610 after toggling with step = 4\n\u2610XX\u2610X\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610X\u2610\u2610\u2610X\u2610XX\u2610\u2610\u2610XX\u2610X\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XXX after toggling with step = 5\n\u2610XX\u2610XX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XXX\u2610X\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610XX\u2610XX\u2610X\u2610XX\u2610XX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XXX after toggling with step = 6\n\u2610XX\u2610XXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610XXXX\u2610\u2610\u2610\u2610XX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610XXXXX\u2610X\u2610X\u2610\u2610XX\u2610\u2610XX\u2610\u2610\u2610X\u2610\u2610XX\u2610XXX\u2610XXXX\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610XX after toggling with step = 7\n\u2610XX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XX\u2610X\u2610\u2610XX\u2610XX\u2610X\u2610X\u2610XXX\u2610\u2610XX\u2610X\u2610X\u2610\u2610XX\u2610\u2610XX\u2610XXXXX\u2610\u2610X\u2610XXXX\u2610\u2610XX after toggling with step = 8\n\u2610XX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610\u2610\u2610XXX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610XX\u2610X\u2610\u2610\u2610X\u2610XX\u2610X\u2610XXXXX\u2610\u2610XX\u2610\u2610\u2610X\u2610\u2610XX\u2610\u2610\u2610X\u2610XXXXX\u2610XX\u2610XXXX\u2610\u2610\u2610X after toggling with step = 9\n\u2610XX\u2610XXXX\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610\u2610XX\u2610XXXX\u2610\u2610\u2610X\u2610XX\u2610\u2610\u2610XXXXX\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610XX\u2610X\u2610X\u2610XXXXX\u2610\u2610X\u2610XXXX\u2610\u2610\u2610\u2610 after toggling with step = 10\n\u2610XX\u2610XXXX\u2610XX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610XX\u2610\u2610\u2610XXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610XXXX\u2610\u2610\u2610X\u2610XXXX\u2610\u2610X\u2610 after toggling with step = 11\n\u2610XX\u2610XXXX\u2610XXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXXX\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610XXX\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610X\u2610 after toggling with step = 12\n\u2610XX\u2610XXXX\u2610XXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610XXXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610 after toggling with step = 13\n\u2610XX\u2610XXXX\u2610XXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610XXXX\u2610\u2610\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXXX\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610XX\u2610 after toggling with step = 14\n\u2610XX\u2610XXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610XXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610X\u2610X\u2610XXXX\u2610\u2610X\u2610\u2610XXX\u2610\u2610XX\u2610 after toggling with step = 15\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXXXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXXX\u2610\u2610X\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 16\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610X\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 17\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XXXX\u2610XX\u2610 after toggling with step = 18\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XX\u2610 after toggling with step = 19\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610X\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 20\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XX\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 21\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610\u2610XX\u2610X\u2610XXX after toggling with step = 22\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610X\u2610XXX after toggling with step = 23\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX after toggling with step = 24\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 25\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 26\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 27\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610XXX\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 28\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610\u2610\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 29\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610\u2610\u2610XX\u2610 after toggling with step = 30\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610\u2610XX\u2610 after toggling with step = 31\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XX\u2610 after toggling with step = 32\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 33\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 34\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 35\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 36\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 37\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 38\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XXX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 39\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610XX\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 40\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 41\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 42\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 43\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 44\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 45\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610X\u2610\u2610 after toggling with step = 46\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610X\u2610\u2610 after toggling with step = 47\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610 after toggling with step = 48\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610 after toggling with step = 49\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 50\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 51\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 52\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 53\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 54\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 55\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 56\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 57\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 58\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 59\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 60\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 61\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 62\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 63\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 64\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 65\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 66\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 67\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 68\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 69\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 70\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 71\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 72\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 73\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 74\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 75\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 76\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 77\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 78\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 79\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 80\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 81\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610X\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 82\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 83\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 84\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 85\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 86\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 87\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 88\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 89\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 90\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 91\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 92\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610\u2610X after toggling with step = 93\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXX\u2610\u2610\u2610\u2610\u2610X after toggling with step = 94\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610\u2610\u2610\u2610X after toggling with step = 95\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXX\u2610\u2610\u2610X after toggling with step = 96\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610\u2610X after toggling with step = 97\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXX\u2610X after toggling with step = 98\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXXXX after toggling with step = 99\n\u2610XX\u2610XXXX\u2610XXXXXX\u2610XXXXXXXX\u2610XXXXXXXXXX\u2610XXXXXXXXXXXX\u2610XXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXX\u2610XXXXXXXXXXXXXXXXXX\u2610 after toggling with step = 100", "safe": true }, { "filename": "100_doors_2.txt", "content": "* 100 doors 13/08/2015\nHUNDOOR CSECT\n USING HUNDOOR,R12\n LR R12,R15\n LA R6,0\n LA R8,1 step 1\n LA R9,100\nLOOPI BXH R6,R8,ELOOPI do ipass=1 to 100 (R6)\n LR R7,R6\n SR R7,R6\n LR R10,R6 step ipass\n LA R11,100\nLOOPJ BXH R7,R10,ELOOPJ do idoor=ipass to 100 by ipass (R7)\n LA R5,DOORS-1\n AR R5,R7\n XI 0(R5),X'01' doors(idoor)=not(doors(idoor))\nNEXTJ B LOOPJ\nELOOPJ B LOOPI\nELOOPI LA R10,BUFFER R10 address of the buffer\n LA R5,DOORS R5 address of doors item\n LA R6,1 idoor=1 (R6)\n LA R9,100 loop counter\nLOOPN CLI 0(R5),X'01' if doors(idoor)=1\n BNE NEXTN\n XDECO R6,XDEC idoor to decimal\n MVC 0(4,R10),XDEC+8 move decimal to buffer\n LA R10,4(R10)\nNEXTN\t LA R6,1(R6) idoor=idoor+1\n LA R5,1(R5)\n BCT R9,LOOPN loop\nELOOPN XPRNT BUFFER,80\nRETURN XR R15,R15\n BR R14\nDOORS DC 100X'00'\nBUFFER DC CL80' '\nXDEC DS CL12\n YREGS\n END HUNDOOR", "safe": true }, { "filename": "100_doors_20.txt", "content": "HOW TO INITIALIZE:\n SHARE doors\n PUT {} IN doors\n FOR door IN {1..100}:\n PUT 0 IN doors[door]\n\nHOW TO TOGGLE door:\n SHARE doors\n PUT 1-doors[door] IN doors[door]\n\nHOW TO WALK step:\n SHARE doors\n PUT step IN door\n WHILE door <= 100:\n TOGGLE door\n PUT door+step IN door\n\nHOW TO DISPLAY OPEN DOORS:\n SHARE doors\n FOR door IN {1..100}:\n IF doors[door] = 1:\n WRITE \"Door\", door, \"is open\"/\n\nINITIALIZE\nFOR pass IN {1..100}: WALK pass\nDISPLAY OPEN DOORS", "safe": true }, { "filename": "100_doors_200.txt", "content": "## NB: This code uses the dc command \"r\" via register \"r\".\n## You may comment out the unwanted version.\n[SxSyLxLy]sr # this should work with every \"dc\"\n[r]sr # GNU dc can exchange top 2 stack values by \"r\"\n## Now use \"lrx\" instead of \"r\" ...\n\n0k # we work without decimal places\n[q]sq # useful e.g. as loop termination\n\n## (x)(y)>R == if (y)>(x) eval R\n## isle x y --> (x <= y)\n[\n [1q]S. [\u00a0!<. 0 ]x s.L.\n]sl\n## l: isle\n\n[\n 100 llx\n]sL\n## L: isle100\n\n## for initcode condcode incrcode body\n## [1] [2] [3] [4]\n[\n [q]S. 4:. 3:. 2:. 1:. 1;.x [2;.x 0=. 4;.x 3;.x 0;.x]d0:.x Os.L.o\n]sf\n## f: for\n##----------------------------------------------------------------------------\n\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## door[i] = 0;\n## }\n#[init ...]P []ps-\n[1si] [li lLx] [li1+si] [\n li 0:d\n]lfx\n\n## for( s=1\u00a0; s<=100\u00a0; ++s ) {\n## for( i=s\u00a0; i<=100\u00a0; i+=s ) {\n## door[i] = 1 - door[i]\n## }\n## }\n[1ss] [ls lLx] [ls1+ss] [\n #[step ]P lsn [ ...]ps-\n [lssi] [li lLx] [lils+si] [\n 1 li;d - li:d\n ]lfx\n]lfx\n\n## long output:\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## print \"door #\", i, \" is \", (door[i]\u00a0? \"open\"\u00a0: \"closed\")), NL\n## }\n[\n [1si] [li lLx] [li1+si] [\n [door #]P\n li n\n [ is ]P\n [closed]\n [open]\n li;d 0=r lrx s- n\n [.]ps-\n ]lfx\n]\n\n## terse output:\n## for( i=1\u00a0; i<=100\u00a0; ++i ) {\n## if( door[i] ) {\n## print i\n## }\n## print NL\n## }\n[\n [1si] [li lLx] [li1+si] [\n [] [ [ ]n lin ]\n li;d 0=r lrx s- x\n ]lfx\n []ps-\n]\n\nlrx # comment out for the long output version\ns- x\n#[stack rest...]P []ps- f", "safe": true }, { "filename": "100_doors_201.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_202.txt", "content": "$! doors.com\n$! Excecute by running @doors at prompt.\n$ square = 1\n$ incr = 3\n$ count2 = 0\n$ d = 1\n$ LOOP2:\n$ count2 = count2 + 1\n$ IF (d .NE. square)\n$ THEN WRITE SYS$OUTPUT \"door ''d' is closed\"\n$ ELSE WRITE SYS$OUTPUT \"door ''d' is open\"\n$ square = incr + square\n$ incr = incr + 2\n$ ENDIF\n$ d = d + 1\n$ IF (count2 .LT. 100) THEN GOTO LOOP2", "safe": true }, { "filename": "100_doors_203.txt", "content": "proc nonrec main() void:\n byte DOORS = 100;\n [DOORS+1] bool door_open;\n unsigned DOORS i, j;\n\n /* make sure all doors are closed */\n for i from 1 upto DOORS do door_open[i]\u00a0:= false od;\n\n /* pass through the doors */\n for i from 1 upto DOORS do\n for j from i by i upto DOORS do\n door_open[j]\u00a0:= not door_open[j]\n od\n od;\n\n /* show the open doors */\n for i from 1 upto DOORS do\n if door_open[i] then\n writeln(\"Door \", i, \" is open.\")\n fi\n od\ncorp", "safe": true }, { "filename": "100_doors_204.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_205.txt", "content": "100[$][0^:1-]# {initialize doors}\n%\n[s;[$101<][$$;~\\:s;+]#%]d: {function d, switch door state function}\n1s:[s;101<][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}\n1[$101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]# {loop through doors, print door number and state}", "safe": true }, { "filename": "100_doors_206.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n11 closed\n12 closed\n...\n94 closed\n95 closed\n96 closed\n97 closed\n98 closed\n99 closed\n100 open", "safe": true }, { "filename": "100_doors_207.txt", "content": "var doors\u00a0: array [1..100] of Boolean;\nvar i, j\u00a0: Integer;\n\nfor i\u00a0:= 1 to 100 do\n for j\u00a0:= i to 100 do\n if (j mod i) = 0 then\n doors[j]\u00a0:= not doors[j];F\n\nfor i\u00a0:= 1 to 100 do\n if doors[i] then\n PrintLn('Door '+IntToStr(i)+' is open');", "safe": true }, { "filename": "100_doors_208.txt", "content": "var doors = Array.Empty(100, false)\n \nfor p in 0..99 {\n for d in 0..99 {\n if (d + 1)\u00a0% (p + 1) == 0 {\n doors[d] = !doors[d];\n }\n }\n}\n \nfor d in doors.Indices() when doors[d] {\n print(\"Door \\(d+1): Open\")\n}", "safe": true }, { "filename": "100_doors_209.txt", "content": "Door 1: Open\nDoor 4: Open\nDoor 9: Open\nDoor 16: Open\nDoor 25: Open\nDoor 36: Open\nDoor 49: Open\nDoor 64: Open\nDoor 81: Open\nDoor 100: Open", "safe": true }, { "filename": "100_doors_21.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100_doors_210.txt", "content": "define function doors ()\n let n = 100;\n let doors = make(, size: n, fill: #f);\n for (x from 0 below n)\n for (y from x below n by x + 1)\n doors[y]\u00a0:= ~doors[y]\n end\n end;\n format-out(\"open: \");\n for (x from 0 below n) \n if (doors[x]) \n format-out(\"%d \", x + 1)\n end\n end\nend function;", "safe": true }, { "filename": "100_doors_211.txt", "content": "local :open-doors [ rep 101 false ]\n\nfor i range 1 100:\n\tlocal :j i\n\twhile <= j 100:\n\t\tset-to open-doors j not open-doors! j\n\t\tset :j + j i\n\n!print\\ \"Open doors: \"\nfor i range 1 100:\n\tif open-doors! i:\n\t\t!print\\( to-str i \" \" )", "safe": true }, { "filename": "100_doors_212.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100 ", "safe": true }, { "filename": "100_doors_213.txt", "content": "#!/usr/bin/env rune\n\nvar toggles\u00a0:= []\nvar gets\u00a0:= []\n\n# Set up GUI (and data model)\ndef frame\u00a0:= (\"100 doors\")\nframe.getContentPane().setLayout((10, 10))\nfor i in 1..100 {\n def component\u00a0:= (E.toString(i))\n toggles with= fn { component.setSelected(!component.isSelected()) }\n gets with= fn { component.isSelected() }\n frame.getContentPane().add(component)\n}\n\n# Set up termination condition\ndef done\nframe.addWindowListener(def _ {\n to windowClosing(event) {\n bind done\u00a0:= true\n }\n match _ {}\n})\n\n# Open and close doors\ndef loop(step, i) {\n toggles[i] <- ()\n def next\u00a0:= i + step\n timer.whenPast(timer.now() + 10, fn {\n if (next >= 100) {\n if (step >= 100) {\n # Done.\n } else {\n loop <- (step + 1, step)\n }\n } else {\n loop <- (step, i + step)\n } \n })\n}\nloop(1, 0)\n\nframe.pack()\nframe.show()\ninterp.waitAtTop(done)", "safe": true }, { "filename": "100_doors_214.txt", "content": "len d[] 100\nfor p = 1 to 100\n i = p\n while i <= 100\n d[i] = 1 - d[i]\n i += p\n .\n.\nfor i = 1 to 100\n if d[i] = 1\n print i\n .\n.", "safe": true }, { "filename": "100_doors_215.txt", "content": "; initial state = closed = #f\n(define doors (make-vector 101 #f))\n; run pass 100 to 1\n(for* \n ((pass (in-range 100 0 -1)) \n (door (in-range 0 101 pass))) \n (when (and \n (vector-set! doors door (not (vector-ref doors door))) \n (= pass 1)) \n (writeln door \"is open\"))) \n\n1 \"is open\" \n4 \"is open\" \n9 \"is open\" \n16 \"is open\" \n25 \"is open\" \n36 \"is open\" \n49 \"is open\" \n64 \"is open\" \n81 \"is open\" \n100 \"is open\"", "safe": true }, { "filename": "100_doors_216.txt", "content": "Doors\u00a0:= RECORD\n UNSIGNED1 DoorNumber;\n STRING6 State;\nEND;\n\nAllDoors\u00a0:= DATASET([{0,0}],Doors);\n\nDoors OpenThem(AllDoors L,INTEGER Cnt)\u00a0:= TRANSFORM\n SELF.DoorNumber\u00a0:= Cnt;\n SELF.State \u00a0:= IF((CNT * 10)\u00a0% (SQRT(CNT)*10)<>0,'Closed','Opened');\nEND;\n\nOpenDoors\u00a0:= NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));\n \nOpenDoors;", "safe": true }, { "filename": "100_doors_217.txt", "content": "Doors\u00a0:= RECORD\n UNSIGNED1 DoorNumber;\n STRING6 State;\nEND;\n\nAllDoors\u00a0:= DATASET([{0,'0'}],Doors);\n\n//first build the 100 doors\n\nDoors OpenThem(AllDoors L,INTEGER Cnt)\u00a0:= TRANSFORM\n SELF.DoorNumber\u00a0:= Cnt;\n SELF.State \u00a0:= 'Closed';\nEND;\n\nClosedDoors\u00a0:= NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));\n\n//now iterate through them and use door logic\n\nloopBody(DATASET(Doors) ds, UNSIGNED4 c)\u00a0:=\n PROJECT(ds, //ds=original input\n TRANSFORM(Doors,\n \tSELF.State\u00a0:= CASE((COUNTER\u00a0% c) * 100,\n\t\t 0 => IF(LEFT.STATE = 'Opened','Closed','Opened')\n\t\t\t\t\t ,LEFT.STATE);\n\t\t\tSELF.DoorNumber\u00a0:= COUNTER; //PROJECT COUNTER\n ));\n \ng1\u00a0:= LOOP(ClosedDoors,100,loopBody(ROWS(LEFT),COUNTER));\n \nOUTPUT(g1);", "safe": true }, { "filename": "100_doors_218.txt", "content": "DoorSet\u00a0:= DATASET(100,TRANSFORM({UNSIGNED1 DoorState},SELF.DoorState\u00a0:= 1));\nSetDoors\u00a0:= SET(DoorSet,DoorState);\n\nDoors\u00a0:= RECORD\n UNSIGNED1 Pass;\n SET OF UNSIGNED1 DoorSet;\nEND;\n\nStartDoors\u00a0:= DATASET(100,TRANSFORM(Doors,SELF.Pass\u00a0:= COUNTER,SELF.DoorSet\u00a0:= SetDoors));\n\nDoors XF(Doors L, Doors R)\u00a0:= TRANSFORM\n ds\u00a0:= DATASET(L.DoorSet,{UNSIGNED1 DoorState});\n NextDoorSet\u00a0:= PROJECT(ds, \n TRANSFORM({UNSIGNED1 DoorState},\n \t SELF.DoorState\u00a0:= CASE((COUNTER\u00a0% R.Pass) * 100,\n 0 => IF(LEFT.DoorState = 1,0,1),\n LEFT.DoorState)));\n SELF.DoorSet\u00a0:= IF(L.Pass=0,R.DoorSet,SET(NextDoorSet,DoorState));\t\t\t\t\t\t\t\t\t\n SELF.Pass\u00a0:= R.Pass\t\t\t\t\t\t\t\t\t\t\nEND;\t\t\t\t\t\t\t\t\t\t\n \nRes\u00a0:= DATASET(ITERATE(StartDoors,XF(LEFT,RIGHT))[100].DoorSet,{UNSIGNED1 DoorState});\nPROJECT(Res,TRANSFORM({STRING20 txt},SELF.Txt\u00a0:= 'Door ' + COUNTER + ' is ' + IF(LEFT.DoorState=1,'Open','Closed')));", "safe": true }, { "filename": "100_doors_219.txt", "content": "module OneHundredDoors {\n void run() {\n Boolean[] doors = new Boolean[100];\n for (Int pass\u00a0: 0 ..< 100) {\n for (Int door = pass; door < 100; door += 1+pass) {\n doors[door] = !doors[door];\n }\n }\n\n @Inject Console console;\n console.print($|open doors: {doors.mapIndexed((d, i) -> d\u00a0? i+1\u00a0: 0)\n | .filter(i -> i > 0)}\n );\n }\n}", "safe": true }, { "filename": "100_doors_22.txt", "content": "(defun rep (n x)\n (if (zp n)\n nil\n (cons x\n (rep (- n 1) x))))\n\n(defun toggle-every-r (n i bs)\n (if (endp bs)\n nil\n (cons (if (zp i)\n (not (first bs))\n (first bs))\n (toggle-every-r n (mod (1- i) n) (rest bs)))))\n\n(defun toggle-every (n bs)\n (toggle-every-r n (1- n) bs))\n\n(defun 100-doors (i doors)\n (if (zp i)\n doors\n (100-doors (1- i) (toggle-every i doors))))\n", "safe": true }, { "filename": "100_doors_220.txt", "content": "open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100_doors_221.txt", "content": "[Hundred doors problem from Rosetta Code website]\n[EDSAC program, Initial Orders 2]\n\n[Library subroutine M3. Prints header and is then overwritten.\nHere, the last character sets the teleprinter to figures.]\n PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF\n @&*THE!OPEN!DOORS!ARE@&#\n ..PZ [blank tape, needed to mark end of header text]\n\n[Library subroutine P6. Prints strictly positive integer.\n32 locations; working locations 1, 4, 5]\n T56K [define load address for subroutine]\n GKA3FT25@H29@VFT4DA3@TFH30@S6@T1F\n V4DU4DAFG26@TFTFO5FA4DF4FS4F\n L4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F\n\n T88K [define load address for main program]\n GK [set @ (theta) for relative addresses]\n\n[The 100 doors are at locations 200..299.\nDoors are numbered 0..99 internally, and 1..100 for output.\nThe base address and the number of doors can be varied.\nThe value of a door is 0 if open, negative if closed.]\n\n [Constants. Program also uses order 'P 1 F'\n which is permanently at absolute address 2.]\n [0] P200F [address of door #0]\n [1] P100F [number of doors, as an address]\n [2] UF [makes S order from T, since 'S' = 'T' + 'U']\n [3] MF [makes A order from T, since 'A' = 'T' + 'M']\n [4] V2047D [all 1's for \"closed\" (any negative value will do)]\n [5] &F [line feed]\n [6] @F [carriage return]\n [7] K4096F [teleprinter null[\n\n [Variables]\n [8] PF [pass number; step when toggling doors]\n [9] PF [door number, as address, 0-based]\n [10] PF [order referring to door 0]\n\n [Enter with acc = 0]\n [Part 1\u00a0: close all the doors]\n [11] T8@ [pass\u00a0:= 0 (used in part 2)]\n T9@ [door number\u00a0:= 0]\n A16@ [load 'T F' order]\n A@ [add base address]\n T10@ [store T order for door #0]\n [16] TF [clear acc; also serves as constant]\n A9@ [load door number]\n A10@ [make T order]\n T21@ [plant in code]\n A4@ [load value for \"closed\"]\n [21] TF [store in current door]\n A9@ [load door number]\n A2F [add 1]\n U9@ [update door number]\n S1@ [done all doors yet?]\n G16@ [if not, loop back]\n\n [Part 2\u00a0: 100 passes, toggling the doors]\n [27] TF [clear acc]\n A8@ [load pass number]\n A2F [add 1]\n T8@ [save updated pass number]\n S2F [make -1]\n U9@ [door number\u00a0:= -1]\n A8@ [add pass number to get first door toggled on this pass]\n S1@ [gone beyond end?]\n E50@ [if so, move on to part 3]\n [36] A1@ [restore acc after test]\n U9@ [store current door number]\n A10@ [make T order to load status]\n U44@ [plant T order for first door in pass]\n A2@ [convert to S order]\n T43@ [plant S order]\n A4@ [load value for \"closed\"]\n [43] SF [subtract status; toggles status]\n [44] TF [update status]\n A9@ [load door number just toggled]\n A8@ [add pass number to get next door in pass]\n S1@ [gone beyond end?]\n G36@ [no, loop to do next door]\n E27@ [yes, loop to do next pass]\n\n [Part 3\u00a0: Print list of open doors.\n Header has set teleprinter to figures.]\n [50] TF [clear acc]\n T9@ [door nr\u00a0:= 0]\n A10@ [T order for door 0]\n A3@ [convert to A order]\n T10@\n [55] TF\n A9@ [load door number]\n A10@ [make A order to load value]\n T59@ [plant in next order]\n [59] AF [acc\u00a0:= 0 if open, < 0 if closed]\n G69@ [skip if closed]\n A9@ [door number as address]\n A2F [add 1 for 1-based output]\n RD [shift 1 right, address --> integer]\n TF [store integer at 0 for printing]\n [65] A65@ [for return from subroutine]\n G56F [call subroutine to print door number]\n O6@ [followed by CRLF]\n O5@\n [69] TF [clear acc]\n A9@ [load door number]\n A2F [add 1]\n U9@ [update door number]\n S1@ [done all doors yet?]\n G55@ [if not, loop back]\n [75] O7@ [output null to flush teleprinter buffer]\n ZF [stop]\n E11Z [define relative start address]\n PF", "safe": true }, { "filename": "100_doors_222.txt", "content": "THE OPEN DOORS ARE\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n 100\n", "safe": true }, { "filename": "100_doors_223.txt", "content": "#import \n\nint main()\n square\u00a0:= 1, increment = 3\n\n for int door in 1 .. 100\n printf(\"door #%d\", door)\n\n if door == square\n puts(\" is open.\")\n square += increment\n increment += 2\n else\n puts(\" is closed.\")\n\n return 0", "safe": true }, { "filename": "100_doors_224.txt", "content": "import \"prelude.eg\"\n\nusing System\nusing List\n\ndata open, closed\n\ndef toggle =\n [ open N -> closed N | closed N -> open N ]\n\ndef doors =\n [ N -> map [ N -> closed N ] (fromto 1 N) ]\n\ndef toggleK =\n [ K nil -> nil\n | K (cons (D N) DD) -> \n let DOOR = if (N%K) == 0 then toggle (D N) else D N in\n cons DOOR (toggleK K DD) ]\n\ndef toggleEvery =\n [ nil DOORS -> DOORS\n | (cons K KK) DOORS -> toggleEvery KK (toggleK K DOORS) ]\n\ndef run =\n [ N -> toggleEvery (fromto 1 N) (doors N) ]\n\ndef main = run 100", "safe": true }, { "filename": "100_doors_225.txt", "content": "program OneHundredDoors\n\n function main()\n\n doors boolean[] = new boolean[100];\n n int = 100;\n\n for (i int from 1 to n)\n for (j int from i to n by i)\n doors[j] = !doors[j];\n end\n end\n \n for (i int from 1 to n)\n if (doors[i])\n SysLib.writeStdout( \"Door \" + i + \" is open\" );\n end\n end\n \n end\n\nend", "safe": true }, { "filename": "100_doors_226.txt", "content": "note\n\tdescription: \"100 Doors problem\"\n\tdate: \"08-JUL-2015\"\n\trevision: \"1.1\"\n\nclass\n\tAPPLICATION\n\ncreate\n\tmake\n\nfeature {NONE} -- Initialization\n\n\tmake\n\t\t\t-- Main application routine.\n\t\tdo\n\t\t\tinitialize_closed_doors\n\t\t\ttoggle_doors\n\t\t\toutput_door_states\n\t\tend\n\nfeature -- Access\n\n\tdoors: ARRAYED_LIST [DOOR]\n\t\t\t-- A set of doors (self-initialized to capacity of `max_door_count').\n\t\tattribute\n\t\t\tcreate Result.make (max_door_count)\n\t\tend\n\nfeature -- Basic Operations\n\n\tinitialize_closed_doors\n\t\t\t-- Initialize all `doors'.\n\t\tdo\n\t\t\tacross min_door_count |..| max_door_count as ic_address_list loop\n\t\t\t\tdoors.extend (create {DOOR}.make_closed (ic_address_list.item))\n\t\t\tend\n\t\tensure\n\t\t\thas_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end\n\t\tend\n\n\ttoggle_doors\n\t\t\t-- Toggle all `doors'.\n\t\tdo\n\t\t\tacross min_door_count |..| max_door_count as ic_addresses_list loop\n\t\t\t\tacross doors as ic_doors_list loop\n\t\t\t\t\tif is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then\n\t\t\t\t\t\tic_doors_list.item.toggle_door\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\toutput_door_states\n\t\t\t-- Output the state of all `doors'.\n\t\tdo\n\t\t\tdoors.do_all (agent door_state_out)\n\t\tend\n\nfeature -- Status Report\n\n\tis_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN\n\t\t\t-- Is the door at `a_door_address' needing to be toggled, when compared to `a_index_address'?\n\t\tdo\n\t\t\tResult\u00a0:= a_door_address \\\\ a_index_address = 0\n\t\tensure\n\t\t\tonly_modulus_zero: Result = (a_door_address \\\\ a_index_address = 0)\n\t\tend\n\nfeature -- Outputs\n\n\tdoor_state_out (a_door: DOOR)\n\t\t\t-- Output the state of `a_door'.\n\t\tdo\n\t\t\tprint (\"Door \" + a_door.address.out + \" is \")\n\t\t\tif a_door.is_open then\n\t\t\t\tprint (\"open.\")\n\t\t\telse\n\t\t\t\tprint (\"closed.\")\n\t\t\tend\n\t\t\tio.new_line\n\t\tend\n\nfeature {DOOR} -- Constants\n\n\tmin_door_count: INTEGER = 1\n\t\t\t-- Minimum number of doors.\n\n\tmax_door_count: INTEGER = 100\n\t\t\t-- Maximum number of doors.\n\nend", "safe": true }, { "filename": "100_doors_227.txt", "content": "note\n\tdescription: \"A door with an address and an open or closed state.\"\n\tdate: \"08-JUL-2015\"\n\trevision: \"1.1\"\n\nclass\n\tDOOR\n\ncreate\n\tmake_closed,\n\tmake\n\nfeature {NONE} -- initialization\n\n\tmake_closed (a_address: INTEGER)\n\t\t\t-- Initialize Current {DOOR} at `a_address' and state of `Is_closed'.\n\t\trequire\n\t\t\tpositive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count\n\t\tdo\n\t\t\tmake (a_address, Is_closed)\n\t\tensure\n\t\t\tclosed: is_open = Is_closed\n\t\tend\n\n\tmake (a_address: INTEGER; a_status: BOOLEAN)\n\t\t\t-- Initialize Current {DOOR} with `a_address' and `a_status', denoting position and `is_open' or `Is_closed'.\n\t\trequire\n\t\t\tpositive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count\n\t\tdo\n\t\t\taddress\u00a0:= a_address\n\t\t\tis_open\u00a0:= a_status\n\t\tensure\n\t\t\taddress_set: address = a_address\n\t\t\tstatus_set: is_open = a_status\n\t\tend\n\nfeature -- access\n\n\taddress: INTEGER\n\t\t\t-- `address' of Current {DOOR}.\n\n\tis_open: BOOLEAN assign set_open\n\t\t\t-- `is_open' (or not) status of Current {DOOR}.\n\nfeature -- Setters\n\n\tset_open (a_status: BOOLEAN)\n\t\t\t-- Set `status' with `a_status'\n\t\tdo\n\t\t\tis_open\u00a0:= a_status\n\t\tensure\n\t\t\topen_updated: is_open = a_status\n\t\tend\n\nfeature {APPLICATION} -- Basic Operations\n\n\ttoggle_door\n\t\t\t-- Toggle Current {DOOR} from `is_open' to not `is_open'.\n\t\tdo\n\t\t\tis_open\u00a0:= not is_open\n\t\tensure\n\t\t\ttoggled: is_open /= old is_open\n\t\tend\n\nfeature {NONE} -- Implementation: Constants\n\n\tIs_closed: BOOLEAN = False\n\t\t\t-- State of being not `is_open'.\n\n\tMin_door_count: INTEGER = 1\n\t\t\t-- Minimum door count.\n\ninvariant\n\tone_or_more: address >= 1\n\tconsistency: is_open implies not Is_closed\n\nend", "safe": true }, { "filename": "100_doors_228.txt", "content": "open generic\n\ntype Door = Open | Closed\n deriving Show\n\ngate [] _ = []\ngate (x::xs) (y::ys) \n | x == y = Open\u00a0:: gate xs ys\n | else = Closed\u00a0:: gate xs ys\n\nrun n = gate [1..n] [& k*k \\\\ k <- [1..]]", "safe": true }, { "filename": "100_doors_229.txt", "content": "open list\nrun n = takeWhile (false);\n for(int i\u00a0:= 0; i < 100; i++)\n {\n for(int j\u00a0:= i; j < 100; j\u00a0:= j + i + 1)\n {\n Doors[j]\u00a0:= Doors[j].Inverted\n }\n };\n \n for(int i\u00a0:= 0; i < 100; i++)\n {\n console.printLine(\"Door #\",i + 1,\"\u00a0:\",Doors[i].iif(\"Open\",\"Closed\"))\n };\n \n console.readChar()\n}", "safe": true }, { "filename": "100_doors_231.txt", "content": "defmodule HundredDoors do\n def doors(n \\\\ 100) do\n List.duplicate(false, n)\n end\n \n def toggle(doors, n) do\n List.update_at(doors, n, &(!&1))\n end\n \n def toggle_every(doors, n) do\n Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end )\n end\nend\n\n# unoptimized\nfinal_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end)\n\nopen_doors = Enum.with_index(final_state)\n |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)\n\nIO.puts \"All doors are closed except these: #{inspect open_doors}\"\n\n\n# optimized \nfinal_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end)\n\nopen_doors = Enum.with_index(final_state)\n |> Enum.filter_map(fn {door,_} -> door end, fn {_,index} -> index+1 end)\n\nIO.puts \"All doors are closed except these: #{inspect open_doors}\"", "safe": true }, { "filename": "100_doors_232.txt", "content": "All doors are closed except these: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_233.txt", "content": "-- Unoptimized\nimport List exposing (indexedMap, foldl, repeat, range)\nimport Html exposing (text)\nimport Debug exposing (toString)\n\ntype Door = Open | Closed\n\ntoggle d = if d == Open then Closed else Open\n\ntoggleEvery\u00a0: Int -> List Door -> List Door\ntoggleEvery k doors = indexedMap \n (\\i door -> if modBy k (i+1) == 0 then toggle door else door)\n doors\n\nn = 100\n\nmain = \n text (toString (foldl toggleEvery (repeat n Closed) (range 1 n)))", "safe": true }, { "filename": "100_doors_234.txt", "content": "(defun create-doors ()\n \"Returns a list of closed doors\n\nEach door only has two status: open or closed.\nIf a door is closed it has the value 0, if it's open it has the value 1.\"\n (let ((return_value '(0))\n \u00a0;; There is already a door in the return_value, so k starts at 1\n \u00a0;; otherwise we would need to compare k against 99 and not 100 in\n \u00a0;; the while loop\n (k 1))\n (while (< k 100)\n (setq return_value (cons 0 return_value))\n (setq k (+ 1 k)))\n return_value))\n\n(defun toggle-single-door (doors)\n \"Toggle the stat of the door at the `car' position of the DOORS list\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\n\nReturns a list where the `car' of the list has it's value toggled (if open\nit becomes closed, if closed it becomes open).\"\n (if (= (car doors) 1)\n (cons 0 (cdr doors))\n (cons 1 (cdr doors))))\n\n(defun toggle-doors (doors step original-step)\n \"Step through all elements of the doors' list and toggle a door when step is 1\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\nSTEP is the number of doors we still need to transverse before we arrive\nat a door that has to be toggled.\nORIGINAL-STEP is the value of the argument step when this function is\ncalled for the first time.\n\nReturns a list of doors\"\n (cond ((null doors)\n '())\n ((= step 1)\n (cons (car (toggle-single-door doors))\n (toggle-doors (cdr doors) original-step original-step)))\n (t\n (cons (car doors)\n (toggle-doors (cdr doors) (- step 1) original-step)))))\n\n(defun main-program ()\n \"The main loop for the program\"\n (let ((doors_list (create-doors))\n (k 1)\n \u00a0;; We need to define max-specpdl-size and max-specpdl-size to big\n \u00a0;; numbers otherwise the loop reaches the max recursion depth and\n \u00a0;; throws an error.\n \u00a0;; If you want more information about these variables, press Ctrl\n \u00a0;; and h at the same time and then press v and then type the name\n \u00a0;; of the variable that you want to read the documentation.\n (max-specpdl-size 5000)\n (max-lisp-eval-depth 2000))\n (while (< k 101)\n (setq doors_list (toggle-doors doors_list k k))\n (setq k (+ 1 k)))\n doors_list))\n\n(defun print-doors (doors)\n \"This function prints the values of the doors into the current buffer.\n\nDOORS is a list of integers with either the value 0 or 1 and it represents\na row of doors.\n\"\n \u00a0;; As in the main-program function, we need to set the variable\n \u00a0;; max-lisp-eval-depth to a big number so it doesn't reach max recursion\n \u00a0;; depth.\n (let ((max-lisp-eval-depth 5000))\n (unless (null doors)\n (insert (int-to-string (car doors)))\n (print-doors (cdr doors)))))\n\n;; Returns a list with the final solution\n(main-program)\n\n;; Print the final solution on the buffer\n(print-doors (main-program))", "safe": true }, { "filename": "100_doors_235.txt", "content": "type Door:State\nenum do int CLOSED, OPEN end\ntype Door\nmodel\n int id\n Door:State state\n new by int \u2190id, Door:State \u2190state do end\n fun toggle \u2190 <|me.state \u2190 when(me.state \u00e6 Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED)\n fun asText \u2190 <|\"Door #\" + me.id + \" is \" + when(me.state \u00e6 Door:State.CLOSED, \"closed\", \"open\")\nend\ntype Main\n^|There are 100 doors in a row that are all initially closed.|^\nList doors \u2190 Door[].with(100, open;\ntoggle(open) -> closed.\n\ngo() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1).\ngo([], L, N, _I) when N =:= 101 -> lists:reverse(L);\ngo([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1);\ngo([H|T], L, N, I) ->\n H2 = case I rem N of\n 0 -> toggle(H);\n _ -> H\n end,\n go(T, [H2|L], N, I + 1).", "safe": true }, { "filename": "100_doors_238.txt", "content": "array_go() -> go(array:new([101, fixed, {default, closed}]), 1, 1).\n\ngo(Array, Big, Inc) when Big > 100, Inc =< 100 ->\n go(Array, Inc + 1, Inc + 1);\ngo(Array, Index, Inc) when Inc < 101 ->\n go(array:set(Index, toggle(Array, Index), Array), Index + Inc, Inc);\ngo(Array, _, _) -> array:sparse_to_orddict(Array).\n\ntoggle(Array, Index) -> toggle(array:get(Index, Array)).", "safe": true }, { "filename": "100_doors_239.txt", "content": " task_100_doors:array_go().\n[{1,open},\n {4,open},\n {9,open},\n {16,open},\n {25,open},\n {36,open},\n {49,open},\n {64,open},\n {81,open},\n {100,open}]\n", "safe": true }, { "filename": "100_doors_24.txt", "content": "Following doors are open:\n1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_240.txt", "content": "doors() ->\n F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end,\n Out = fun(X, true) -> io:format(\"Door ~p: open~n\",[X]);\n (X, false)-> io:format(\"Door ~p: close~n\",[X]) end,\n [Out(X,F(X)) || X <- lists:seq(1,100)].", "safe": true }, { "filename": "100_doors_241.txt", "content": "! \"100 Doors\" program for ERRE LANGUAGE\n! Author: Claudio Larini\n! Date: 21-Nov-2014\n!\n! PC Unoptimized version translated from a QB version\n\nPROGRAM 100DOORS\n\n!$INTEGER\n\nCONST N=100\n\nDIM DOOR[N]\n\nBEGIN\n\nFOR STRIDE=1 TO N DO\n FOR INDEX=STRIDE TO N STEP STRIDE DO\n DOOR[INDEX]=NOT(DOOR[INDEX])\n END FOR\nEND FOR\n\nPRINT(\"Open doors:\";)\nFOR INDEX=1 TO N DO\n IF DOOR[INDEX] THEN PRINT(INDEX;) END IF\nEND FOR\nPRINT\n\nEND PROGRAM", "safe": true }, { "filename": "100_doors_242.txt", "content": "begin new doors; new i; label doorLoop; label outDoors;\n doors <- list 100;\n i <- 0;\ndoorLoop: if [ i <- i + 1 ] <= length doors then begin\n new j; label flipLoop;\n j <- 0;\nflipLoop: if [ j <- J + i ] <= length doors then begin\n doors[ j ] <- isu doors[ j ] or not doors[ j ];\n goto flipLoop\n end else 0;\n goto doorLoop\n end else 0;\n i <- 0;\noutDoors: if [ i <- i + 1 ] <= length doors then begin\n if doors[ i ] then out i else 0;\n goto outDoors\n end else 0\nend $\n", "safe": true }, { "filename": "100_doors_243.txt", "content": ">function Doors () ...\n$ doors:=zeros(1,100);\n$ for i=1 to 100\n$ for j=i to 100 step i\n$ doors[j]=!doors[j];\n$ end;\n$ end;\n$ return doors\n$endfunction\n>nonzeros(Doors())\n [ 1 4 9 16 25 36 49 64 81 100 ]", "safe": true }, { "filename": "100_doors_244.txt", "content": "-- doors.ex\ninclude std/console.e\nsequence doors\ndoors = repeat( 0, 100 ) -- 1 to 100, initialised to false \n\nfor pass = 1 to 100 do\n\tfor door = pass to 100 by pass do\n\t\t--printf( 1, \"%d\", doors[door] )\n\t\t--printf( 1, \"%d\", not doors[door] )\n\t\tdoors[door] = not doors[door]\n\tend for\nend for\n\nsequence oc\n\nfor i = 1 to 100 do\n\tif doors[i] then\n\t\toc = \"open\"\n\telse\n\t\toc = \"closed\"\n\tend if\n \tprintf( 1, \"door %d is %s\\n\", { i, oc } )\nend for", "safe": true }, { "filename": "100_doors_245.txt", "content": "=IF($A2/C$1=INT($A2/C$1),IF(B2=0,1,IF(B2=1,0)),B2)", "safe": true }, { "filename": "100_doors_246.txt", "content": "=IF($A3/C$1=INT($A3/C$1),IF(B3=0,1,IF(B3=1,0)),B3)", "safe": true }, { "filename": "100_doors_247.txt", "content": "=IF($A2/D$1=INT($A2/D$1),IF(C2=0,1,IF(C2=1,0)),C2)", "safe": true }, { "filename": "100_doors_248.txt", "content": "type doorState=Open|Closed\nlet flip=function Open->Closed |_->Open\nlet Doors=Array.create 100 Closed\nfor n in 1..100 do {n-1..n..99}|>Seq.iter(fun n->Doors[n]<-flip Doors[n])\nDoors|>Array.iteri(fun n g->if g=Open then printf \"%d \" (n+1)); printfn \"\"", "safe": true }, { "filename": "100_doors_249.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_25.txt", "content": "package { \n import flash.display.Sprite; \n\n public class Doors extends Sprite {\n public function Doors() {\n\n // Initialize the array\n var doors:Array = new Array(100);\n for (var i:Number = 0; i < 100; i++) {\n doors[i] = false;\n\n // Do the work\n for (var pass:Number = 0; pass < 100; pass++) {\n for (var j:Number = pass; j < 100; j += (pass+1)) {\n doors[j] = !doors[j];\n }\n }\n trace(doors);\n }\n }\n}\n", "safe": true }, { "filename": "100_doors_250.txt", "content": "open System\nlet answer2 =\n let PerfectSquare n =\n let sqrt = int(Math.Sqrt(float n))\n n = sqrt * sqrt\n [| for i in 1..100 do yield PerfectSquare i |]", "safe": true }, { "filename": "100_doors_251.txt", "content": "[1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1)\u00a0% pass)=0 then not x else x) doors) (List.init 100 (fun _->false))", "safe": true }, { "filename": "100_doors_252.txt", "content": "USING: bit-arrays formatting fry kernel math math.ranges\nsequences\u00a0;\nIN: rosetta.doors\n\nCONSTANT: number-of-doors 100\n\n: multiples ( n -- range )\n 0 number-of-doors rot \u00a0;\n\n: toggle-multiples ( n doors -- )\n [ multiples ] dip '[ _ [ not ] change-nth ] each\u00a0;\n\n: toggle-all-multiples ( doors -- )\n [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each\u00a0;\n\n: print-doors ( doors -- )\n [\n swap \"open\" \"closed\"\u00a0? \"Door %d is %s\\n\" printf\n ] each-index\u00a0;\n\n: main ( -- )\n number-of-doors 1 + \n [ toggle-all-multiples ] [ print-doors ] bi\u00a0;\n\nmain", "safe": true }, { "filename": "100_doors_253.txt", "content": "USING:\n formatting\n math math.primes.factors math.ranges\n sequences\u00a0;\nIN: rosetta-doors2\n\n: main ( -- )\n 100 [1,b] [ divisors length odd? ] filter \"Open\u00a0%[%d,\u00a0%]\\n\" printf\u00a0;", "safe": true }, { "filename": "100_doors_254.txt", "content": "doors = arrayBuffer( 101, false )\n\nfor pass in [ 0\u00a0: doors.len() ]\n for door in [ 0\u00a0: doors.len()\u00a0: pass+1 ]\n doors[ door ] = not doors[ door ]\n end\nend\n\nfor door in [ 1\u00a0: doors.len() ] // Show Output\n > \"Door \", $door, \" is: \", ( doors[ door ] )\u00a0? \"open\"\u00a0: \"closed\"\nend", "safe": true }, { "filename": "100_doors_255.txt", "content": "for door in [ 1\u00a0: 101 ]: > \"Door \", $door, \" is: \", fract( door ** 0.5 )\u00a0? \"closed\"\u00a0: \"open\"", "safe": true }, { "filename": "100_doors_256.txt", "content": "100[$][0 1\u00f8:1-]# {initialize doors}\n%\n[s;[$101\\>][$$;~\\:s;+]#%]d: {function d, switch door state function}\n1s:[s;101\\>][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time}\n1[$101\\>][$$.\" \";$[\"open\n\"]?~[\"closed\n\"]?1+]# {loop through doors, print door number and state}", "safe": true }, { "filename": "100_doors_257.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n...\n98 closed\n99 closed\n100 open", "safe": true }, { "filename": "100_doors_258.txt", "content": " states\u00a0:= (1..100).toList\n 100.times |i| {\n states = states.map |state| { state\u00a0% (i+1) == 0\u00a0? -state\u00a0: +state }\n }\n echo(\"Open doors are \" + states.findAll { it < 0 }.map { -it })", "safe": true }, { "filename": "100_doors_259.txt", "content": " echo(\"Open doors are \" + (1..100).toList.findAll { it.toFloat.pow(0.5f).toInt.pow(2) == it})", "safe": true }, { "filename": "100_doors_26.txt", "content": "Using #HASH-OFF, OPTION OICC =\"^\" , CICC =\"^\"\n", "safe": true }, { "filename": "100_doors_260.txt", "content": "#AppType Console\n\nDim doors[], n As Integer = 100\n\nFor Dim i = 1 To n\n\tFor Dim j = i To n Step i\n\t\tdoors[j] = Not doors[j]\n\tNext\nNext\n\nFor i = 1 To n\n\tIf doors[i] Then Print \"Door \", i, \" is open\"\nNext\n\nPause", "safe": true }, { "filename": "100_doors_261.txt", "content": "#APPTYPE CONSOLE\n\nDIM i = 0, j = 0, door = 1\n\nWHILE INCR(i) < 101\n IF i = door THEN\n PRINT \"Door \", door, \" open\"\n INCR(door, INCR((INCR(j) << 1)))\n END IF\nWEND\n\nPAUSE", "safe": true }, { "filename": "100_doors_262.txt", "content": "; macro for finite loop\n(= repeat (mac (i n . body)\n (list 'do\n (list 'let i 0)\n (list 'while (list '< i n)\n (list '= i (list '+ i 1))\n (cons 'do body)))))\n\n; function to get n-th element of list\n(= nth (fn (i lst)\n (while (< 0 i)\n (= i (- i 1))\n (= lst (cdr lst)))\n lst))\n\n; make list of 100 nils\n(repeat i 100 (= doors (cons nil doors)))\n\n; do algorithm iterations\n(repeat i 100\n (let pos (nth (- i 1) doors))\n (while pos\n (setcar pos (not (car pos)))\n (= pos (nth i pos))))\n\n(print doors)", "safe": true }, { "filename": "100_doors_263.txt", "content": "; do algorithm iterations sqrt(100) = 10 times\n(repeat i 10 (setcar (nth (- (* i i) 1) doors) 't))", "safe": true }, { "filename": "100_doors_264.txt", "content": "doors = malloc$ 100u\nfor uint [0u, sizeof$ doors) with l1 {\n put_byte$ + doors l1 as false byte\n}\nfunction void pass(step:uint) {\n location = step\n while <= location sizeof$ doors {\n ac = - + doors location 1u\n put_byte$ ac ~ deref_byte$ ac// true is represented as 255 (0xff)\n location = + location step\n }\n}\nfor uint (0u, sizeof$ doors] with l2 {//range exclusive of 0, inclusive of 100\n pass$ l2\n}\ncount = 1u\nfor ubyte as doors listubyte with isopen {// list for-each\n if as isopen bool {// cast byte to bool\n puts$ \"door \"\n putui$ count\n puts$ \" is open\\n\"\n }\u00a0;\n count = + count 1u\n}\nfree$ doors", "safe": true }, { "filename": "100_doors_265.txt", "content": "1001-p01.\n>0101-p02.\n>101-g001-g+:::aa*)?v101-p03.\n>02-g?v1}02-p02. >05.\n >0}02-p02.\n>~~~0101-p001-g:1+001-paa*)?v02.\n >07.\n>0101-p08.\n>101-g::02-g?v >1+:101-paa*=?;\n >n\" \"o^", "safe": true }, { "filename": "100_doors_266.txt", "content": "1.1 F N=1,100;S D(N)=0\n1.2 F M=1,100;F N=M,M,100;S D(N)=1-D(N)\n1.3 F N=1,100;D 2.0\n1.4 Q\n2.1 I (D(N)),,2.2;R\n2.2 T \"OPEN DOOR \",%3.0,N,!", "safe": true }, { "filename": "100_doors_267.txt", "content": "OPEN DOOR = 1\nOPEN DOOR = 4\nOPEN DOOR = 9\nOPEN DOOR = 16\nOPEN DOOR = 25\nOPEN DOOR = 36\nOPEN DOOR = 49\nOPEN DOOR = 64\nOPEN DOOR = 81\nOPEN DOOR = 100", "safe": true }, { "filename": "100_doors_268.txt", "content": ": toggle ( c-addr -- ) \\ toggle the byte at c-addr\n dup c@ 1 xor swap c!\u00a0;\n\n100 1+ ( 1-based indexing ) constant ndoors\ncreate doors ndoors allot\n\n: init ( -- ) doors ndoors erase\u00a0; \\ close all doors\n\n: pass ( n -- ) \\ toggle every nth door\n ndoors over do\n doors i + toggle\n dup ( n ) +loop drop\u00a0;\n\n: run ( -- ) ndoors 1 do i pass loop\u00a0;\n: display ( -- ) \\ display open doors\n ndoors 1 do doors i + c@ if i . then loop cr\u00a0;\n\ninit run display", "safe": true }, { "filename": "100_doors_269.txt", "content": ": squared ( n -- n' ) dup *\u00a0;\n: doors ( n -- )\n 1 begin 2dup squared >= while\n dup squared .\n 1+ repeat 2drop\u00a0;\n100 doors", "safe": true }, { "filename": "100_doors_27.txt", "content": "VAR sStatus: SHORT\nVAR sArray: SHORT\nVAR sCount: SHORT\nVAR sDoor: SHORT\nVAR sPass: SHORT\nVAR zIndex: STRING\nVAR zState: STRING\n//\nSET sStatus = GET_UNUSED_ARRAY_HANDLE(sArray)\nSET sStatus = INIT_SORTED_ARRAY(sArray, 0, 0, 1)\n//\nDO sCount = 1 TO 100\n DO sPass = 1 TO 100\n SET sDoor = sCount * sPass\n IF sDoor <= 100\n SET zIndex = REPEAT(\"0\", 3 - LENGTH(STR(sDoor))) + STR(sDoor)\n SET sStatus = READ_ARRAY_REC(\"=\", sArray, zIndex)\n SET zState = \"OPEN\"\n IF GET_STRING_SAY(sArray, 1) = \"OPEN\"\n SET zState = \"CLOSE\"\n ENDIF\n //\n SET sStatus = ADD_ARRAY_REC(sArray, zIndex)\n SET sStatus = PUT_STRING_SAY(sArray, 1, zState)\n ELSE\n BREAK\n ENDIF\n ENDDO\nENDDO\n//\nSET zIndex = \"\"\nSET sStatus = READ_ARRAY_REC(\">=\", sArray, zIndex)\nDO WHILE sStatus = 0\n >>Door: ^zIndex^ State: ^GET_STRING_SAY(sArray, 1)^\n SET sStatus = READ_ARRAY_REC(\"+\", sArray, zIndex)\nENDDO", "safe": true }, { "filename": "100_doors_270.txt", "content": "program doors\n implicit none\n integer, allocatable\u00a0:: door(:)\n character(6), parameter\u00a0:: s(0:1) = [character(6)\u00a0:: \"closed\", \"open\"]\n integer\u00a0:: i, n\n \n print \"(A)\", \"Number of doors?\"\n read *, n\n allocate (door(n))\n door = 1\n do i = 1, n\n door(i:n:i) = 1 - door(i:n:i)\n print \"(A,G0,2A)\", \"door \", i, \" is \", s(door(i))\n end do\nend program", "safe": true }, { "filename": "100_doors_271.txt", "content": "PROGRAM DOORS\n\n INTEGER, PARAMETER\u00a0:: n = 100 \u00a0! Number of doors\n INTEGER\u00a0:: i\n LOGICAL\u00a0:: door(n) = .TRUE. \u00a0! Initially closed\n \n DO i = 1, SQRT(REAL(n))\n door(i*i) = .FALSE.\n END DO \n \n DO i = 1, n\n WRITE(*,\"(A,I3,A)\", ADVANCE=\"NO\") \"Door \", i, \" is \"\n IF (door(i)) THEN\n WRITE(*,\"(A)\") \"closed\"\n ELSE\n WRITE(*,\"(A)\") \"open\"\n END IF\n END DO\n \nEND PROGRAM DOORS", "safe": true }, { "filename": "100_doors_272.txt", "content": "program OneHundredIsOpen;\n\nconst\n DoorCount = 100;\n\nvar\n IsOpen: array[1..DoorCount] of boolean;\n Door, Jump: integer;\n\nbegin\n // Close all doors\n for Door\u00a0:= 1 to DoorCount do\n IsOpen[Door]\u00a0:= False;\n // Iterations\n for Jump\u00a0:= 1 to DoorCount do\n begin\n Door\u00a0:= Jump;\n repeat\n IsOpen[Door]\u00a0:= not IsOpen[Door];\n Door\u00a0:= Door + Jump;\n until Door > DoorCount;\n end;\n // Show final status\n for Door\u00a0:= 1 to DoorCount do\n begin\n Write(Door, ' ');\n if IsOpen[Door] then\n WriteLn('open')\n else\n WriteLn('closed');\n end;\n // Wait for \n Readln;\nend.", "safe": true }, { "filename": "100_doors_273.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n, n1, door(1 To max_doors)\n\n' toggle, at start all doors are closed (0)\n' 0 = door closed, 1 = door open\nFor n = 1 To max_doors\n For n1 = n To max_doors Step n\n door(n1) = 1 - door(n1)\n Next\nNext\n\n' count the doors that are open (1)\nPrint \"doors that are open nr: \";\nFor n = 1 To max_doors\n If door(n) = 1 Then\n Print n; \" \";\n c = c + 1\n End If\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100_doors_274.txt", "content": "doors that are open nr: 1 4 9 16 25 36 49 64 81 100 \n\nThere are 10 doors open", "safe": true }, { "filename": "100_doors_275.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n, n1, door(1 To max_doors)\n\n' at start all doors are closed\n' simple add 1 each time we open or close a door\n' doors with odd numbers are open\n' doors with even numbers are closed\nFor n = 1 To max_doors\n For n1 = n To max_doors Step n\n door(n1) += 1\n Next\nNext\n\nPrint \"doors that are open nr: \";\nFor n = 1 To max_doors\n If door(n) And 1 Then\n Print n; \" \";\n c = c + 1\n End If\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100_doors_276.txt", "content": "' version 27-10-2016\n' compile with: fbc -s console\n\n#Define max_doors 100\n\nDim As ULong c, n\n\nPrint \"doors that are open nr: \";\nFor n = 1 To 10\n Print n * n; \" \";\n c = c + 1\nNext\n\nPrint\u00a0: Print\nPrint \"There are \" + Str(c) + \" doors open\"\n\n' empty keyboard buffer\nWhile InKey <> \"\"\u00a0: Wend\nPrint\u00a0: Print \"hit any key to end program\"\nSleep\nEnd", "safe": true }, { "filename": "100_doors_277.txt", "content": "' version 16-06-2021\n' portado desde Julia\n\nFor i As Integer = 1 To 10\n If (i Mod i^2) < 11 Then Print \"La puerta\"; i^2; \" esta abierta\" \nNext i\nSleep", "safe": true }, { "filename": "100_doors_278.txt", "content": "# Set doors to empty list\nset doors\n\n# Initialize doors arrays\nfor i in (seq 100)\n set doors[$i] 0\nend\n\nfor i in (seq 100)\n set j $i\n while test $j -le 100\n # Logical not on doors\n set doors[$j] (math\u00a0!$doors[$j])\n set j (math $j + $i)\n end\nend\n\n# Print every door\nfor i in (seq (count $doors))\n echo -n \"$i \"\n if test $doors[$i] -eq 0\n echo closed\n else\n echo open\n end\nend", "safe": true }, { "filename": "100_doors_279.txt", "content": "# Set doors to empty list\nset doors\n\nfor i in (seq 100)\n set doors[(math \"$i * $i\")] 1\n echo -n \"$i \"\n if test $doors[$i] -eq 1\n echo open\n else\n echo closed\n end\nend", "safe": true }, { "filename": "100_doors_28.txt", "content": "Door: 001 State: OPEN\nDoor: 002 State: CLOSE\nDoor: 003 State: CLOSE\nDoor: 004 State: OPEN\nDoor: 005 State: CLOSE\nDoor: 006 State: CLOSE\nDoor: 007 State: CLOSE\nDoor: 008 State: CLOSE\nDoor: 009 State: OPEN\nDoor: 010 State: CLOSE\nDoor: 011 State: CLOSE\nDoor: 012 State: CLOSE\nDoor: 013 State: CLOSE\nDoor: 014 State: CLOSE\nDoor: 015 State: CLOSE\nDoor: 016 State: OPEN\nDoor: 017 State: CLOSE\nDoor: 018 State: CLOSE\nDoor: 019 State: CLOSE\nDoor: 020 State: CLOSE\nDoor: 021 State: CLOSE\nDoor: 022 State: CLOSE\nDoor: 023 State: CLOSE\nDoor: 024 State: CLOSE\nDoor: 025 State: OPEN\nDoor: 026 State: CLOSE\nDoor: 027 State: CLOSE\nDoor: 028 State: CLOSE\nDoor: 029 State: CLOSE\nDoor: 030 State: CLOSE\nDoor: 031 State: CLOSE\nDoor: 032 State: CLOSE\nDoor: 033 State: CLOSE\nDoor: 034 State: CLOSE\nDoor: 035 State: CLOSE\nDoor: 036 State: OPEN\nDoor: 037 State: CLOSE\nDoor: 038 State: CLOSE\nDoor: 039 State: CLOSE\nDoor: 040 State: CLOSE\nDoor: 041 State: CLOSE\nDoor: 042 State: CLOSE\nDoor: 043 State: CLOSE\nDoor: 044 State: CLOSE\nDoor: 045 State: CLOSE\nDoor: 046 State: CLOSE\nDoor: 047 State: CLOSE\nDoor: 048 State: CLOSE\nDoor: 049 State: OPEN\nDoor: 050 State: CLOSE\nDoor: 051 State: CLOSE\nDoor: 052 State: CLOSE\nDoor: 053 State: CLOSE\nDoor: 054 State: CLOSE\nDoor: 055 State: CLOSE\nDoor: 056 State: CLOSE\nDoor: 057 State: CLOSE\nDoor: 058 State: CLOSE\nDoor: 059 State: CLOSE\nDoor: 060 State: CLOSE\nDoor: 061 State: CLOSE\nDoor: 062 State: CLOSE\nDoor: 063 State: CLOSE\nDoor: 064 State: OPEN\nDoor: 065 State: CLOSE\nDoor: 066 State: CLOSE\nDoor: 067 State: CLOSE\nDoor: 068 State: CLOSE\nDoor: 069 State: CLOSE\nDoor: 070 State: CLOSE\nDoor: 071 State: CLOSE\nDoor: 072 State: CLOSE\nDoor: 073 State: CLOSE\nDoor: 074 State: CLOSE\nDoor: 075 State: CLOSE\nDoor: 076 State: CLOSE\nDoor: 077 State: CLOSE\nDoor: 078 State: CLOSE\nDoor: 079 State: CLOSE\nDoor: 080 State: CLOSE\nDoor: 081 State: OPEN\nDoor: 082 State: CLOSE\nDoor: 083 State: CLOSE\nDoor: 084 State: CLOSE\nDoor: 085 State: CLOSE\nDoor: 086 State: CLOSE\nDoor: 087 State: CLOSE\nDoor: 088 State: CLOSE\nDoor: 089 State: CLOSE\nDoor: 090 State: CLOSE\nDoor: 091 State: CLOSE\nDoor: 092 State: CLOSE\nDoor: 093 State: CLOSE\nDoor: 094 State: CLOSE\nDoor: 095 State: CLOSE\nDoor: 096 State: CLOSE\nDoor: 097 State: CLOSE\nDoor: 098 State: CLOSE\nDoor: 099 State: CLOSE\nDoor: 100 State: OPEN\n", "safe": true }, { "filename": "100_doors_280.txt", "content": "doors = new array[[101], false]\nfor pass=1 to 100\n for door=pass to 100 step pass\n doors@door =\u00a0! doors@door\n\nprint[\"Open doors: \"]\nfor door=1 to 100\n if doors@door\n print[\"$door \"]", "safe": true }, { "filename": "100_doors_281.txt", "content": "define i = 0, d = 0\n\ndo\n\n\tlet i = i + 1\n\tlet d = i * i\n\tprint d\n\nloop d < 100\n\npause\nend", "safe": true }, { "filename": "100_doors_282.txt", "content": "for i <- 1..100\n r = foldl1( \\a, b -> a xor b, [(a|i) | a <- 1..100] )\n println( i + ' ' + (if r then 'open' else 'closed') )", "safe": true }, { "filename": "100_doors_283.txt", "content": "import math.sqrt\n\nfor i <- 1..100\n println( i + ' ' + (if sqrt(i) is Integer then 'open' else 'closed') )", "safe": true }, { "filename": "100_doors_284.txt", "content": "let main(n: i32): [n]bool =\n loop is_open = replicate n false for i < n do\n let js = map (*i+1) (iota n)\n let flips = map (\\j ->\n if j < n\n then unsafe !is_open[j]\n else true -- Doesn't matter.\n ) js\n in scatter is_open js flips", "safe": true }, { "filename": "100_doors_285.txt", "content": "include \"NSLog.incl\"\n\nNSInteger door, square = 1, increment = 3\n\nfor door = 1 to 100\n if ( door == square )\n NSLog( @\"Door %ld is open.\", door )\n square += increment\u00a0: increment += 2\n else\n NSLog( @\"Door %ld is closed.\", door )\n end if\nnext\n\nHandleEvents", "safe": true }, { "filename": "100_doors_286.txt", "content": "Door 1 is open.\nDoor 2 is closed.\nDoor 3 is closed.\nDoor 4 is open.\nDoor 5 is closed.\nDoor 6 is closed.\nDoor 7 is closed.\nDoor 8 is closed.\nDoor 9 is open.\nDoor 10 is closed.\nDoor 11 is closed.\nDoor 12 is closed.\nDoor 13 is closed.\nDoor 14 is closed.\nDoor 15 is closed.\nDoor 16 is open.\nDoor 17 is closed.\nDoor 18 is closed.\nDoor 19 is closed.\nDoor 20 is closed.\nDoor 21 is closed.\nDoor 22 is closed.\nDoor 23 is closed.\nDoor 24 is closed.\nDoor 25 is open.\nDoor 26 is closed.\nDoor 27 is closed.\nDoor 28 is closed.\nDoor 29 is closed.\nDoor 30 is closed.\nDoor 31 is closed.\nDoor 32 is closed.\nDoor 33 is closed.\nDoor 34 is closed.\nDoor 35 is closed.\nDoor 36 is open.\nDoor 37 is closed.\nDoor 38 is closed.\nDoor 39 is closed.\nDoor 40 is closed.\nDoor 41 is closed.\nDoor 42 is closed.\nDoor 43 is closed.\nDoor 44 is closed.\nDoor 45 is closed.\nDoor 46 is closed.\nDoor 47 is closed.\nDoor 48 is closed.\nDoor 49 is open.\nDoor 50 is closed.\nDoor 51 is closed.\nDoor 52 is closed.\nDoor 53 is closed.\nDoor 54 is closed.\nDoor 55 is closed.\nDoor 56 is closed.\nDoor 57 is closed.\nDoor 58 is closed.\nDoor 59 is closed.\nDoor 60 is closed.\nDoor 61 is closed.\nDoor 62 is closed.\nDoor 63 is closed.\nDoor 64 is open.\nDoor 65 is closed.\nDoor 66 is closed.\nDoor 67 is closed.\nDoor 68 is closed.\nDoor 69 is closed.\nDoor 70 is closed.\nDoor 71 is closed.\nDoor 72 is closed.\nDoor 73 is closed.\nDoor 74 is closed.\nDoor 75 is closed.\nDoor 76 is closed.\nDoor 77 is closed.\nDoor 78 is closed.\nDoor 79 is closed.\nDoor 80 is closed.\nDoor 81 is open.\nDoor 82 is closed.\nDoor 83 is closed.\nDoor 84 is closed.\nDoor 85 is closed.\nDoor 86 is closed.\nDoor 87 is closed.\nDoor 88 is closed.\nDoor 89 is closed.\nDoor 90 is closed.\nDoor 91 is closed.\nDoor 92 is closed.\nDoor 93 is closed.\nDoor 94 is closed.\nDoor 95 is closed.\nDoor 96 is closed.\nDoor 97 is closed.\nDoor 98 is closed.\nDoor 99 is closed.\nDoor 100 is open.\n", "safe": true }, { "filename": "100_doors_287.txt", "content": "READ x,y,z\nPRINT \"Open doors: \";x;\" \";\nCYCLE\n z=x+y\n PRINT z;\" \";\n x=z\n y=y+2\nREPEAT UNTIL z>=100\nDATA 1,3,0\nEND", "safe": true }, { "filename": "100_doors_288.txt", "content": "Public Sub Main()\nDim bDoor As New Boolean[101]\nDim siCount1, siCount2, siStart As Short\n\nFor siCount1 = 1 To 100\n Inc siStart\n For siCount2 = siStart To 100 Step siCount1\n bDoor[siCount2] = Not bDoor[siCount2]\n Next\nNext\n\nFor siCount1 = 1 To 100\n If bDoor[siCount1] Then Print siCount1;;\nNext\n\nEnd", "safe": true }, { "filename": "100_doors_289.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_29.txt", "content": "with Ada.Text_Io; use Ada.Text_Io;\n \n procedure Doors is\n type Door_State is (Closed, Open);\n type Door_List is array(Positive range 1..100) of Door_State;\n The_Doors : Door_List := (others => Closed);\n begin\n for I in 1..100 loop\n for J in The_Doors'range loop\n if J mod I = 0 then\n if The_Doors(J) = Closed then\n The_Doors(J) := Open;\n else\n The_Doors(J) := Closed;\n end if;\n end if;\n end loop;\n end loop;\n for I in The_Doors'range loop\n Put_Line(Integer'Image(I) & \" is \" & Door_State'Image(The_Doors(I)));\n end loop;\n end Doors;\n", "safe": true }, { "filename": "100_doors_290.txt", "content": "doors\u00a0:= function(n)\n local a,j,s;\n a\u00a0:= [ ];\n for j in [1 .. n] do\n a[j]\u00a0:= 0;\n od;\n for s in [1 .. n] do\n j\u00a0:= s;\n while j <= n do\n a[j]\u00a0:= 1 - a[j];\n j\u00a0:= j + s;\n od;\n od;\n return Filtered([1 .. n], j -> a[j] = 1);\nend;\n\ndoors(100);\n# [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]", "safe": true }, { "filename": "100_doors_291.txt", "content": "func Doors(door_count:int) -> void\u00a0:\n var doors\u00a0: Array\n doors.resize(door_count)\n\n # Note\u00a0: Initialization is not necessarily mandatory (by default values are false)\n # Intentionally left here\n for i in door_count\u00a0:\n doors[i] = false\n\n # do visits\n for i in door_count\u00a0:\n for j in range(i,door_count,i+1)\u00a0:\n doors[j] = not doors[j]\n \t\n # print results\n var results\u00a0: String = \"\"\n for i in door_count\u00a0:\n results += str(i+1) + \" \" if doors[i] else \"\"\n print(\"Doors open\u00a0: %s\"\u00a0% [results] )\n\n# calling the function from the _ready function\nfunc _ready() -> void\u00a0:\n Doors(100)", "safe": true }, { "filename": "100_doors_292.txt", "content": "Doors open\u00a0: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_293.txt", "content": "// 100 doors problem\n// Author: Sinuhe masan (2019)\ninit\n\n\t// 100 elements array of boolean type\n\tdoors:bool[100]\n \n\tfor var i = 1 to 100\n\t\tdoors[i] = false // set all doors closed\n \n \n\tfor var i = 1 to 100\n\t\tj:int = i\n\t\twhile j <= 100 do\n\t\t\tdoors[j] = not doors[j]\n\t\t\tj = j + i\n \n\tprint(\"Doors open: \")\n\tfor var i = 1 to 100\n\t\tif doors[i]\n\t\t\tstdout.printf (\"%d \", i)", "safe": true }, { "filename": "100_doors_294.txt", "content": "100` *=0=>d $$ create vector 1..100, create bit pattern d, marking all equal to 0\n:for (1..100[.s]){ $$ loop s from 1 to 100\n d^(100` %s *=0 )=>d;} $$ d = d xor (bit pattern of vector 1..100\u00a0% s)\nd $$ output d", "safe": true }, { "filename": "100_doors_295.txt", "content": "Result:\n10010000 10000001 00000000 10000000 00010000 00000000 10000000 00000001 00000000 00000000 10000000 00000000 0001", "safe": true }, { "filename": "100_doors_296.txt", "content": "var doors,a,i;\n//Sets up the array for all of the doors.\nfor (i = 1; i<=100; i += 1)\n {\n doors[i]=0;\n }\n\n//This first for loop goes through and passes the interval down to the next for loop.\nfor (i = 1; i <= 100; i += 1;)\n {\n //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..)\n for (a = 0; a <= 100; a += i;)\n {\n //Opens or closes a door.\n doors[a] = !doors[a];\n }\n }\nopen_doors = '';\n\n//This for loop goes through the array and checks for open doors.\n//If the door is open it adds it to the string then displays the string.\nfor (i = 1; i <= 100; i += 1;)\n {\n if (doors[i] == 1)\n {\n open_doors += \"Door Number \"+string(i)+\" is open#\";\n }\n }\nshow_message(open_doors);\ngame_end();", "safe": true }, { "filename": "100_doors_297.txt", "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n doors\u00a0:= [100]bool{}\n\n // the 100 passes called for in the task description\n for pass\u00a0:= 1; pass <= 100; pass++ {\n for door\u00a0:= pass-1; door < 100; door += pass {\n doors[door] = !doors[door]\n }\n }\n\n // one more pass to answer the question\n for i, v\u00a0:= range doors {\n if v {\n fmt.Print(\"1\")\n } else {\n fmt.Print(\"0\")\n }\n\n if i%10 == 9 {\n fmt.Print(\"\\n\")\n } else {\n fmt.Print(\" \")\n }\n\n }\n}", "safe": true }, { "filename": "100_doors_298.txt", "content": "1 0 0 1 0 0 0 0 1 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 0 0 0 0 1 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 1\n", "safe": true }, { "filename": "100_doors_299.txt", "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var door int = 1\n var incrementer = 0\n\n for current\u00a0:= 1; current <= 100; current++ {\n fmt.Printf(\"Door %d \", current)\n\n if current == door {\n fmt.Printf(\"Open\\n\")\n incrementer++\n door += 2*incrementer + 1\n } else {\n fmt.Printf(\"Closed\\n\")\n }\n }\n}", "safe": true }, { "filename": "100_doors_3.txt", "content": " 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_30.txt", "content": "with Ada.Text_Io; use Ada.Text_Io;\n with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;\n \n procedure Doors_Optimized is\n Num : Float;\n begin\n for I in 1..100 loop\n Num := Sqrt(Float(I));\n Put(Integer'Image(I) & \" is \");\n if Float'Floor(Num) = Num then\n Put_Line(\"Opened\");\n else\n Put_Line(\"Closed\");\n end if;\n end loop;\n end Doors_Optimized;\n", "safe": true }, { "filename": "100_doors_300.txt", "content": "// 100 (optimized) doors in Go\n\npackage main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n for i\u00a0:= 1; i <= 100; i++ {\n f\u00a0:= math.Sqrt(float64(i))\n if math.Mod(f, 1) == 0 {\n fmt.Print(\"O\")\n } else {\n fmt.Print(\"-\")\n }\n }\n fmt.Println()\n}", "safe": true }, { "filename": "100_doors_301.txt", "content": "O--O----O------O--------O----------O------------O--------------O----------------O------------------O\n", "safe": true }, { "filename": "100_doors_302.txt", "content": "100:c;[{0}c*]:d;\nc,{.c,>\\)%{.d<\\.d=1^\\)d>++:d;}/}/\n[c,{)\"door \"\\+\" is\"+}%d{{\"open\"}{\"closed\"}if}%]zip\n{\" \"*puts}/", "safe": true }, { "filename": "100_doors_303.txt", "content": "100,{)}%\n{:d.sqrt 2?=\n{\"open\"}{\"close\"}if\"door \"d+\" is \"+\\+puts}/", "safe": true }, { "filename": "100_doors_304.txt", "content": "[{\"close\"}100*]:d;\n10,{)2?(.d<\\[\"open\"]\\)d>++:d;}/\n[100,{)\"door \"\\+\" is\"+}%d]zip\n{\" \"*puts}/", "safe": true }, { "filename": "100_doors_305.txt", "content": "uses java.util.Arrays\n\nvar doors = new boolean[100]\nArrays.fill( doors, false )\n\nfor( pass in 1..100 ) {\n var counter = pass-1\n while( counter < 100 ) {\n doors[counter] = !doors[counter]\n counter += pass\n }\n}\n\nfor( door in doors index i ) {\n print( \"door ${i+1} is ${door\u00a0? 'open'\u00a0: 'closed'}\" )\n}", "safe": true }, { "filename": "100_doors_306.txt", "content": "var door = 1\nvar delta = 0\n\nfor( i in 1..100 ) {\n if( i == door ) {\n print( \"door ${i} is open\" )\n delta++\n door += 2*delta + 1\n } else {\n print( \"door ${i} is closed\" )\n }\n}", "safe": true }, { "filename": "100_doors_307.txt", "content": "doors = [false] * 100\n(0..99).each {\n it.step(100, it + 1) {\n doors[it] ^= true\n }\n}\n(0..99).each {\n println(\"Door #${it + 1} is ${doors[it]\u00a0? 'open'\u00a0: 'closed'}.\")\n}", "safe": true }, { "filename": "100_doors_308.txt", "content": "(1..100).each {\n println(\"Door #${it} is ${Math.sqrt(it).with{it==(int)it}\u00a0? 'open'\u00a0: 'closed'}.\")\n}", "safe": true }, { "filename": "100_doors_309.txt", "content": "doors = ['closed'] * 100\n(1..10).each { doors[it**2 - 1] = 'open' }\n(0..99).each {\n println(\"Door #${it + 1} is ${doors[it]}.\")\n}", "safe": true }, { "filename": "100_doors_31.txt", "content": "# find the first few squares via the unoptimised door flipping method\nscope\n\n local doorMax\u00a0:= 100;\n local door;\n create register door( doorMax );\n\n # set all doors to closed\n for i to doorMax do door[ i ]\u00a0:= false od;\n\n # repeatedly flip the doors\n for i to doorMax do\n for j from i to doorMax by i do door[ j ]\u00a0:= not door[ j ] od\n od;\n\n # display the results\n for i to doorMax do if door[ i ] then write( \" \", i ) fi od; print()\n\nepocs", "safe": true }, { "filename": "100_doors_310.txt", "content": "10 DIM A(100)\n20 FOR OFFSET = 1 TO 100\n30 FOR I = 0 TO 100 STEP OFFSET\n40 A(I) = A(I) + 1\n50 NEXT I\n60 NEXT OFFSET\n70 ' Print \"opened\" doors\n80 FOR I = 1 TO 100\n90 IF A(I) MOD 2 = 1 THEN PRINT I\n100 NEXT I", "safe": true }, { "filename": "100_doors_311.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100_doors_312.txt", "content": "#define ARRAY_ELEMENTS 100\nPROCEDURE Main()\n LOCAL aDoors\u00a0:= Array( ARRAY_ELEMENTS )\n LOCAL i, j\n\n AFill( aDoors, .F. )\n FOR i\u00a0:= 1 TO ARRAY_ELEMENTS\n FOR j\u00a0:= i TO ARRAY_ELEMENTS STEP i\n aDoors[ j ] =\u00a0! aDoors[ j ]\n NEXT\n NEXT\n AEval( aDoors, {|e, n| QQout( Padl(n,3) + \" is \" + Iif(aDoors[n], \"*open*\", \"closed\" ) + \"|\" ), Iif( n%5 == 0, Qout(), e:=NIL) } )\n RETURN", "safe": true }, { "filename": "100_doors_313.txt", "content": "#define ARRAY_ELEMENTS 100\nPROCEDURE Main()\n LOCAL aDoors\u00a0:= Array( ARRAY_ELEMENTS )\n\n AFill( aDoors, .F. )\n AEval( aDoors, {|e, n| aDoors[n]\u00a0:= e\u00a0:= Iif( Int(Sqrt(n))==Sqrt(n), .T., .F. ) } )\n AEval( aDoors, {|e, n| QQout( Padl(n,3) + \" is \" + Iif(aDoors[n], \"*open*\", \"closed\" ) + \"|\" ), Iif( n%5 == 0, Qout(), e:=NIL )} )\n RETURN", "safe": true }, { "filename": "100_doors_314.txt", "content": " 1 is *open*| 2 is closed| 3 is closed| 4 is *open*| 5 is closed| \n 6 is closed| 7 is closed| 8 is closed| 9 is *open*| 10 is closed| \n11 is closed| 12 is closed| 13 is closed| 14 is closed| 15 is closed| \n16 is *open*| 17 is closed| 18 is closed| 19 is closed| 20 is closed| \n21 is closed| 22 is closed| 23 is closed| 24 is closed| 25 is *open*| \n26 is closed| 27 is closed| 28 is closed| 29 is closed| 30 is closed| \n31 is closed| 32 is closed| 33 is closed| 34 is closed| 35 is closed| \n36 is *open*| 37 is closed| 38 is closed| 39 is closed| 40 is closed| \n41 is closed| 42 is closed| 43 is closed| 44 is closed| 45 is closed| \n46 is closed| 47 is closed| 48 is closed| 49 is *open*| 50 is closed| \n51 is closed| 52 is closed| 53 is closed| 54 is closed| 55 is closed| \n56 is closed| 57 is closed| 58 is closed| 59 is closed| 60 is closed| \n61 is closed| 62 is closed| 63 is closed| 64 is *open*| 65 is closed| \n66 is closed| 67 is closed| 68 is closed| 69 is closed| 70 is closed| \n71 is closed| 72 is closed| 73 is closed| 74 is closed| 75 is closed| \n76 is closed| 77 is closed| 78 is closed| 79 is closed| 80 is closed| \n81 is *open*| 82 is closed| 83 is closed| 84 is closed| 85 is closed| \n86 is closed| 87 is closed| 88 is closed| 89 is closed| 90 is closed| \n91 is closed| 92 is closed| 93 is closed| 94 is closed| 95 is closed| \n96 is closed| 97 is closed| 98 is closed| 99 is closed|100 is *open*|\n", "safe": true }, { "filename": "100_doors_315.txt", "content": "data Door\n = Open\n | Closed\n deriving (Eq, Show)\n\ntoggle\u00a0:: Door -> Door\ntoggle Open = Closed\ntoggle Closed = Open\n\ntoggleEvery\u00a0:: Int -> [Door] -> [Door]\ntoggleEvery k = zipWith toggleK [1 ..]\n where\n toggleK n door\n | n `mod` k == 0 = toggle door\n | otherwise = door\n\nrun\u00a0:: Int -> [Door]\nrun n = foldr toggleEvery (replicate n Closed) [1 .. n]\n\nmain\u00a0:: IO ()\nmain = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100)", "safe": true }, { "filename": "100_doors_316.txt", "content": "[(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]", "safe": true }, { "filename": "100_doors_317.txt", "content": "run n = findIndices odd $ foldr toggleEvery (replicate n 0) [0..n] where toggleEvery k = zipWith (+) $ cycle $ 1\u00a0: replicate k 0", "safe": true }, { "filename": "100_doors_318.txt", "content": "gate\u00a0:: Eq a => [a] -> [a] -> [Door]\ngate (x:xs) (y:ys) | x == y = Open \u00a0: gate xs ys\ngate (x:xs) ys = Closed\u00a0: gate xs ys\ngate [] _ = []\n\nrun n = gate [1..n] [k*k | k <- [1..]]", "safe": true }, { "filename": "100_doors_319.txt", "content": "run n = takeWhile (< n) [k*k | k <- [1..]]", "safe": true }, { "filename": "100_doors_32.txt", "content": "var doors = new int [100]\n\nforeach pass 100 {\n for (var door = pass\u00a0; door < 100\u00a0; door += pass+1) {\n doors[door] = !doors[door]\n }\n}\n\nvar d = 1\nforeach door doors {\n println (\"door \" + d++ + \" is \" + (door\u00a0? \"open\"\u00a0: \"closed\"))\n\n}", "safe": true }, { "filename": "100_doors_320.txt", "content": "class Main\n{\n static public function main()\n {\n findOpenDoors( 100 );\n }\n\n static function findOpenDoors( n\u00a0: Int )\n {\n var door = [];\n for( i in 0...n + 1 ){ door[ i ] = false; }\n for( i in 1...n + 1 ){\n var j = i;\n while( j <= n ){ \n door[ j ] =\u00a0! door[ j ];\n j += i;\n }\n }\n for( i in 1...n + 1 ){\n if( door[ i ] ){ Sys.print( ' $i' ); }\n }\n }\n}", "safe": true }, { "filename": "100_doors_321.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_322.txt", "content": "class RosettaDemo\n{\n static public function main()\n {\n findOpenLockers(100);\n }\n\n static function findOpenLockers(n\u00a0: Int)\n {\n var i = 1;\n\n while((i*i) <= n)\n {\n Sys.println(i*i);\n i++;\n }\n }\n}", "safe": true }, { "filename": "100_doors_323.txt", "content": "REAL\u00a0:: n=100, open=1, door(n)\n\ndoor = 1 - open\u00a0! = closed\nDO i = 1, n\n DO j = i, n, i\n door(j) = open - door(j)\n ENDDO\nENDDO\nDLG(Text=door, TItle=SUM(door)//\" doors open\")", "safe": true }, { "filename": "100_doors_324.txt", "content": "door = 1 - open\u00a0! = closed\nDO i = 1, n^0.5\n door(i*i) = open\nENDDO\nDLG(Text=door, TItle=SUM(door)//\" doors open\")", "safe": true }, { "filename": "100_doors_325.txt", "content": "U8 is_open[100];\nU8 pass = 0, door = 0;\n\n/* do the 100 passes */\nfor (pass = 0; pass < 100; ++pass)\n for (door = pass; door < 100; door += pass + 1)\n is_open[door] = !is_open[door];\n\n/* output the result */\nfor (door = 0; door < 100; ++door)\n if (is_open[door])\n Print(\"Door #%d is open.\\n\", door + 1);\n else\n Print(\"Door #%d is closed.\\n\", door + 1);", "safe": true }, { "filename": "100_doors_326.txt", "content": "|^\n=/ doors=(list\u00a0?) (reap 100\u00a0%.n)\n=/ passes=(list (list\u00a0?)) (turn (gulf 1 100) pass-n)\n|-\n?~ passes doors\n$(doors (toggle doors i.passes), passes t.passes)\n++ pass-n\n |= n=@ud\n (turn (gulf 1 100) |=(k=@ud =((mod k n) 0)))\n++ toggle\n |= [a=(list\u00a0?) b=(list\u00a0?)]\n =| c=(list\u00a0?)\n |-\n \u00a0?: |(?=(~ a)\u00a0?=(~ b)) (flop c)\n $(a t.a, b t.b, c [=((mix i.a i.b) 1) c])\n--", "safe": true }, { "filename": "100_doors_327.txt", "content": "#! /bin/sh\nexec huginn --no-argv -E \"${0}\"\n#! huginn\n\nimport Algorithms as algo;\n\nmain() {\n doorCount = 100;\n doors = [].resize( doorCount, false );\n\n for ( pass\u00a0: algo.range( doorCount ) ) {\n i = 0;\n step = pass + 1;\n while ( i < doorCount ) {\n doors[i] =\u00a0! doors[i];\n i += step;\n }\n }\n\n for ( i\u00a0: algo.range( doorCount ) ) {\n if ( doors[i] ) {\n print( \"door {} is open\\n\".format( i ) );\n }\n }\n return ( 0 );\n}", "safe": true }, { "filename": "100_doors_328.txt", "content": "(setv doors (* [False] 100))\n\n(for [pass (range (len doors))]\n (for [i (range pass (len doors) (inc pass))]\n (assoc doors i (not (get doors i)))))\n\n(for [i (range (len doors))]\n (print (.format \"Door {} is {}.\"\n (inc i)\n (if (get doors i) \"open\" \"closed\"))))", "safe": true }, { "filename": "100_doors_329.txt", "content": "software {\n\tvar doors = len(100)\n\t\n\tfor pass over [1, 100]\n\t\tvar door = pass - 1\n\t\tloop door < len(doors) {\n\t\t\tdoors[door] = doors[door]/0\n\t\t\tdoor += pass\n\t\t}\n\tend\n\t\n\tfor door,isopen in doors\n\t\tif isopen\n\t\t\tprint(\"Door \",door+1,\": open\")\n\t\tend\n\tend\n\tprint(\"All other doors are closed\")\n}", "safe": true }, { "filename": "100_doors_33.txt", "content": "begin\n \ncomment - 100 doors problem in ALGOL-60;\n \nboolean array doors[1:100];\ninteger i, j;\nboolean open, closed;\n \nopen\u00a0:= true;\nclosed\u00a0:= not true;\n \noutstring(1,\"100 Doors Problem\\n\");\n \ncomment - all doors are initially closed;\nfor i\u00a0:= 1 step 1 until 100 do\n doors[i]\u00a0:= closed;\n \ncomment\n cycle through at increasing intervals\n and flip each door encountered;\nfor i\u00a0:= 1 step 1 until 100 do\n for j\u00a0:= i step i until 100 do\n doors[j]\u00a0:= not doors[j];\n \ncomment - show which doors are open;\noutstring(1,\"The open doors are:\");\nfor i\u00a0:= 1 step 1 until 100 do\n if doors[i] then\n outinteger(1,i);\n \nend\n", "safe": true }, { "filename": "100_doors_330.txt", "content": "procedure main()\n door\u00a0:= table(0) # default value of entries is 0\n every pass\u00a0:= 1 to 100 do\n every door[i\u00a0:= pass to 100 by pass]\u00a0:= 1 - door[i]\n\n every write(\"Door \", i\u00a0:= 1 to 100, \" is \", if door[i] = 1 then \"open\" else \"closed\")\nend", "safe": true }, { "filename": "100_doors_331.txt", "content": "procedure main()\n every write(\"Door \", i\u00a0:= 1 to 100, \" is \", if integer(sqrt(i)) = sqrt(i) then \"open\" else \"closed\")\nend", "safe": true }, { "filename": "100_doors_332.txt", "content": "procedure main(args)\n dMap\u00a0:= table(\"closed\")\n every dMap[(1 to sqrt(100))^2]\u00a0:= \"open\"\n every write(\"Door \",i\u00a0:= 1 to 100,\" is \",dMap[i])\nend", "safe": true }, { "filename": "100_doors_333.txt", "content": "import Data.Vect\n\n-- Creates list from 0 to n (not including n) \nupTo\u00a0: (m\u00a0: Nat) -> Vect m (Fin m)\nupTo Z = []\nupTo (S n) = 0\u00a0:: (map FS (upTo n))\n\ndata DoorState = DoorOpen | DoorClosed\n\ntoggleDoor\u00a0: DoorState -> DoorState\ntoggleDoor DoorOpen = DoorClosed\ntoggleDoor DoorClosed = DoorOpen\n\nisOpen\u00a0: DoorState -> Bool\nisOpen DoorOpen = True\nisOpen DoorClosed = False\n\ninitialDoors\u00a0: Vect 100 DoorState\ninitialDoors = fromList $ map (\\_ => DoorClosed) [1..100]\n\niterate\u00a0: (n\u00a0: Fin m) -> Vect m DoorState -> Vect m DoorState\niterate n doors {m} = \n map (\\(idx, doorState) => \n if ((S (finToNat idx)) `mod` (S (finToNat n))) == Z \n then toggleDoor doorState \n else doorState) \n (zip (upTo m) doors)\n\n-- Returns all doors left open at the end\nsolveDoors\u00a0: List (Fin 100)\nsolveDoors = \n findIndices isOpen $ foldl (\\doors,val => iterate val doors) initialDoors (upTo 100)\n\nmain\u00a0: IO ()\nmain = print $ map (\\n => S (finToNat n)) solveDoors", "safe": true }, { "filename": "100_doors_334.txt", "content": "Hallway is a room.\n\nA toggle door is a kind of thing.\nA toggle door can be open or closed. It is usually closed.\nA toggle door has a number called the door number.\nUnderstand the door number property as referring to a toggle door.\nRule for printing the name of a toggle door: say \"door #[door number]\".\n\nThere are 100 toggle doors.\n\nWhen play begins (this is the initialize doors rule):\n\tlet the next door number be 1;\n\trepeat with D running through toggle doors:\n\t\tnow the door number of D is the next door number;\n\t\tincrement the next door number.\n\nTo toggle (D - open toggle door): now D is closed.\nTo toggle (D - closed toggle door): now D is open.\n\nWhen play begins (this is the solve puzzle rule):\n\tlet the door list be the list of toggle doors;\n\tlet the door count be the number of entries in the door list;\n\trepeat with iteration running from 1 to 100:\n\t\tlet N be the iteration;\n\t\twhile N is less than the door count:\n\t\t\ttoggle entry N in the door list;\n\t\t\tincrease N by the iteration;\n\tsay \"Doors left open: [list of open toggle doors].\";\n\tend the story.", "safe": true }, { "filename": "100_doors_335.txt", "content": "MAIN\n DEFINE\n i, pass SMALLINT,\n doors ARRAY[100] OF SMALLINT\n \n FOR i = 1 TO 100\n LET doors[i] = FALSE\n END FOR\n \n FOR pass = 1 TO 100\n FOR i = pass TO 100 STEP pass\n LET doors[i] = NOT doors[i]\n END FOR\n END FOR\n \n FOR i = 1 TO 100\n IF doors[i]\n THEN DISPLAY i USING \"Door <<& is open\"\n ELSE DISPLAY i USING \"Door <<& is closed\"\n END IF\n END FOR\nEND MAIN", "safe": true }, { "filename": "100_doors_336.txt", "content": "(var doors (times 100 false))\n\n(for i (range 1 101)\n i2 (range (dec i) 100 i)\n (var! doors (set-at [i2] (! (i2 doors))))\n (continue))\n\n(-> (xmap vec doors)\n (filter 1)\n (map (comp 0 inc))\n (join \", \")\n @(str \"open doors: \"))", "safe": true }, { "filename": "100_doors_337.txt", "content": "open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100_doors_338.txt", "content": "doors\u00a0:= List clone\n100 repeat(doors append(false))\nfor(i,1,100,\n for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not))\n)\ndoors foreach(i, x, if(x, \"Door #{i + 1} is open\" interpolate println))", "safe": true }, { "filename": "100_doors_339.txt", "content": "(Range 1 to(10) asList) foreach(v, \"Door #{v ** 2} is open.\" interpolate println)", "safe": true }, { "filename": "100_doors_34.txt", "content": "100 Doors Problem\nThe open doors are: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_340.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_341.txt", "content": "NDoors = Origin mimic\n\nNDoors Toggle = Origin mimic do(\n initialize = method(toggled?, @toggled? = toggled?)\n toggle! = method(@toggled? = !toggled?. self)\n)\n\nNDoors Doors = Origin mimic do(\n initialize = method(n,\n @n = n\n @doors = {} addKeysAndValues(1..n, (1..n) map(_, NDoors Toggle mimic(false)))\n )\n numsToToggle = method(n, for(x <- (1..@n), (x\u00a0% n) zero?, x))\n toggleThese = method(nums, nums each(x, @doors[x] = @doors at(x) toggle))\n show = method(@doors filter:dict(value toggled?) keys sort println)\n)\n\n; Test code\nx = NDoors Doors mimic(100)\n(1..100) each(n, x toggleThese(x numsToToggle(n)))\nx show", "safe": true }, { "filename": "100_doors_342.txt", "content": "theory Scratch\n imports Main\nbegin\n\nsection\u2039100 Doors\u203a\n\n datatype doorstate = Open | Closed\n \n fun toggle\u00a0:: \"doorstate \u21d2 doorstate\" where\n \"toggle Open = Closed\"\n | \"toggle Closed = Open\"\n \n fun walk\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"walk f _ _ [] = []\"\n | \"walk f every 0 (x#xs) = (f x) # walk f every every xs\"\n | \"walk f every (Suc n) (x#xs) = x # walk f every n xs\"\n \n text\u2039Example: \\<^const>\u2039toggle\u203a every second door. (second = 1, because of 0 indexing)\u203a\n lemma \"walk toggle 1 1 [Open, Open, Open, Open, Open, Open] =\n [Open, Closed, Open, Closed, Open, Closed]\" by code_simp\n \n text\u2039Example: \\<^const>\u2039toggle\u203a every third door.\u203a\n lemma \"walk toggle 2 2 [Open, Open, Open, Open, Open, Open] =\n [Open, Open, Closed, Open, Open, Closed]\" by code_simp\n \n text\u2039Walking each door is essentially the same as the common \\<^const>\u2039map\u203a function.\u203a\n lemma \"walk f 0 0 xs = map f xs\"\n by(induction xs) (simp)+\n \n lemma walk_beginning:\n \"walk f every n xs = (walk f every n (take (Suc n) xs)) @ (walk f every every (drop (Suc n) xs))\"\n by(induction f every n xs rule:walk.induct) (simp)+\n \n text\u2039A convenience definition to take the off-by-one into account and setting the starting position.\u203a\n definition visit_every\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"visit_every f every xs \u2261 walk f (every - 1) (every - 1) xs\"\n \n \n fun iterate\u00a0:: \"nat \u21d2 (nat \u21d2 'a \u21d2 'a) \u21d2 nat \u21d2 'a \u21d2 'a\" where\n \"iterate 0 _ _ a = a\"\n | \"iterate (Suc i) f n a = iterate i f (Suc n) (f n a)\"\n \n text\u2039The 100 doors problem.\u203a\n definition \"onehundred_doors \u2261 iterate 100 (visit_every toggle) 1 (replicate 100 Closed)\"\n \n lemma \"onehundred_doors =\n [Open, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Open, Closed, Closed, Closed, Closed, Closed,\n Closed, Open, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Open, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Open,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Open, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Open, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Closed, Closed, Closed, Closed, Closed, Closed,\n Closed, Open]\" by code_simp\n \n text\u2039Filtering for the open doors, we get the same result as the Haskell implementation.\u203a\n lemma\n \"[(i, door) \u2190 enumerate 1 onehundred_doors. door = Open] =\n [(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]\"\n by code_simp\n\nsection\u2039Equivalence to Haskell Implementation\u203a\ntext\u2039\nWe will now present an alternative implementation, which is similar to the Haskell implementation\non \ud83c\udf10\u2039https://rosettacode.org/wiki/100_doors#Haskell\u203a. We will prove, that the two behave the same;\nin general, not just for a fixed set of 100 doors.\n\u203a\n\n definition map_every_start\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"map_every_start f every start xs \u2261\n map (\u03bb(i, x). if i mod every = 0 then f x else x) (enumerate start xs)\"\n\n definition visit_every_alt\u00a0:: \"('a \u21d2 'a) \u21d2 nat \u21d2 'a list \u21d2 'a list\" where\n \"visit_every_alt f every xs \u2261 map_every_start f every 1 xs\"\n \n text\u2039Essentially, \\<^term>\u2039start\u203a and \\<^term>\u2039start mod every\u203a behave the same.\u203a\n lemma map_every_start_cycle:\n \"map_every_start f every (start + k*every) xs = map_every_start f every start xs\"\n proof(induction xs arbitrary: start)\n case Nil\n show \"map_every_start f every (start + k * every) [] = map_every_start f every start []\"\n by(simp add: map_every_start_def)\n next\n case (Cons x xs)\n from Cons.IH[of \"Suc start\"]\n show \"map_every_start f every (start + k * every) (x # xs) =\n map_every_start f every start (x # xs)\"\n by(simp add: map_every_start_def)\n qed\n corollary map_every_start_cycle_zero:\n \"map_every_start f every every xs = map_every_start f every 0 xs\"\n using map_every_start_cycle[where k=1 and start=0, simplified] by blast\n \n lemma map_every_start_fst_zero:\n \"map_every_start f every 0 (x # xs) = f x # map_every_start f every (Suc 0) xs\"\n by(simp add: map_every_start_def)\n \n text\u2039\n The first \\<^term>\u2039n\u203a elements are not processed by \\<^term>\u2039f\u203a,\n as long as \\<^term>\u2039n\u203a is less than the \\<^term>\u2039every\u203a cycle.\n \u00a0\u203a\n lemma map_every_start_skip_first: \"Suc n < every \u27f9\n map_every_start f every (every - (Suc n)) (x # xs) = \n x # map_every_start f every (every - n) xs\"\n by(simp add: map_every_start_def Suc_diff_Suc)\n\n lemma map_every_start_append:\n \"map_every_start f n s (ds1 @ ds2) =\n map_every_start f n s ds1 @ map_every_start f n (s + length ds1) ds2\"\n by(simp add: map_every_start_def enumerate_append_eq)\n\n text\u2039\n The \\<^const>\u2039walk\u203a function and \\<^const>\u2039map_every_start\u203a behave the same,\n as long as the starting \\<^term>\u2039n\u203a is less than the \\<^term>\u2039every\u203a cycle,\n because \\<^const>\u2039walk\u203a allows pushing the start arbitrarily far and\n \\<^const>\u2039map_every_start\u203a only allows deferring the start within\n the \\<^term>\u2039every\u203a cycle.\n This generalization is needed to strengthen the induction hypothesis\n for the proof.\n \u00a0\u203a\n lemma walk_eq_map_every_start:\n \"n \u2264 every \u27f9 walk f every n xs = map_every_start f (Suc every) (Suc every - n) xs\"\n proof(induction xs arbitrary: n)\n case Nil\n show \"walk f every n [] = map_every_start f (Suc every) (Suc every - n) []\"\n by(simp add: map_every_start_def)\n next\n case (Cons x xs)\n then show \"walk f every n (x # xs) = map_every_start f (Suc every) (Suc every - n) (x # xs)\"\n proof(cases n)\n case 0\n with Cons.IH show ?thesis \n by(simp add: map_every_start_cycle_zero map_every_start_fst_zero)\n next\n case (Suc n2)\n with Cons.prems map_every_start_skip_first[of n2 \"Suc every\"] have\n \"map_every_start f (Suc every) (Suc every - Suc n2) (x # xs) =\n x # map_every_start f (Suc every) (Suc every - n2) xs\"\n by fastforce\n with Suc Cons show ?thesis\n by(simp)\n qed\n qed\n \n corollary walk_eq_visit_every_alt:\n \"walk f every every xs = visit_every_alt f (Suc every) xs\"\n unfolding visit_every_alt_def\n using walk_eq_map_every_start by fastforce\n\n text\u2039\n Despite their very different implementations, our alternative visit function behaves the same\n as our original visit function.\n Text the theorem includes \\<^term>\u2039Suc every\u203a to express that we exclude \\<^term>\u2039every = 0\u203a.\n \u00a0\u203a\n theorem visit_every_eq_visit_every_alt:\n \"visit_every f (Suc every) xs = visit_every_alt f (Suc every) xs\"\n unfolding visit_every_def\n using walk_eq_visit_every_alt by fastforce\n\n text\u2039Also, the \\<^const>\u2039iterate\u203a function we implemented above can be implemented by a simple \\<^const>\u2039fold\u203a.\u203a\n lemma fold_upt_helper: assumes n_geq_1: \"Suc 0 \u2264 n\"\n shows \"fold f [Suc s..:i.100\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n ~:/ 0=|/~ >:i.100 NB. alternative\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n (*/\"1)2|>:_ q:>:i.100 NB. alternative", "safe": true }, { "filename": "100_doors_344.txt", "content": " (e. *:) 1+i.100\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...\n 1 (<:*:i.10)} 100$0 NB. alternative\n1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...", "safe": true }, { "filename": "100_doors_345.txt", "content": " 'these doors are open: ',\": I. (i.101) e. *: 1+i.10\nthese doors are open: 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_346.txt", "content": "(def doors (seq [_ :range [0 100]] false))\n\n(loop [pass :range [0 100]\n door :range [pass 100 (inc pass)]]\n (put doors door (not (doors door))))\n\n(print \"open doors: \"\u00a0;(seq [i :range [0 100] :when (doors i)] (string (inc i) \" \")))", "safe": true }, { "filename": "100_doors_347.txt", "content": "open doors: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_348.txt", "content": "class HundredDoors {\n public static void main(String[] args) {\n boolean[] doors = new boolean[101];\n\n for (int i = 1; i < doors.length; i++) {\n for (int j = i; j < doors.length; j += i) {\n doors[j] = !doors[j];\n }\n }\n\n for (int i = 1; i < doors.length; i++) {\n if (doors[i]) {\n System.out.printf(\"Door %d is open.%n\", i);\n }\n }\n }\n}", "safe": true }, { "filename": "100_doors_349.txt", "content": "import java.util.BitSet;\n\npublic class HundredDoors {\n public static void main(String[] args) {\n final int n = 100;\n var a = new BitSet(n);\n for (int i = 1; i <= n; i++) {\n for (int j = i - 1; j < n; j += i) {\n a.flip(j);\n }\n }\n a.stream().map(i -> i + 1).forEachOrdered(System.out::println);\n }\n}", "safe": true }, { "filename": "100_doors_35.txt", "content": "PROC doors = (INT limit)VOID:\n(\n MODE DOORSTATE = BOOL;\n BOOL closed = FALSE;\n BOOL open = NOT closed;\n MODE DOORLIST = [limit]DOORSTATE;\n\n DOORLIST the doors;\n FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD;\n\n FOR i FROM LWB the doors TO UPB the doors DO\n FOR j FROM LWB the doors BY i TO UPB the doors DO\n the doors[j]\u00a0:= NOT the doors[j]\n OD\n OD;\n FOR i FROM LWB the doors TO UPB the doors DO\n print((whole(i,-12),\" is \",(the doors[i]|\"opened\"|\"closed\"),newline))\n OD\n);\ndoors(100)\n", "safe": true }, { "filename": "100_doors_350.txt", "content": "class HundredDoors {\n public static void main(String[] args) {\n for (int i = 1; i <= 10; i++)\n System.out.printf(\"Door %d is open.%n\", i * i);\n }\n}", "safe": true }, { "filename": "100_doors_351.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_352.txt", "content": "import java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\nclass HundredDoors {\n public static void main(String args[]) {\n String openDoors = IntStream.rangeClosed(1, 100)\n .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i)\n .mapToObj(Integer::toString)\n .collect(Collectors.joining(\", \"));\n System.out.printf(\"Open doors: %s%n\", openDoors);\n }\n}", "safe": true }, { "filename": "100_doors_353.txt", "content": "Open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100_doors_354.txt", "content": "var doors=[];\nfor (var i=0;i<100;i++)\n doors[i]=false;\nfor (var i=1;i<=100;i++)\n for (var i2=i-1;i2<100;i2+=i)\n doors[i2]=!doors[i2];\nfor (var i=1;i<=100;i++)\n console.log(\"Door %d is %s\",i,doors[i-1]?\"open\":\"closed\")", "safe": true }, { "filename": "100_doors_355.txt", "content": "(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\u00a0% m\u00a0? x[1]\u00a0: !x[1]];\n });\n }, zip(\n lstRange,\n replicate(n, false)\n ));\n };\n function zip(xs, ys) {\n return xs.length === ys.length\u00a0? (\n xs.map(function (x, i) {\n return [x, ys[i]];\n })\n )\u00a0: 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\u00a0? n - m\u00a0: 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);", "safe": true }, { "filename": "100_doors_356.txt", "content": "for (var door = 1; door <= 100; door++) {\n var sqrt = Math.sqrt(door);\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door %d is open\", door);\n }\n}", "safe": true }, { "filename": "100_doors_357.txt", "content": "for(var door=1;i<10/*Math.sqrt(100)*/;i++){\n console.log(\"Door %d is open\",i*i);\n}", "safe": true }, { "filename": "100_doors_358.txt", "content": "(function (n) {\n \"use strict\";\n return range(1, 100)\n .filter(function (x) {\n return integerFactors(x)\n .length\u00a0% 2;\n });\n function integerFactors(n) {\n var rRoot = Math.sqrt(n),\n intRoot = Math.floor(rRoot),\n lows = range(1, intRoot)\n .filter(function (x) {\n return (n\u00a0% x) === 0;\n });\n return lows.concat(lows.map(function (x) {\n return n / x;\n })\n .reverse()\n .slice((rRoot === intRoot) | 0));\n }\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp\u00a0? n - m\u00a0: 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})(100);", "safe": true }, { "filename": "100_doors_359.txt", "content": "(function (n) {\n \"use strict\";\n return perfectSquaresUpTo(100);\n function perfectSquaresUpTo(n) {\n return range(1, Math.floor(Math.sqrt(n)))\n .map(function (x) {\n return x * x;\n });\n }\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp\u00a0? n - m\u00a0: 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})(100);", "safe": true }, { "filename": "100_doors_36.txt", "content": "PROC doors optimised = ( INT limit )VOID:\n FOR i TO limit DO\n REAL num\u00a0:= sqrt(i);\n print((whole(i,0),\" is \",(ENTIER num = num |\"opened\"|\"closed\"),newline))\n OD\n;\ndoors optimised(100)\n", "safe": true }, { "filename": "100_doors_360.txt", "content": "Array.apply(null, { length: 100 })\n .map((v, i) => i + 1)\n .forEach(door => { \n var sqrt = Math.sqrt(door); \n\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door %d is open\", door);\n } \n });", "safe": true }, { "filename": "100_doors_361.txt", "content": "// Array comprehension style\n[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { \n var door = i + 1\n var sqrt = Math.sqrt(door); \n\n if (sqrt === (sqrt | 0)) {\n console.log(\"Door \" + door + \" is open\");\n } \n});", "safe": true }, { "filename": "100_doors_362.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100_doors_363.txt", "content": "(function (n) {\n \n \n // ONLY PERFECT SQUARES HAVE AN ODD NUMBER OF INTEGER FACTORS\n // (Leaving the door open at the end of the process) \n \n return perfectSquaresUpTo(n);\n \n \n // perfectSquaresUpTo\u00a0:: Int -> [Int]\n function perfectSquaresUpTo(n) {\n return range(1, Math.floor(Math.sqrt(n)))\n .map(x => x * x);\n }\n \n \n // GENERIC\n \n // range(intFrom, intTo, optional intStep)\n // Int -> Int -> Maybe Int -> [Int]\n function range(m, n, step) {\n let d = (step || 1) * (n >= m\u00a0? 1\u00a0: -1);\n \n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, (_, i) => m + (i * d));\n }\n \n})(100);", "safe": true }, { "filename": "100_doors_364.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_365.txt", "content": "\"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\u00a0? closed\u00a0: 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\u00a0? 'opened'\u00a0: '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.\";", "safe": true }, { "filename": "100_doors_366.txt", "content": "# Solution for n doors:\ndef doors(n):\n\n def print:\n . as $doors\n | range(1; length+1)\n | if $doors[.] then \"Door \\(.) is open\" else empty end;\n\n [range(n+1)|null] as $doors\n | reduce range(1; n+1) as $run\n ( $doors; reduce range($run; n+1; $run ) as $door\n ( .; .[$door] = (.[$door] | not) ) )\n | print\u00a0;", "safe": true }, { "filename": "100_doors_367.txt", "content": "# Solution for 100 doors:\ndef solution:\n range(1;11) | \"Door \\(. * .) is open\";", "safe": true }, { "filename": "100_doors_368.txt", "content": "doors = falses(100)\nfor a in 1:100, b in a:a:100\n doors[b] = !doors[b]\nend\nfor a = 1:100\n println(\"Door $a is \" * (doors[a]\u00a0? \"open.\"\u00a0: \"closed.\")) \nend", "safe": true }, { "filename": "100_doors_369.txt", "content": "for i in 1:10 println(\"Door $(i^2) is open.\") end", "safe": true }, { "filename": "100_doors_37.txt", "content": "begin\n % find the first few squares via the unoptimised door flipping method \u00a0%\n \n integer doorMax;\n doorMax\u00a0:= 100;\n \n begin\n % need to start a new block so the array can have variable bounds \u00a0%\n \n % array of doors - door( i ) is true if open, false if closed \u00a0%\n logical array door( 1\u00a0:: doorMax );\n \n % set all doors to closed \u00a0%\n for i\u00a0:= 1 until doorMax do door( i )\u00a0:= false;\n \n % repeatedly flip the doors \u00a0%\n for i\u00a0:= 1 until doorMax\n do begin\n for j\u00a0:= i step i until doorMax\n do begin\n door( j )\u00a0:= not door( j )\n end\n end;\n \n % display the results \u00a0%\n i_w\u00a0:= 1; % set integer field width \u00a0%\n s_w\u00a0:= 1; % and separator width \u00a0%\n for i\u00a0:= 1 until doorMax do if door( i ) then writeon( i )\n \n end\n \nend.\n", "safe": true }, { "filename": "100_doors_370.txt", "content": " doors:{`closed`open![;2]@#:'1_=,/&:'0=t!\\:/:t:!101}", "safe": true }, { "filename": "100_doors_371.txt", "content": " (1+!10)^2\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_372.txt", "content": " {(1+!_ x^%2)^2}100\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_373.txt", "content": "include ..\\Utilitys.tlhy\n\n%n 100 !n\n0 $n repeat\n\n$n [dup sqrt int dup * over\n== ( [1 swap set] [drop] ) if] for\n\n$n [ ( \"The door \" over \" is \" ) lprint get ( [\"OPEN\"] [\"closed\"] ) if print nl] for\n\n( \"Time elapsed: \" msec \" seconds\" ) lprint nl\n\npstack\n\" \" input", "safe": true }, { "filename": "100_doors_374.txt", "content": "flip::{,/{(1-*x),1_x}'x:#y}\ni::0;(100{i::i+1;flip(i;x)}:*100:^0)?1", "safe": true }, { "filename": "100_doors_375.txt", "content": "(1+!9)^2", "safe": true }, { "filename": "100_doors_376.txt", "content": "type state\n Open\n Closed\n\nfun toggle(self: state): state\n match self\n Open -> Closed\n Closed -> Open\n\ninline extern unsafe-assign\u00a0: forall
( v\u00a0: vector, i\u00a0: ssize_t, x\u00a0: a ) -> total ()\n c \"kk_vector_unsafe_assign\"\n\nfun main()\n val doors = vector(100, Closed)\n for(0,99) fn(pass)\n var door\u00a0:= pass\n while { door < 99 }\n doors.unsafe-assign(door.ssize_t, doors[door].toggle)\n door\u00a0:= door + (pass+1)\n doors.foreach-indexed fn(idx, it)\n match it\n Open -> println(\"door \" ++ (idx + 1).show ++ \" is open\")\n Closed -> println(\"door \" ++ (idx + 1).show ++ \" is closed\")", "safe": true }, { "filename": "100_doors_377.txt", "content": "fun main()\n val doors = list(0,99,1,fn(i) Closed)\n val transformed = list(1,99).foldl(doors) fn(drs, pass)\n drs.map-indexed fn(i, door)\n if ((i + 1)\u00a0% pass) == 0 then door.toggle else door\n transformed.foreach-indexed fn(idx, it)\n match it\n Open -> println(\"door \" ++ (idx + 1).show ++ \" is open\")\n Closed -> println(\"door \" ++ (idx + 1).show ++ \" is closed\")", "safe": true }, { "filename": "100_doors_378.txt", "content": "fun oneHundredDoors(): List {\n val doors = BooleanArray(100) { false }\n\n repeat(doors.size) { i ->\n for (j in i until doors.size step (i + 1)) {\n doors[j] = !doors[j]\n }\n }\n\n return doors\n .foldIndexed(emptyList()) { i, acc, door ->\n if (door) acc + (i + 1) else acc\n }\n}", "safe": true }, { "filename": "100_doors_379.txt", "content": "range InitialDoor from 1 to 100 step 1\n| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)\n| mvexpand DoorVisited=DoorsVisited to typeof(int)\n| summarize VisitCount=count() by DoorVisited\n| project Door=DoorVisited, IsOpen=(VisitCount\u00a0% 2) == 1", "safe": true }, { "filename": "100_doors_38.txt", "content": " 1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100_doors_380.txt", "content": "1) unoptimized version\n\n{def doors\n {A.new\n {S.map {lambda {} false} {S.serie 1 100}}}}\n-> doors\n\n{def toggle\n {lambda {:i :a}\n {let { {_ {A.set! :i {not {A.get :i :a}} :a} }}}}}\n-> toggle\n\n{S.map {lambda {:b} \n {S.map {lambda {:i} {toggle :i {doors}}} \n {S.serie :b 99 {+ :b 1}}}}\n {S.serie 0 99}} \n->\n\n{S.replace \\s by space in \n {S.map {lambda {:i} {if {A.get :i {doors}} then {+ :i 1} else}} \n {S.serie 0 99}}}\n\n-> 1 4 9 16 25 36 49 64 81 100\n\n2.2) optimized version\n\n{S.replace \\s by space in \n {S.map {lambda {:i}\n {let { {:root {sqrt :i}} } \n {if {= :root {round :root}} \n then {* :root :root}\n else}}}\n {S.serie 1 100}}}\n\n-> 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_381.txt", "content": "&doors = fn.arrayGenerateFrom(fn.inc, 100)\nfp.mapper = ($i) -> {\n\t$n\n\t$open = 0\n\trepeat($[n], 100) {\n\t\t$open $= $i\u00a0% +|$n?!$open:$open\n\t}\n\t\n\treturn $open\n}\nfn.arrayMap(&doors, fp.mapper)\n\nfn.print(Open doors:)\n$i\nrepeat($[i], @&doors) {\n\tif(&doors[$i]) {\n\t\tfn.printf(\\s%03d, parser.op(+|$i))\n\t}\n}\nfn.println()", "safe": true }, { "filename": "100_doors_382.txt", "content": "Open doors: 001 004 009 016 025 036 049 064 081 100\n", "safe": true }, { "filename": "100_doors_383.txt", "content": "var doors = [false] * 100\n\nfor i of doors {\n for j = i; j <= len(doors); j += i {\n doors[j] = not doors[j]\n }\n}\n\nwriteln for[=[]] i of doors { if doors[i]: _for = more(_for, i) }", "safe": true }, { "filename": "100_doors_384.txt", "content": "writeln foldfrom(fn a, b, c: if(b: a~[c]; a), [], doors, series(1..len(doors)))", "safe": true }, { "filename": "100_doors_385.txt", "content": "writeln map(fn{^2}, 1..10)", "safe": true }, { "filename": "100_doors_386.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_387.txt", "content": "loop(100) => {^\n\tlocal(root = math_sqrt(loop_count))\n\tlocal(state = (#root == math_ceil(#root)\u00a0? 'open' | 'closed'))\n\t#state\u00a0!= 'closed'\u00a0? 'Door ' + loop_count + ': ' + #state + '
'\n^}", "safe": true }, { "filename": "100_doors_388.txt", "content": "Door 1: open\nDoor 4: open\nDoor 9: open\nDoor 16: open\nDoor 25: open\nDoor 36: open\nDoor 49: open\nDoor 64: open\nDoor 81: open\nDoor 100: open", "safe": true }, { "filename": "100_doors_389.txt", "content": "use 'format importAllSigils.\n\ndoors\u00a0:= Object clone.\ndoors missing\u00a0:= { False. }.\ndoors check\u00a0:= {\n self slot ($1 ordinal).\n}.\ndoors toggle\u00a0:= {\n self slot ($1 ordinal) = self slot ($1 ordinal) not.\n}.\n1 upto 101 do {\n takes '[i].\n local 'j = i.\n while { j <= 100. } do {\n doors toggle (j).\n j = j + i.\n }.\n}.\n$stdout printf: ~fmt \"The open doors are: ~A\", 1 upto 101 filter { doors check. } to (Array).", "safe": true }, { "filename": "100_doors_39.txt", "content": "BEGIN\n\nINTEGER ARRAY DOORS[1:100];\nINTEGER I, J, OPEN, CLOSED;\n\nOPEN\u00a0:= 1;\nCLOSED\u00a0:= 0;\n\n% ALL DOORS ARE INITIALLY CLOSED\u00a0%\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n DOORS[I]\u00a0:= CLOSED;\n END;\n\n% PASS THROUGH AT INCREASING INTERVALS AND FLIP\u00a0%\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n FOR J\u00a0:= I STEP I UNTIL 100 DO\n BEGIN\n DOORS[J]\u00a0:= 1 - DOORS[J];\n END;\n END;\n\n% SHOW RESULTS\u00a0%\nWRITE(\"THE OPEN DOORS ARE:\");\nWRITE(\"\");\nFOR I\u00a0:= 1 STEP 1 UNTIL 100 DO\n BEGIN\n IF DOORS[I] = OPEN THEN\n WRITEON(I);\n END;\n\nEND", "safe": true }, { "filename": "100_doors_390.txt", "content": "to doors\n\t;Problem 100 Doors \n\t;Lhogho\n\n\tfor \"p [1 100] \n\t[\n\t\tmake :p \"false\n\t]\n\n\tfor \"a [1 100 1]\n\t[\n\t\tfor \"b [:a 100 :a]\n\t\t[\n\t\t\tif :b < 101 \n\t\t\t[\n\t\t\t\tmake :b not thing :b\n\t\t\t]\n\t\t]\n\t]\n\n\tfor \"c [1 100]\n\t[\n\t\tif thing :c \n\t\t[ \n\t\t\t(print \"door :c \"is \"open) \n\t\t]\n\t] \nend\n\ndoors", "safe": true }, { "filename": "100_doors_391.txt", "content": "dim doors(100)\nfor pass = 1 to 100\n for door = pass to 100 step pass\n doors(door) = not(doors(door))\n next door\nnext pass\nprint \"open doors \";\nfor door = 1 to 100\n if doors(door) then print door;\" \";\nnext door", "safe": true }, { "filename": "100_doors_392.txt", "content": "var doors = List.fill(100, false)\n\nfor i in 0...99:\n for j in i...99 by i + 1:\n doors[j] = !doors[j]\n\n# The type must be specified since the list starts off empty.\nvar open_doors: List[Integer] = []\n\ndoors.each_index{|i|\n if doors[i]:\n open_doors.push(i + 1)\n}\n\nprint($\"Open doors: ^(open_doors)\")", "safe": true }, { "filename": "100_doors_393.txt", "content": "Open doors: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_394.txt", "content": "on mouseUp \n repeat with tStep = 1 to 100\n repeat with tDoor = tStep to 100 step tStep\n put not tDoors[tDoor] into tDoors[tDoor]\n end repeat\n if tDoors[tStep] then put \"Door \" & tStep & \" is open\" & cr after tList\n end repeat\n set the text of field \"Doors\" to tList\nend mouseUp", "safe": true }, { "filename": "100_doors_395.txt", "content": "to doors\n;Problem 100 Doors \n;FMSLogo\n;lrcvs 2010\n\nmake \"door (vector 100 1) \nfor [p 1 100][setitem :p :door 0] \n \nfor [a 1 100 1][for [b :a 100 :a][make \"x item :b :door \n\t ifelse :x = 0 [setitem :b :door 1][setitem :b :door 0] ] ] \n \nfor [c 1 100][make \"y item :c :door \n\t ifelse :y = 0 [pr (list :c \"Close)] [pr (list :c \"Open)] ] \nend", "safe": true }, { "filename": "100_doors_396.txt", "content": "HAI 1.3\n\nI HAS A doors ITZ A BUKKIT\nIM IN YR hallway UPPIN YR door TIL BOTH SAEM door AN 100\n doors HAS A SRS door ITZ FAIL BTW, INISHULIZE ALL TEH DOORZ AS CLOZD\nIM OUTTA YR hallway\n\nIM IN YR hallway UPPIN YR pass TIL BOTH SAEM pass AN 100\n I HAS A door ITZ pass\n IM IN YR passer\n doors'Z SRS door R NOT doors'Z SRS door\n door R SUM OF door AN SUM OF pass AN 1\n DIFFRINT door AN SMALLR OF door AN 99, O RLY?\n YA RLY, GTFO\n OIC\n IM OUTTA YR passer\nIM OUTTA YR hallway\n\nIM IN YR printer UPPIN YR door TIL BOTH SAEM door AN 100\n VISIBLE \"Door #\" SUM OF door AN 1 \" is \"!\n doors'Z SRS door, O RLY?\n YA RLY, VISIBLE \"open.\"\n NO WAI, VISIBLE \"closed.\"\n OIC\nIM OUTTA YR printer\n\nKTHXBYE", "safe": true }, { "filename": "100_doors_397.txt", "content": "local is_open = {}\n\nfor pass = 1,100 do\n for door = pass,100,pass do\n is_open[door] = not is_open[door]\n end\nend\n\nfor i,v in next,is_open do\n print ('Door '..i..':',v and 'open' or 'close')\nend", "safe": true }, { "filename": "100_doors_398.txt", "content": "Module Doors100 {\n Dim Doors(1 to 100)\n For i=1 to 100\n For j=i to 100 step i\n Doors(j)~\n Next j\n Next i\n DispAll()\n ' optimization\n Dim Doors(1 to 100)=False\n For i=1 to 10\n Doors(i**2)=True\n Next i\n Print\n DispAll()\n Sub DispAll()\n Local i\n For i=1 to 100\n if Doors(i) then print i,\n Next i\n Print\n End Sub\n}\nDoors100", "safe": true }, { "filename": "100_doors_399.txt", "content": "define(`_set', `define(`$1[$2]', `$3')')dnl\ndefine(`_get', `defn(`$1[$2]')')dnl\ndefine(`for',`ifelse($#,0,``$0'',`ifelse(eval($2<=$3),1,\n`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl\ndefine(`opposite',`_set(`door',$1,ifelse(_get(`door',$1),`closed',`open',`closed'))')dnl\ndefine(`upper',`100')dnl\nfor(`x',`1',upper,`1',`_set(`door',x,`closed')')dnl\nfor(`x',`1',upper,`1',`for(`y',x,upper,x,`opposite(y)')')dnl\nfor(`x',`1',upper,`1',`door x is _get(`door',x)\n')dnl", "safe": true }, { "filename": "100_doors_4.txt", "content": "@echo off\nset doors=%@repeat[C,100]\ndo step = 1 to 100\n do door = %step to 100 by %step\n set doors=%@left[%@eval[%door-1],%doors]%@if[%@instr[%@eval[%door-1],1,%doors]==C,O,C]%@right[%@eval[100-%door],%doors]\n enddo\nenddo", "safe": true }, { "filename": "100_doors_40.txt", "content": "THE OPEN DOORS ARE:\n 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_400.txt", "content": " .TITLE DOORS\n .MCALL .TTYOUT,.EXIT\nNDOORS = ^D100\nDOORS::\n \u00a0; CLOSE ALL DOORS\n MOV #DOORBF+1,R0\nCLOSE: CLR (R0)+\n CMP R0,#BUFTOP\n BLT CLOSE\n\n \u00a0; VISIT DOORS\n MOV #1,R1 \u00a0; R1 = PASS\nPASS: MOV R1,R2 \u00a0; R2 = DOOR\nDOOR: COMB DOORBF(R2) \u00a0; VISIT DOOR\n ADD R1,R2\n CMP R2,#NDOORS \u00a0; NEXT DOOR\n BLE DOOR\n INC R1\n CMP R1,R2 \u00a0; NEXT PASS\n BLE PASS\n\n \u00a0; DISPLAY DOORS AS ASCII 0 OR 1\n MOV #DOORBF+1,R1\nDISP: MOVB (R1)+,R0\n BICB #^C1,R0\n BISB #^D48,R0\n .TTYOUT\n CMP R1,#BUFTOP\n BLT DISP\n\n .EXIT\nDOORBF: .BLKB NDOORS+1\nBUFTOP = .\n .END DOORS", "safe": true }, { "filename": "100_doors_401.txt", "content": "1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100_doors_402.txt", "content": " NORMAL MODE IS INTEGER\n DIMENSION OPEN(100)\n PRINT COMMENT $ $\n \n R MAKE SURE ALL DOORS ARE CLOSED AT BEGINNING\n THROUGH CLOSE, FOR DOOR=1, 1, DOOR.G.100\nCLOSE OPEN(DOOR) = 0\n\n R MAKE 100 PASSES\n THROUGH TOGGLE, FOR PASS=1, 1, PASS.G.100\n THROUGH TOGGLE, FOR DOOR=PASS, PASS, DOOR.G.100\nTOGGLE OPEN(DOOR) = 1 - OPEN(DOOR) \n\n R PRINT THE DOORS THAT ARE OPEN\n THROUGH SHOW, FOR DOOR=1, 1, DOOR.G.100\nSHOW WHENEVER OPEN(DOOR).E.1, PRINT FORMAT ISOPEN, DOOR\n \n VECTOR VALUES ISOPEN = $5HDOOR ,I3,S1,8HIS OPEN.*$ \n END OF PROGRAM", "safe": true }, { "filename": "100_doors_403.txt", "content": "DOOR 1 IS OPEN.\nDOOR 4 IS OPEN.\nDOOR 9 IS OPEN.\nDOOR 16 IS OPEN.\nDOOR 25 IS OPEN.\nDOOR 36 IS OPEN.\nDOOR 49 IS OPEN.\nDOOR 64 IS OPEN.\nDOOR 81 IS OPEN.\nDOOR 100 IS OPEN.", "safe": true }, { "filename": "100_doors_404.txt", "content": ".DEFAULT_GOAL:=100\ndigit=1 2 3 4 5 6 7 8 9\ndoors:=$(digit) $(foreach i,$(digit),$(foreach j,0 $(digit),$i$j)) 100\n$(doors):;@: $(if $(filter %1 %3 %5 %7 %9,$(words $^)),$(info $@))\n$(foreach i,$(doors),$(eval $i: $(word $i,0 $(doors))))\n0 $(addprefix pass,$(doors)):\npass:=X\ndep=$(eval count+=$(pass))$(eval $(words $(count)):pass$(words $(pass)))\nloop=$(foreach inner,$(doors),$(if $(word 101,$(count)),,$(dep)))\n$(foreach outer,$(doors),$(eval pass+=X)$(eval count:=)$(loop))", "safe": true }, { "filename": "100_doors_405.txt", "content": "NDoors\u00a0:= proc( N\u00a0:: posint )\n # Initialise, using 0 to represent \"closed\"\n local pass, door, doors\u00a0:= Array( 1 .. N, 'datatype' = 'integer'[ 1 ] );\n # Now do N passes\n for pass from 1 to N do\n for door from pass by pass while door <= N do\n doors[ door ]\u00a0:= 1 - doors[ door ]\n end do\n end do;\n # Output\n for door from 1 to N do\n printf( \"Door %d is %s.\\n\", door, `if`( doors[ door ] = 0, \"closed\", \"open\" ) )\n end do;\n # Since this is a printing routine, return nothing.\n NULL\nend proc:", "safe": true }, { "filename": "100_doors_406.txt", "content": "> NDoors( 100 );", "safe": true }, { "filename": "100_doors_407.txt", "content": "> seq( i^2, i = 1 .. isqrt( 100 ) );\n 1, 4, 9, 16, 25, 36, 49, 64, 81, 100", "safe": true }, { "filename": "100_doors_408.txt", "content": "> [seq]( 1 .. 10 )^~2;\n [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_409.txt", "content": "n=100;\ntmp=ConstantArray[-1,n];\nDo[tmp[[i;;;;i]]*=-1;,{i,n}];\nDo[Print[\"door \",i,\" is \",If[tmp[[i]]==-1,\"closed\",\"open\"]],{i,1,Length[tmp]}]", "safe": true }, { "filename": "100_doors_41.txt", "content": "PROC main()\n DEF t[100]: ARRAY,\n pass, door\n FOR door\u00a0:= 0 TO 99 DO t[door]\u00a0:= FALSE\n FOR pass\u00a0:= 0 TO 99\n door\u00a0:= pass\n WHILE door <= 99\n t[door]\u00a0:= Not(t[door])\n door\u00a0:= door + pass + 1\n ENDWHILE\n ENDFOR\n FOR door\u00a0:= 0 TO 99 DO WriteF('\\d is \\s\\n', door+1,\n IF t[door] THEN 'open' ELSE 'closed')\nENDPROC", "safe": true }, { "filename": "100_doors_410.txt", "content": "f[n_] = \"Closed\"; \nDo[Do[If[f[n] == \"Closed\", f[n] = \"Open\", f[n] = \"Closed\"], {n, k, 100, k}], {k, 1, 100}]; \nTable[f[n], {n, 1, 100}]", "safe": true }, { "filename": "100_doors_411.txt", "content": "Fold[\n ReplacePart[#1, (i_ /; Mod[i, #2] == 0)\u00a0:> (-#1[[i]])] &,\n ConstantArray[-1, {100}],\n Range[100]\n] /. {1 -> \"Open\", -1 -> \"Closed\"}", "safe": true }, { "filename": "100_doors_412.txt", "content": "Do[Print[\"door \",i,\" is \",If[IntegerQ[Sqrt[i]],\"open\",\"closed\"]],{i,100}]", "safe": true }, { "filename": "100_doors_413.txt", "content": "n=100;\na=Range[1,Sqrt[n]]^2\nDo[Print[\"door \",i,\" is \",If[MemberQ[a,i],\"open\",\"closed\"]],{i,100}]", "safe": true }, { "filename": "100_doors_414.txt", "content": "n=100\nnn=1\na=0\nFor[i=1,i<=n,i++,\n If[i==nn,\n Print[\"door \",i,\" is open\"];\n a++;\n nn+=2a+1;\n ,\n Print[\"door \",i,\" is closed\"];\n ];\n]", "safe": true }, { "filename": "100_doors_415.txt", "content": "Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]]", "safe": true }, { "filename": "100_doors_416.txt", "content": "Range[Sqrt[100]]^2", "safe": true }, { "filename": "100_doors_417.txt", "content": "a = false(1,100);\nfor b=1:100\n for i = b:b:100\n a(i) = ~a(i);\n end\nend\na", "safe": true }, { "filename": "100_doors_418.txt", "content": "for x=1:100;\n if sqrt(x) == floor(sqrt(x))\n a(i)=1;\n end\nend\na", "safe": true }, { "filename": "100_doors_419.txt", "content": "doors = zeros(1,100); // 0: closed 1: open\nfor i = 1:100\n doors(i:i:100) = 1-doors(i:i:100)\nend\ndoors", "safe": true }, { "filename": "100_doors_42.txt", "content": "doors\u2190{100\u2374((\u2375-1)\u23740),1}\n\u2260\u233f\u2283doors\u00a8 \u2373100\n", "safe": true }, { "filename": "100_doors_420.txt", "content": "a = zeros(100,1);\nfor counter = 1:sqrt(100);\n a(counter^2) = 1;\nend\na", "safe": true }, { "filename": "100_doors_421.txt", "content": "function [doors,opened,closed] = hundredDoors()\n\n %Initialize the doors, make them booleans for easy vectorization\n doors = logical( (1:1:100) );\n \n %Go through the flipping process, ignore the 1 case because the doors\n %array is already initialized to all open\n for initialPosition = (2:100)\n doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) );\n end\n \n opened = find(doors); %Stores the numbers of the open doors\n closed = find( not(doors) ); %Stores the numbers of the closed doors\n \nend", "safe": true }, { "filename": "100_doors_422.txt", "content": "doors((1:10).^2) = 1;\n\ndoors", "safe": true }, { "filename": "100_doors_423.txt", "content": "doors(n)\u00a0:= block([v], local(v),\n v: makelist(true, n),\n for i: 2 thru n do\n for j: i step i thru n do v[j]: not v[j],\n sublist_indices(v, 'identity));", "safe": true }, { "filename": "100_doors_424.txt", "content": "doors(100);\n/* [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] */", "safe": true }, { "filename": "100_doors_425.txt", "content": "doorsOpen = for i in 1 to 100 collect false\n\nfor pass in 1 to 100 do\n(\n for door in pass to 100 by pass do\n (\n doorsOpen[door] = not doorsOpen[door]\n )\n)\n\nfor i in 1 to doorsOpen.count do\n(\n format (\"Door\u00a0% is open?:\u00a0%\\n\") i doorsOpen[i]\n)", "safe": true }, { "filename": "100_doors_426.txt", "content": "for i in 1 to 100 do\n(\n root = pow i 0.5\n format (\"Door\u00a0% is open?:\u00a0%\\n\") i (root == (root as integer))\n)", "safe": true }, { "filename": "100_doors_427.txt", "content": ":- module doors.\n:- interface.\n:- import_module io.\n:- pred main(io::di, io::uo) is det.\n:- implementation.\n:- import_module bitmap, bool, list, string, int.\n\n:- func doors = bitmap.\ndoors = bitmap.init(100, no).\n\n:- pred walk(int, bitmap, bitmap).\n:- mode walk(in, bitmap_di, bitmap_uo) is det.\nwalk(Pass, !Doors)\u00a0:-\n walk(Pass, Pass, !Doors).\n\n:- pred walk(int, int, bitmap, bitmap).\n:- mode walk(in, in, bitmap_di, bitmap_uo) is det.\nwalk(At, By, !Doors)\u00a0:-\n ( if bitmap.in_range(!.Doors, At - 1) then\n bitmap.unsafe_flip(At - 1, !Doors),\n walk(At + By, By, !Doors)\n else\n true\n ).\n\n:- pred report(bitmap, int, io, io).\n:- mode report(bitmap_di, in, di, uo) is det.\nreport(Doors, N, !IO)\u00a0:-\n ( if is_set(Doors, N - 1) then\n State = \"open\"\n else\n State = \"closed\"\n ),\n io.format(\"door #%d is %s\\n\",\n [i(N), s(State)], !IO).\n\nmain(!IO)\u00a0:-\n list.foldl(walk, 1 .. 100, doors, Doors),\n list.foldl(report(Doors), 1 .. 100, !IO).", "safe": true }, { "filename": "100_doors_428.txt", "content": "boolean doors[];\nfor i = 1 upto 100: doors[i]\u00a0:= false; endfor\nfor i = 1 upto 100:\n for j = 1 step i until 100:\n doors[j]\u00a0:= not doors[j];\n endfor\nendfor\nfor i = 1 upto 100:\n message decimal(i) & \" \" & if doors[i]: \"open\" else: \"close\" fi;\nendfor\nend", "safe": true }, { "filename": "100_doors_429.txt", "content": "For offset = 1 To 100\n For i = 0 To 100 Step offset\n a[i] = a[i] + 1\n EndFor\nEndFor\n' Print \"opened\" doors\nFor i = 1 To 100\n If math.Remainder(a[i], 2) = 1 Then \n TextWindow.WriteLine(i)\n EndIf \nEndFor", "safe": true }, { "filename": "100_doors_43.txt", "content": "2|+/[1]0=D\u2218.|D\u2190\u2373100\n", "safe": true }, { "filename": "100_doors_430.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100_doors_431.txt", "content": "d = {}\nfor p in range(1, 100)\n for t in range(p, 100, p)\n if d.hasIndex(t) then d.remove t else d.push t\n end for\nend for\n\nprint d.indexes.sort", "safe": true }, { "filename": "100_doors_432.txt", "content": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]", "safe": true }, { "filename": "100_doors_433.txt", "content": "d = [false] * 101\nopen = []\nfor p in range(1, 100)\n for t in range(p, 100, p)\n d[t] = not d[t]\n end for\n if d[p] then open.push p\nend for\n\nprint open", "safe": true }, { "filename": "100_doors_434.txt", "content": ".data\n doors: .space 100\n num_str: .asciiz \"Number \"\n comma_gap: .asciiz \" is \"\n newline: .asciiz \"\\n\"\n\n.text\nmain:\n# Clear all the cells to zero\n li $t1, 100\n la $t2, doors\nclear_loop:\n sb $0, ($t2)\n add $t2, $t2, 1\n sub $t1, $t1, 1\n bnez $t1, clear_loop\n\n# Now start the loops\n li $t0, 1 # This will the the step size\n li $t4, 1 # just an arbitrary 1\nloop1:\n move $t1, $t0 # Counter\n la $t2, doors # Current pointer\n add $t2, $t2, $t0\n addi $t2, $t2, -1\nloop2:\n lb $t3, ($t2)\n sub $t3, $t4, $t3\n sb $t3, ($t2)\n add $t1, $t1, $t0\n add $t2, $t2, $t0\n ble $t1, 100, loop2\n\n addi $t0, $t0, 1\n ble $t0, 100, loop1\n\n # Now display everything\n la $t0, doors\n li $t1, 1\nloop3:\n li $v0, 4\n la $a0, num_str\n syscall\n \n li $v0, 1\n move $a0, $t1\n syscall\n\n li $v0, 4\n la $a0, comma_gap\n syscall\n\n li $v0, 1\n lb $a0, ($t0)\n syscall\n\n li $v0, 4,\n la $a0, newline\n syscall\n\n addi $t0, $t0, 1\n addi $t1, $t1, 1\n bne $t1, 101 loop3", "safe": true }, { "filename": "100_doors_435.txt", "content": "import java.util.ArrayList\n\nclass Door\n\t:state\n\n\tdef initialize\n\t\t@state=false\n\tend\n \n\tdef closed?;\u00a0!@state; end\n\tdef open?; @state; end\n\n\tdef close; @state=false; end\n\tdef open; @state=true; end\n \n\tdef toggle\n\t\tif closed?\n\t\t\topen\n\t\telse\n\t\t\tclose\n\t\tend\n\tend\n \n\tdef toString; Boolean.toString(@state); end\nend\n \ndoors=ArrayList.new\n1.upto(100) do\n doors.add(Door.new)\nend \n\n1.upto(100) do |multiplier|\n index = 0\n doors.each do |door|\n Door(door).toggle if (index+1)%multiplier == 0\n index += 1\n end\nend\n\ni = 0\ndoors.each do |door| \n puts \"Door #{i+1} is #{door}.\"\n i+=1\nend", "safe": true }, { "filename": "100_doors_436.txt", "content": "main\u00a0:: [sys_message]\nmain = [Stdout (show (openDoors 100)), \n Stdout \"\\n\"] \n\nopenDoors\u00a0:: num->[num]\nopenDoors doors =\n map snd (filter fst (zip2 (doorStates doors) [1..]))\n\ndoorStates\u00a0:: num->[bool]\ndoorStates doors =\n take doors (foldr (zipWith (~=)) (repeat False) (map pass [1..doors]))\n\npass\u00a0:: num->[bool]\npass n = tl (concat (repeat (take n (True:repeat False))))\n\nzipWith f x y = map f' (zip2 x y)\n where f' (x,y) = f x y", "safe": true }, { "filename": "100_doors_437.txt", "content": "[1,4,9,16,25,36,49,64,81,100]", "safe": true }, { "filename": "100_doors_438.txt", "content": "var %d = $str(0 $+ $chr(32),100), %m = 1\nwhile (%m <= 100) {\n var %n = 1\n while ($calc(%n * %m) <= 100) {\n var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32)\n inc %n\n }\n inc %m\n}\necho -ag All Doors (Boolean): %d\nvar %n = 1\nwhile (%n <= $findtok(%d,1,0,32)) {\n var %t = %t $findtok(%d,1,%n,32)\n inc %n\n}\necho -ag Open Door Numbers: %t", "safe": true }, { "filename": "100_doors_439.txt", "content": "MCSKIP \"WITH\" NL\n\"\" 100 doors\nMCINS\u00a0%.\nMCSKIP MT,<>\n\"\" Doors represented by P1-P100, 0 is closed\nMCPVAR 100\n\"\" Set P variables to 0\nMCDEF ZEROPS WITHS NL AS \nZEROPS\n\"\" Generate door state\nMCDEF STATE WITHS () AS MCGO L0\n%L1.open>\n\"\" Main macro - no arguments\n\"\" T1 is pass number\n\"\" T2 is door number\nMCDEF DOORS WITHS NL\nAS \n\"\" Do it\nDOORS", "safe": true }, { "filename": "100_doors_44.txt", "content": "\u2260\u233f0=(\u2373100)\u2218.|\u2373100\n", "safe": true }, { "filename": "100_doors_440.txt", "content": "MODULE Doors;\nIMPORT InOut;\n\nTYPE State = (Closed, Open);\nTYPE List = ARRAY [1 .. 100] OF State;\n\nVAR\n Doors: List;\n I, J: CARDINAL;\n\nBEGIN\n FOR I\u00a0:= 1 TO 100 DO\n FOR J\u00a0:= 1 TO 100 DO\n IF J MOD I = 0 THEN\n IF Doors[J] = Closed THEN\n Doors[J]\u00a0:= Open\n ELSE\n Doors[J]\u00a0:= Closed\n END\n END\n END\n END;\n\n FOR I\u00a0:= 1 TO 100 DO\n InOut.WriteCard(I, 3);\n InOut.WriteString(' is ');\n\n IF Doors[I] = Closed THEN\n InOut.WriteString('Closed.')\n ELSE\n InOut.WriteString('Open.')\n END;\n\n InOut.WriteLn\n END\nEND Doors.", "safe": true }, { "filename": "100_doors_441.txt", "content": "MODULE DoorsOpt;\nIMPORT InOut;\n\nTYPE State = (Closed, Open);\nTYPE List = ARRAY [1 .. 100] OF State;\n\nVAR\n Doors: List;\n I: CARDINAL;\n\nBEGIN\n FOR I\u00a0:= 1 TO 10 DO\n Doors[I*I]\u00a0:= Open\n END;\n\n FOR I\u00a0:= 1 TO 100 DO\n InOut.WriteCard(I, 3);\n InOut.WriteString(' is ');\n IF Doors[I] = Closed THEN\n InOut.WriteString('Closed.')\n ELSE\n InOut.WriteString('Open.')\n END;\n InOut.WriteLn\n END\nEND DoorsOpt.", "safe": true }, { "filename": "100_doors_442.txt", "content": "MODULE Doors EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nTYPE State = {Closed, Open};\nTYPE List = ARRAY [1..100] OF State;\n\nVAR doors\u00a0:= List{State.Closed, ..};\n\nBEGIN\n FOR i\u00a0:= 1 TO 100 DO\n FOR j\u00a0:= FIRST(doors) TO LAST(doors) DO\n IF j MOD i = 0 THEN\n IF doors[j] = State.Closed THEN\n doors[j]\u00a0:= State.Open;\n ELSE\n doors[j]\u00a0:= State.Closed;\n END;\n END;\n END;\n END;\n\n FOR i\u00a0:= FIRST(doors) TO LAST(doors) DO\n IO.Put(Fmt.Int(i) & \" is \");\n IF doors[i] = State.Closed THEN\n IO.Put(\"Closed.\\n\");\n ELSE\n IO.Put(\"Open.\\n\");\n END;\n END;\nEND Doors.", "safe": true }, { "filename": "100_doors_443.txt", "content": "MODULE DoorsOpt EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nTYPE State = {Closed, Open};\nTYPE List = ARRAY [1..100] OF State;\n\nVAR doors\u00a0:= List{State.Closed, ..};\n\nBEGIN\n FOR i\u00a0:= 1 TO 10 DO\n doors[i * i]\u00a0:= State.Open;\n END;\n\n FOR i\u00a0:= FIRST(doors) TO LAST(doors) DO\n IO.Put(Fmt.Int(i) & \" is \");\n IF doors[i] = State.Closed THEN\n IO.Put(\"Closed.\\n\");\n ELSE\n IO.Put(\"Open.\\n\");\n END;\n END;\nEND DoorsOpt.", "safe": true }, { "filename": "100_doors_444.txt", "content": "101 var l .\n\nfor l 0 endfor\narr\n\n0 var i .\nfor l\n i 1 + var i var j .\n j l < var pass .\n while pass\n get j not insert j .\n j i + var j\n l < var pass . \n endwhile\nendfor\nprint /# show all doors #/\n\n/# show only open doors #/\n|| print .\n0 var i .\nfor l\n get i\n if\u00a0: i out | | out . . endif .\n i 1 + var i .\nendfor\n\ninput . /# pause until ENTER key pressed #/", "safe": true }, { "filename": "100_doors_445.txt", "content": "is_open = make(100);\nfor pass in [1..100]\n for door in [pass..100]\n if (door\u00a0% pass)\n continue;\n endif\n is_open[door] = !is_open[door];\n endfor\nendfor\n\n\"output the result\";\nfor door in [1..100]\n player:tell(\"door #\", door, \" is \", (is_open[door]\u00a0? \"open\"\u00a0: \"closed\"), \".\");\nendfor", "safe": true }, { "filename": "100_doors_446.txt", "content": "is_open = [false for door = 1,100]\n \nfor pass = 1,100 \n for door = pass,100,pass\n is_open[door] = not is_open[door]\n \nfor i,v in ipairs is_open\n print \"Door #{i}: \" .. if v then 'open' else 'closed'", "safe": true }, { "filename": "100_doors_447.txt", "content": "doors\tnew door,pass\n\tFor door=1:1:100 Set door(door)=0\n\tFor pass=1:1:100 For door=pass:pass:100 Set door(door)='door(door)\n\tFor door=1:1:100 If door(door) Write\u00a0!,\"Door\",$j(door,4),\" is open\"\n\tWrite\u00a0!,\"All other doors are closed.\"\n\tQuit\nDo doors\nDoor 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open\nAll other doors are closed.", "safe": true }, { "filename": "100_doors_448.txt", "content": "use std\n\nconst main = {\n\tvar isopen\t: bool[100]\n\n\tstd.slfill(isopen[:], false)\n\tfor var i = 0; i < isopen.len; i++\n\t\tfor var j = i; j < isopen.len; j += i + 1\n\t\t\tisopen[j] = !isopen[j]\n\t\t;;\n\t;;\n\n\tfor var i = 0; i < isopen.len; i++\n\t\tif isopen[i]\n\t\t\tstd.put(\"door {} is open\\n\", i + 1)\n\t\t;;\n\t;;\n}", "safe": true }, { "filename": "100_doors_449.txt", "content": "door 1 is open\ndoor 4 is open\ndoor 9 is open\ndoor 16 is open\ndoor 25 is open\ndoor 36 is open\ndoor 49 is open\ndoor 64 is open\ndoor 81 is open\ndoor 100 is open\n", "safe": true }, { "filename": "100_doors_45.txt", "content": "1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1", "safe": true }, { "filename": "100_doors_450.txt", "content": "DROP PROCEDURE IF EXISTS one_hundred_doors;\n\nDELIMITER |\n\nCREATE PROCEDURE one_hundred_doors (n INT)\nBEGIN\n DROP TEMPORARY TABLE IF EXISTS doors; \n CREATE TEMPORARY TABLE doors (\n id INTEGER NOT NULL,\n open BOOLEAN DEFAULT FALSE,\n PRIMARY KEY (id)\n );\n\n SET @i = 1;\n create_doors: LOOP\n INSERT INTO doors (id, open) values (@i, FALSE);\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE create_doors;\n END IF;\n END LOOP create_doors;\n\n SET @i = 1;\n toggle_doors: LOOP\n UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0;\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE toggle_doors;\n END IF;\n END LOOP toggle_doors;\n\n SELECT id FROM doors WHERE open;\nEND|\n\nDELIMITER\u00a0;\n\nCALL one_hundred_doors(100);", "safe": true }, { "filename": "100_doors_451.txt", "content": "+-----+\n| id |\n+-----+\n| 1 |\n| 4 |\n| 9 |\n| 16 |\n| 25 |\n| 36 |\n| 49 |\n| 64 |\n| 81 |\n| 100 |\n+-----+\n10 rows in set (0.02 sec)\n", "safe": true }, { "filename": "100_doors_452.txt", "content": "// allocate a boolean array with all closed doors (false)\n// we need 101 since there will technically be a door 0\ndoors = {false} * 101\n \n// loop through all the step lengths (1-100)\nfor step in range(1, 100)\n\t// loop through all the doors, stepping by step\n\tfor door in range(0, len(doors) - 1, step)\n\t\t// change the state of the current door\n\t\tdoors[door] = !doors[door]\n\tend for\nend for\n \n// loop through and print the doors that are open, skipping door 0\nfor i in range(1, len(doors) - 1)\n\t// if the door is open, display it\n\tif doors[i]\n\t\tprintln \"Door \" + i + \" is open.\"\n\tend if\nend for", "safe": true }, { "filename": "100_doors_453.txt", "content": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nTrue = Rexx(1 == 1)\nFalse = Rexx(\\True)\n\ndoors = False\n\nloop i_ = 1 to 100\n loop j_ = 1 to 100\n if 0 = (j_ // i_) then doors[j_] = \\doors[j_]\n end j_\n end i_\n\nloop d_ = 1 to 100\n if doors[d_] then state = 'open'\n else state = 'closed'\n\n say 'Door Nr.' Rexx(d_).right(4) 'is' state\n end d_", "safe": true }, { "filename": "100_doors_454.txt", "content": "/* NetRexx */\noptions replace format comments java crossref symbols binary\n\nTrue = (1 == 1)\nFalse = \\True\n\ndoors = boolean[100]\n\nloop i_ = 0 to 9\n doors[(i_ + 1) * (i_ + 1) - 1] = True;\n end i_\n\nloop i_ = 0 to 99\n if doors[i_] then state = 'open'\n else state = 'closed'\n\n say 'Door Nr.' Rexx(i_ + 1).right(4) 'is' state\n end i_", "safe": true }, { "filename": "100_doors_455.txt", "content": "/* NetRexx */\noptions replace format comments java crossref savelog symbols binary\n\nresultstring = ''\n\nloop i_ = 1 to 10\n resultstring = resultstring || 'Door Nr.' Rexx(i_ * i_).right(4) 'is open\\n'\n end i_\n\nsay resultstring", "safe": true }, { "filename": "100_doors_456.txt", "content": "/* NetRexx */\n\nloop i = 1 to 10\n say 'Door Nr.' i * i 'is open.'\n end i", "safe": true }, { "filename": "100_doors_457.txt", "content": "(define (status door-num)\n (let ((x (int (sqrt door-num))))\n (if\n (= (* x x) door-num) (string \"Door \" door-num \" Open\")\n (string \"Door \" door-num \" Closed\"))))\n\n(dolist (n (map status (sequence 1 100)))\n (println n))", "safe": true }, { "filename": "100_doors_458.txt", "content": "(set 'Doors (array 100)) \u00a0;; Default value: nil (Closed)\n\n(for (x 0 99)\n (for (y x 99 (+ 1 x))\n (setf (Doors y) (not (Doors y)))))\n\n(for (x 0 99) \u00a0;; Display open doors\n (if (Doors x)\n (println (+ x 1) \"\u00a0: Open\")))", "safe": true }, { "filename": "100_doors_459.txt", "content": "1\u00a0: Open\n4\u00a0: Open\n9\u00a0: Open\n16\u00a0: Open\n25\u00a0: Open\n36\u00a0: Open\n49\u00a0: Open\n64\u00a0: Open\n81\u00a0: Open\n100\u00a0: Open\n", "safe": true }, { "filename": "100_doors_46.txt", "content": "\u2378\u2260\u233f0=(\u2373100)\u2218.|\u2373100\n", "safe": true }, { "filename": "100_doors_460.txt", "content": " n:=100;reduce xor (count n eachright mod count n eachall<1)\nlooloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo\n\nlooooooooooooooooool", "safe": true }, { "filename": "100_doors_461.txt", "content": " true findall (n:=100;reduce xor (count n eachright mod count n eachall<1))+1\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_462.txt", "content": " count 10 power 2\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_463.txt", "content": "from strutils import `%`\n\nconst numDoors = 100\nvar doors: array[1..numDoors, bool]\n\nfor pass in 1..numDoors:\n for door in countup(pass, numDoors, pass):\n doors[door] = not doors[door]\n\nfor door in 1..numDoors:\n echo \"Door $1 is $2.\"\u00a0% [$door, if doors[door]: \"open\" else: \"closed\"]", "safe": true }, { "filename": "100_doors_464.txt", "content": "from strutils import `%`\n\nconst numDoors = 100\nvar doors {.compileTime.}: array[1..numDoors, bool]\n\nproc calcDoors(): string =\n for pass in 1..numDoors:\n for door in countup(pass, numDoors, pass):\n doors[door] = not doors[door] \n for door in 1..numDoors:\n result.add(\"Door $1 is $2.\\n\"\u00a0% [$door, if doors[door]: \"open\" else: \"closed\"])\n\nconst outputString: string = calcDoors()\n\necho outputString", "safe": true }, { "filename": "100_doors_465.txt", "content": "MODULE Doors;\n IMPORT Out;\n \n PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *)\n CONST N = 100; len = N + 1;\n VAR i, j: INTEGER;\n closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *)\n BEGIN\n FOR i\u00a0:= 1 TO N DO closed[i]\u00a0:= TRUE END;\n FOR i\u00a0:= 1 TO N DO\n j\u00a0:= 1;\n WHILE j < len DO\n IF j MOD i = 0 THEN closed[j]\u00a0:= ~closed[j] END; INC(j) (* ~ = NOT *)\n END\n END;\n (* Print a state diagram of all doors *)\n FOR i\u00a0:= 1 TO N DO \n IF (i - 1) MOD 10 = 0 THEN Out.Ln END;\n IF closed[i] THEN Out.String(\"- \") ELSE Out.String(\"+ \") END\n END; Out.Ln;\n (* Print the numbers of the open doors *)\n FOR i\u00a0:= 1 TO N DO \n IF ~closed[i] THEN Out.Int(i, 0); Out.Char(\" \") END\n END; Out.Ln\n END Do;\n\nEND Doors.\n", "safe": true }, { "filename": "100_doors_466.txt", "content": "+ \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 + \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 + \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 + \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n+ \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \n\u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 \u2013 + \n1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100_doors_467.txt", "content": "bundle Default {\n class Doors {\n function\u00a0: Main(args\u00a0: String[]) ~ Nil {\n doors\u00a0:= Bool->New[100];\n \n for(pass\u00a0:= 0; pass < 10; pass += 1;) {\n doors[(pass + 1) * (pass + 1) - 1]\u00a0:= true;\n };\n \n for(i\u00a0:= 0; i < 100; i += 1;) { \n IO.Console->GetInstance()->Print(\"Door #\")->Print(i + 1)->Print(\" is \");\n if(doors[i]) {\n \"open.\"->PrintLine();\n }\n else {\n \"closed.\"->PrintLine();\n };\n };\n }\n }\n}", "safe": true }, { "filename": "100_doors_468.txt", "content": "@import Foundation;\n\nint main(int argc, const char * argv[]) {\n @autoreleasepool {\n \n // Create a mutable array\n NSMutableArray *doorArray = [@[] mutableCopy];\n \n // Fill the doorArray with 100 closed doors\n for (NSInteger i = 0; i < 100; ++i) {\n doorArray[i] = @NO;\n }\n \n // Do the 100 passes\n for (NSInteger pass = 0; pass < 100; ++pass) {\n for (NSInteger door = pass; door < 100; door += pass+1) {\n doorArray[door] = [doorArray[door] isEqual: @YES]\u00a0? @NO\u00a0: @YES;\n }\n }\n \n // Print the results\n [doorArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if ([obj isEqual: @YES]) {\n NSLog(@\"Door number %lu is open\", idx + 1);\n }\n }];\n }\n}", "safe": true }, { "filename": "100_doors_469.txt", "content": "@import Foundation;\n\n#pragma mark - Classes\n////////////////////////////////////////////////////\n// Model class header - A we are using a category to add a method to MSMutableArray\n@interface NSMutableArray (DoorModelExtension)\n\n- (void)setNumberOfDoors:(NSUInteger)doors;\n\n@end\n\n// Model class implementation\n@implementation NSMutableArray (DoorModelExtension)\n\n- (void)setNumberOfDoors:(NSUInteger)doors {\n // Fill the doorArray with 100 closed doors\n for (NSInteger i = 0; i < doors; ++i) {\n self[i] = @NO;\n }\n}\n@end\n////////////////////////////////////////////////////\n\n// View class header - A simple class to handle printing our values\n@interface DoorViewClass\u00a0: NSObject\n\n- (void)printResultsOfDoorTask:(NSMutableArray *)doors;\n\n@end\n\n// View class implementation\n@implementation DoorViewClass\n\n- (void)printResultsOfDoorTask:(NSMutableArray *)doors {\n\n // Print the results, using an enumeration block for easy index tracking\n [doors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if ([obj isEqual: @YES]) {\n NSLog(@\"Door number %lu is open\", idx + 1);\n }\n }];\n}\n\n@end\n////////////////////////////////////////////////////\n\n#pragma mark - main\n// With our classes set we can use them from our controller, in this case main\nint main(int argc, const char * argv[]) {\n \n // Init our classes\n NSMutableArray *doorArray = [NSMutableArray array];\n DoorViewClass *doorView = [DoorViewClass new];\n \n // Use our class category to add the doors\n [doorArray setNumberOfDoors:100];\n \n // Do the 100 passes\n for (NSUInteger pass = 0; pass < 100; ++pass) {\n for (NSUInteger door = pass; door < 100; door += pass+1) {\n doorArray[door] = [doorArray[door] isEqual: @YES]\u00a0? @NO\u00a0: @YES;\n }\n }\n \n // Print the results\n [doorView printResultsOfDoorTask:doorArray];\n \n}", "safe": true }, { "filename": "100_doors_47.txt", "content": "1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_470.txt", "content": "let max_doors = 100\n\nlet show_doors =\n Array.iteri (fun i x -> Printf.printf \"Door %d is %s\\n\" (i+1)\n (if x then \"open\" else \"closed\"))\n\nlet flip_doors doors =\n for i = 1 to max_doors do\n let rec flip idx =\n if idx < max_doors then begin\n doors.(idx) <- not doors.(idx);\n flip (idx + i)\n end\n in flip (i - 1)\n done;\n doors\n\nlet () =\n show_doors (flip_doors (Array.make max_doors false))", "safe": true }, { "filename": "100_doors_471.txt", "content": "let optimised_flip_doors doors =\n for i = 1 to int_of_float (sqrt (float_of_int max_doors)) do\n doors.(i*i - 1) <- true\n done;\n doors\n\nlet () =\n show_doors (optimised_flip_doors (Array.make max_doors false))", "safe": true }, { "filename": "100_doors_472.txt", "content": "type door = Open | Closed (* human readable code *)\n\nlet flipdoor = function Open -> Closed | Closed -> Open\n\nlet string_of_door = \n function Open -> \"is open.\" | Closed -> \"is closed.\"\n\nlet printdoors ls =\n let f i d = Printf.printf \"Door %i %s\\n\" (i + 1) (string_of_door d)\n in List.iteri f ls\n\nlet outerlim = 100\nlet innerlim = 100\n\nlet rec outer cnt accu =\n let rec inner i door = match i > innerlim with (* define inner loop *)\n | true -> door \n | false -> inner (i + 1) (if (cnt mod i) = 0 then flipdoor door else door)\n in (* define and do outer loop *)\n match cnt > outerlim with\n | true -> List.rev accu\n | false -> outer (cnt + 1) (inner 1 Closed\u00a0:: accu) (* generate new entries with inner *)\n\nlet () = printdoors (outer 1 [])", "safe": true }, { "filename": "100_doors_473.txt", "content": "doors = false(100,1);\nfor i = 1:100\n for j = i:i:100\n doors(j) = !doors(j);\n endfor\nendfor\nfor i = 1:100\n if ( doors(i) )\n s = \"open\";\n else\n s = \"closed\";\n endif\n printf(\"%d %s\\n\", i, s);\nendfor", "safe": true }, { "filename": "100_doors_474.txt", "content": "package main\n\nimport \"core:fmt\"\n\nmain\u00a0:: proc() {\n using fmt\n \n Door_State\u00a0:: enum {Closed, Open}\n \n doors\u00a0:= [?]Door_State { 0..<100 = .Closed }\n \n for i in 1..=100 {\n for j\u00a0:= i-1; j < 100; j += i {\n if doors[j] == .Closed {\n doors[j] = .Open\n } else {\n doors[j] = .Closed\n }\n }\n }\n for state, i in doors {\n println(\"Door: \",int(i+1),\" -> \",state)\n }\n}", "safe": true }, { "filename": "100_doors_475.txt", "content": "package main\n\nimport \"core:fmt\"\nimport \"core:math\"\n\nmain\u00a0:: proc() {\n using fmt\n \n Door_State\u00a0:: enum {Closed, Open}\n \n doors\u00a0:= [?]Door_State { 0..<100 = .Closed }\n \n for i in 1..=100 {\n res\u00a0:= math.sqrt_f64( f64(i) )\n if math.mod_f64( res, 1) == 0 {\n doors[i-1] = .Open\n } else {\n doors[i-1] = .Closed\n }\n println(\"Door: \", i, \" -> \", doors[i-1])\n }\n}", "safe": true }, { "filename": "100_doors_476.txt", "content": ": doors\n| i j l |\n 100 false Array newWith dup ->l\n 100 loop: i [ \n i 100 i step: j [ l put ( j , j l at not ) ] \n ] \n;", "safe": true }, { "filename": "100_doors_477.txt", "content": "(define (flip doors every)\n (map (lambda (door num)\n (mod (+ door (if (eq? (mod num every) 0) 1 0)) 2))\n doors\n (iota (length doors) 1)))\n\n(define doors\n (let loop ((doors (repeat 0 100)) (n 1))\n (if (eq? n 100)\n doors\n (loop (flip doors n) (+ n 1)))))\n\n(print \"100th doors: \" doors)", "safe": true }, { "filename": "100_doors_478.txt", "content": "100th doors: (1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)\n", "safe": true }, { "filename": "100_doors_479.txt", "content": "process\n local switch doors size 100\u00a0; all initialised ('1st pass' to false)\n\n repeat over doors\n repeat for integer door from #item to 100 by #item\n do when doors[door] = false\n activate doors[door]\u00a0; illustrating alternative to set ... to\n else\n set doors[door] to false\n done\n again\n again\n\n repeat over doors\n do when doors = true\n put #error '%d(#item)%n'\n done\n again", "safe": true }, { "filename": "100_doors_48.txt", "content": "set is_open to {}\nrepeat 100 times\n set end of is_open to false\nend\nrepeat with pass from 1 to 100\n repeat with door from pass to 100 by pass\n set item door of is_open to not item door of is_open\n end\nend\nset open_doors to {}\nrepeat with door from 1 to 100\n if item door of is_open then\n set end of open_doors to door\n end\nend\nset text item delimiters to \", \"\ndisplay dialog \"Open doors: \" & open_doors\n", "safe": true }, { "filename": "100_doors_480.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100_doors_481.txt", "content": "process\n local integer door initial {1}\n local integer step initial {3}\n\n repeat\n output \"Door %d(door) is open%n\"\n increment door by step\n increment step by 2\n exit when door > 100\n again", "safe": true }, { "filename": "100_doors_482.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open\n", "safe": true }, { "filename": "100_doors_483.txt", "content": "$Door dict def\n1 1 100 {Door exch false put} for\n$Toggle {dup Door exch get not Door up put} def\n$EveryNthDoor {dup 100 {Toggle} for} def\n$Run {1 1 100 {EveryNthDoor} for} def\n$ShowDoor {dup `Door no. ' exch cvs cat ` is ' cat\n exch Door exch get {`open.\\n'}{`shut.\\n'} ifelse cat\n print flush} def\nRun 1 1 100 {ShowDoor} for", "safe": true }, { "filename": "100_doors_484.txt", "content": "Door no. 1 is open.\nDoor no. 2 is shut.\nDoor no. 3 is shut.\nDoor no. 4 is open.\nDoor no. 5 is shut.\nDoor no. 6 is shut.\nDoor no. 7 is shut.\nDoor no. 8 is shut.\nDoor no. 9 is open.\nDoor no. 10 is shut.\nDoor no. 11 is shut.\nDoor no. 12 is shut.\nDoor no. 13 is shut.\nDoor no. 14 is shut.\nDoor no. 15 is shut.\nDoor no. 16 is open.\nDoor no. 17 is shut.\nDoor no. 18 is shut.\nDoor no. 19 is shut.\nDoor no. 20 is shut.\nDoor no. 21 is shut.\nDoor no. 22 is shut.\nDoor no. 23 is shut.\nDoor no. 24 is shut.\nDoor no. 25 is open.\nDoor no. 26 is shut.\nDoor no. 27 is shut.\nDoor no. 28 is shut.\nDoor no. 29 is shut.\nDoor no. 30 is shut.\nDoor no. 31 is shut.\nDoor no. 32 is shut.\nDoor no. 33 is shut.\nDoor no. 34 is shut.\nDoor no. 35 is shut.\nDoor no. 36 is open.\nDoor no. 37 is shut.\nDoor no. 38 is shut.\nDoor no. 39 is shut.\nDoor no. 40 is shut.\nDoor no. 41 is shut.\nDoor no. 42 is shut.\nDoor no. 43 is shut.\nDoor no. 44 is shut.\nDoor no. 45 is shut.\nDoor no. 46 is shut.\nDoor no. 47 is shut.\nDoor no. 48 is shut.\nDoor no. 49 is open.\nDoor no. 50 is shut.\nDoor no. 51 is shut.\nDoor no. 52 is shut.\nDoor no. 53 is shut.\nDoor no. 54 is shut.\nDoor no. 55 is shut.\nDoor no. 56 is shut.\nDoor no. 57 is shut.\nDoor no. 58 is shut.\nDoor no. 59 is shut.\nDoor no. 60 is shut.\nDoor no. 61 is shut.\nDoor no. 62 is shut.\nDoor no. 63 is shut.\nDoor no. 64 is open.\nDoor no. 65 is shut.\nDoor no. 66 is shut.\nDoor no. 67 is shut.\nDoor no. 68 is shut.\nDoor no. 69 is shut.\nDoor no. 70 is shut.\nDoor no. 71 is shut.\nDoor no. 72 is shut.\nDoor no. 73 is shut.\nDoor no. 74 is shut.\nDoor no. 75 is shut.\nDoor no. 76 is shut.\nDoor no. 77 is shut.\nDoor no. 78 is shut.\nDoor no. 79 is shut.\nDoor no. 80 is shut.\nDoor no. 81 is open.\nDoor no. 82 is shut.\nDoor no. 83 is shut.\nDoor no. 84 is shut.\nDoor no. 85 is shut.\nDoor no. 86 is shut.\nDoor no. 87 is shut.\nDoor no. 88 is shut.\nDoor no. 89 is shut.\nDoor no. 90 is shut.\nDoor no. 91 is shut.\nDoor no. 92 is shut.\nDoor no. 93 is shut.\nDoor no. 94 is shut.\nDoor no. 95 is shut.\nDoor no. 96 is shut.\nDoor no. 97 is shut.\nDoor no. 98 is shut.\nDoor no. 99 is shut.\nDoor no. 100 is open.", "safe": true }, { "filename": "100_doors_485.txt", "content": "doors = .array~new(100) -- array containing all of the doors\ndo i = 1 to doors~size -- initialize with a collection of closed doors\n doors[i] = .door~new(i)\nend\n\ndo inc = 1 to doors~size\n do d = inc to doors~size by inc\n doors[d]~toggle\n end\nend\nsay \"The open doors after 100 passes:\"\ndo door over doors\n if door~isopen then say door\nend\n\n::class door -- simple class to represent a door\n::method init -- initialize an instance of a door\n expose id state -- instance variables of a door\n use strict arg id -- set the id\n state = .false -- initial state is closed\n\n::method toggle -- toggle the state of the door\n expose state\n state = \\state\n\n::method isopen -- test if the door is open\n expose state\n return state\n\n::method string -- return a string value for a door\n expose state id\n if state then return \"Door\" id \"is open\"\n else return \"Door\" id \"is closed\"\n\n::method state -- return door state as a descriptive string\n expose state\n if state then return \"open\"\n else return \"closed\"", "safe": true }, { "filename": "100_doors_486.txt", "content": "DEFINE VARIABLE lopen AS LOGICAL NO-UNDO EXTENT 100.\nDEFINE VARIABLE idoor AS INTEGER NO-UNDO.\nDEFINE VARIABLE ipass AS INTEGER NO-UNDO.\nDEFINE VARIABLE cresult AS CHARACTER NO-UNDO.\n\nDO ipass = 1 TO 100:\n idoor = 0.\n DO WHILE idoor <= 100:\n idoor = idoor + ipass.\n IF idoor <= 100 THEN\n lopen[ idoor ] = NOT lopen[ idoor ].\n END.\nEND.\n\nDO idoor = 1 TO 100:\n cresult = cresult + STRING( lopen[ idoor ], \"1 /0 \" ).\n IF idoor MODULO 10 = 0 THEN\n cresult = cresult + \"~r\":U.\nEND.\n\nMESSAGE cresult VIEW-AS ALERT-BOX.", "safe": true }, { "filename": "100_doors_487.txt", "content": "def doors 100\nint door[doors],i ,j, c\nstring cr,tab,pr\n'\nfor i=1 to doors\n for j=i to doors step i\n door[j]=1-door[j]\n if door[j] then c++ else c--\n next\nnext\n'\ncr=chr(13) chr(10)\npr=\"Doors Open: \" c cr cr \n'\nfor i=1 to doors\n if door[i] then pr+=i cr\nnext\nprint pr\n", "safe": true }, { "filename": "100_doors_488.txt", "content": "declare\n NumDoors = 100\n NumPasses = 100\n\n fun {NewDoor} closed end\n\n fun {Toggle Door}\n case Door of closed then open\n [] open then closed\n end\n end\n\n fun {Pass Doors I}\n {List.mapInd Doors\n fun {$ Index Door}\n if Index mod I == 0 then {Toggle Door}\n else Door\n end\n end}\n end\n \n Doors0 = {MakeList NumDoors}\n {ForAll Doors0 NewDoor}\n\n DoorsN = {FoldL {List.number 1 NumPasses 1} Pass Doors0}\nin\n \u00a0%% print open doors\n {List.forAllInd DoorsN\n proc {$ Index Door}\n if Door == open then\n\t {System.showInfo \"Door \"#Index#\" is open.\"}\n end\n end\n }", "safe": true }, { "filename": "100_doors_489.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.\n", "safe": true }, { "filename": "100_doors_49.txt", "content": "on _100doors()\n script o\n property doors : {}\n end script\n repeat 100 times\n set end of o's doors to false -- false = \"not open\".\n end repeat\n repeat with pass from 1 to 100\n if (not item pass of o's doors) then set item pass of o's doors to pass\n repeat with d from (pass + pass) to 100 by pass\n set item d of o's doors to (not item d of o's doors)\n end repeat\n end repeat\n \n return o's doors's integers\nend _100doors\n\non join(lst, delim)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delim\n set txt to lst as text\n set AppleScript's text item delimiters to astid\n return txt\nend join\n\nreturn \"Open doors:\n\" & join(_100doors(), \", \")\n", "safe": true }, { "filename": "100_doors_490.txt", "content": "v=vector(d=100);/*set 100 closed doors*/\nfor(i=1,d,forstep(j=i,d,i,v[j]=1-v[j]));\nfor(i=1,d,if(v[i],print(\"Door \",i,\" is open.\")))", "safe": true }, { "filename": "100_doors_491.txt", "content": "for(n=1,sqrt(100),print(\"Door \",n^2,\" is open.\"))", "safe": true }, { "filename": "100_doors_492.txt", "content": "doors =vector(100);\nprint(\"open doors are\u00a0: \");\nfor(i=1,100,for(j=i,100,doors[j]=!doors[j];j +=i-1))\nfor(k=1,100,if(doors[k]==1,print1(\" \",k)))", "safe": true }, { "filename": "100_doors_493.txt", "content": "Open doors are:\n 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_494.txt", "content": "Program OneHundredDoors;\n\nvar\n doors\u00a0: Array[1..100] of Boolean;\n i, j\t\u00a0: Integer;\n \nbegin\n for i\u00a0:= 1 to 100 do\n doors[i]\u00a0:= False;\n for i\u00a0:= 1 to 100 do begin\n j\u00a0:= i;\n while j <= 100 do begin\n\t doors[j]\u00a0:= not doors[j];\n\t j\u00a0:= j + i\n end\n end;\n for i\u00a0:= 1 to 100 do begin\n Write(i, ' ');\n if doors[i] then\n\t WriteLn('open')\n else\n\t WriteLn('closed');\n end\nend.", "safe": true }, { "filename": "100_doors_495.txt", "content": "program OneHundredDoors;\n\n{$APPTYPE CONSOLE}\n\nuses\n math, sysutils;\n\nvar\n AOpendoors \u00a0: String;\n ACloseDoors\u00a0: String;\n i\t \u00a0: Integer;\n\nbegin\n for i\u00a0:= 1 to 100 do\n begin\n if (sqrt(i) = floor(sqrt(i))) then\n AOpenDoors\u00a0:= AOpenDoors + IntToStr(i) + ';'\n else\n ACloseDoors\u00a0:= ACloseDoors + IntToStr(i) +';';\n end;\n\n WriteLn('Open doors: ' + AOpenDoors);\n WriteLn('Close doors: ' + ACloseDoors);\nend.", "safe": true }, { "filename": "100_doors_496.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_497.txt", "content": ";100 doors example program for x86 DOS\n;Compiles with Pebble to 95 bytes com executable\n\nprogram examples\\100doors\n\ndata\n\n\tint i[0]\n\tint d[0]\n\nbegin\n\n\tlabel loop\n\n\t\t+1 [i]\n\t\t[d] = [i] * [i]\n\t\techo [d]\n\t\tcrlf\n\n\tif [d] < 100 then loop\n\n\tpause\n\tkill\n\nend", "safe": true }, { "filename": "100_doors_498.txt", "content": "my @doors;\nfor my $pass (1 .. 100) {\n for (1 .. 100) {\n if (0 == $_\u00a0% $pass) {\n $doors[$_] = not $doors[$_];\n };\n };\n};\n\nprint \"Door $_ is \", $doors[$_]\u00a0? \"open\"\u00a0: \"closed\", \"\\n\" for 1 .. 100;", "safe": true }, { "filename": "100_doors_499.txt", "content": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy @doors = (1) x 100;\nfor my $N (1 .. 100) {\n $doors[$_]=1-$doors[$_] for map { $_*$N - 1 } 1 .. int(100/$N);\n}\nprint join(\"\\n\", map { \"Door $_ is Open\" } grep {\u00a0! $doors[$_-1] } 1 .. 100), \"\\n\";\nprint \"The rest are closed\\n\";", "safe": true }, { "filename": "100_doors_5.txt", "content": "%@left[n,string] ^: Return n leftmost chars in string\n%@right[n,string] ^: Return n rightmost chars in string\n%@if[condition,true-val,false-val] ^: Evaluate condition; return true-val if true, false-val if false\n", "safe": true }, { "filename": "100_doors_50.txt", "content": "\"Open doors:\n1, 4, 9, 16, 25, 36, 49, 64, 81, 100\"\n", "safe": true }, { "filename": "100_doors_500.txt", "content": "print \"Door $_ is open\\n\" for map $_**2, 1 .. 10;", "safe": true }, { "filename": "100_doors_501.txt", "content": "print \"Door $_ is \", qw\"closed open\"[int sqrt == sqrt], \"\\n\" for 1..100;", "safe": true }, { "filename": "100_doors_502.txt", "content": "while( ++$i <= 100 )\n{\n $root = sqrt($i);\n if ( int( $root ) == $root )\n {\n print \"Door $i is open\\n\";\n }\n else\n {\n print \"Door $i is closed\\n\";\n }\n}", "safe": true }, { "filename": "100_doors_503.txt", "content": "use perl5i::2;\n\npackage doors {\n\n use perl5i::2;\n use Const::Fast;\n\n const my $OPEN => 1;\n const my $CLOSED => 0;\n\n # ----------------------------------------\n # Constructor: door->new( @args );\n # input: N - how many doors?\n # returns: door object\n #\n method new($class: @args ) {\n my $self = bless {}, $class;\n $self->_init( @args );\n return $self;\n }\n\n # ----------------------------------------\n # class initializer.\n # input: how many doors?\n # sets N, creates N+1 doors ( door zero is not used ).\n #\n method _init( $N ) {\n $self->{N} = $N;\n $self->{doors} = [ ($CLOSED) x ($N+1) ];\n }\n\n # ----------------------------------------\n # $self->toggle( $door_number );\n # input: number of door to toggle.\n # OPEN a CLOSED door; CLOSE an OPEN door.\n #\n method toggle( $which ) {\n $self->{doors}[$which] = ( $self->{doors}[$which] == $OPEN\n \u00a0? $CLOSED\n \u00a0: $OPEN\n \t\t );\n }\n\n # ----------------------------------------\n # $self->toggle_n( $cycle );\n # input: number.\n # Toggle doors 0, $cycle, 2 * $cycle, 3 * $cycle, .. $self->{N}\n #\n method toggle_n( $n ) {\n $self->toggle($_)\n for map { $n * $_ }\n ( 1 .. int( $self->{N} / $n) );\n\n }\n\n # ----------------------------------------\n # $self->toggle_all();\n # Toggle every door, then every other door, every third door, ...\n #\n method toggle_all() {\n $self->toggle_n( $_ ) for ( 1 .. $self->{N} );\n }\n\n\n # ----------------------------------------\n # $self->print_open();\n # Print list of which doors are open.\n #\n method print_open() {\n say join ', ', grep { $self->{doors}[$_] == $OPEN } ( 1 ... $self->{N} );\n }\n}\n\n# ----------------------------------------------------------------------\n# Main Thread\n#\nmy $doors = doors->new(100);\n$doors->toggle_all();\n$doors->print_open();", "safe": true }, { "filename": "100_doors_504.txt", "content": "sequence doors = repeat(false,100)\n \nfor i=1 to 100 do\n for j=i to 100 by i do\n doors[j] = not doors[j]\n end for\nend for\n \nfor i=1 to 100 do\n if doors[i] == true then\n printf(1,\"Door #%d is open.\\n\", i)\n end if\nend for\n", "safe": true }, { "filename": "100_doors_505.txt", "content": "Door #1 is open.\nDoor #4 is open.\nDoor #9 is open.\nDoor #16 is open.\nDoor #25 is open.\nDoor #36 is open.\nDoor #49 is open.\nDoor #64 is open.\nDoor #81 is open.\nDoor #100 is open.\n", "safe": true }, { "filename": "100_doors_506.txt", "content": "function doors(integer n)\n-- returns the perfect squares<=n\ninteger door = 1, step = 1\nsequence res = {}\n while door<=n do\n res &= door\n step += 2\n door += step\n end while\n return res\nend function\n \n?doors(100)\n", "safe": true }, { "filename": "100_doors_507.txt", "content": "{1,4,9,16,25,36,49,64,81,100}\n", "safe": true }, { "filename": "100_doors_508.txt", "content": "101 var l \n0 l repeat \n\nl for\n var s\n s l s 3 tolist\n for\n var i\n i get not i set\n endfor\nendfor\n\nl for\n var i\n i get\n if\n i print \" \" print\n endif\nendfor", "safe": true }, { "filename": "100_doors_509.txt", "content": "100 var n /# Number of doors #/\n0 n repeat /# Make the doors #/\n\nn for\n dup\n sqrt int\n dup * over == if 1 swap set else drop endif\nendfor\n\nn for\n \"The door \" print dup print \" is \" print\n get if \"OPEN.\" else \"closed.\" endif print nl\nendfor", "safe": true }, { "filename": "100_doors_51.txt", "content": "-- FINAL DOOR STATES ---------------------------------------------------------\n\n-- finalDoors\u00a0:: Int -> [(Int, Bool)]\non finalDoors(n)\n \n -- toggledCorridor\u00a0:: [(Int, Bool)] -> (Int, Bool) -> Int -> [(Int, Bool)]\n script toggledCorridor\n on |\u03bb|(a, _, k)\n \n -- perhapsToggled\u00a0:: Bool -> Int -> Bool\n script perhapsToggled\n on |\u03bb|(x, i)\n if i mod k = 0 then\n {i, not item 2 of x}\n else\n {i, item 2 of x}\n end if\n end |\u03bb|\n end script\n \n map(perhapsToggled, a)\n end |\u03bb|\n end script\n \n set xs to enumFromTo(1, n)\n \n foldl(toggledCorridor, \u00ac\n zip(xs, replicate(n, {false})), xs)\nend finalDoors\n\n-- TEST ----------------------------------------------------------------------\non run\n -- isOpenAtEnd\u00a0:: (Int, Bool) -> Bool\n script isOpenAtEnd\n on |\u03bb|(door)\n (item 2 of door)\n end |\u03bb|\n end script\n \n -- doorNumber\u00a0:: (Int, Bool) -> Int\n script doorNumber\n on |\u03bb|(door)\n (item 1 of door)\n end |\u03bb|\n end script\n \n map(doorNumber, filter(isOpenAtEnd, finalDoors(100)))\n \n --> {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\nend run\n\n\n-- GENERIC FUNCTIONS ---------------------------------------------------------\n\n-- enumFromTo\u00a0:: Int -> Int -> [Int]\non enumFromTo(m, n)\n if n < m then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- filter\u00a0:: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |\u03bb|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- foldl\u00a0:: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |\u03bb|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- map\u00a0:: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |\u03bb|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- min\u00a0:: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n-- Lift 2nd class handler function into 1st class script wrapper \n-- mReturn\u00a0:: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |\u03bb| : f\n end script\n end if\nend mReturn\n\n-- replicate\u00a0:: Int -> a -> [a]\non replicate(n, a)\n set out to {}\n if n < 1 then return out\n set dbl to {a}\n \n repeat while (n > 1)\n if (n mod 2) > 0 then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicate\n\n-- zip\u00a0:: [a] -> [b] -> [(a, b)]\non zip(xs, ys)\n set lng to min(length of xs, length of ys)\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to {item i of xs, item i of ys}\n end repeat\n return lst\nend zip\n", "safe": true }, { "filename": "100_doors_510.txt", "content": "100 sqrt for dup * print \" \" print endfor", "safe": true }, { "filename": "100_doors_511.txt", "content": "module doors;\n\nextern printf;\n\n@Integer main [\n\t@Array<@Boolean> doors = new @Array<@Boolean>.init(100);\n\tvar i = 1;\n\twhile (i <= 100) {\n\t\tvar j = i-1;\n\t\twhile (j < 100) {\n\t\t\tdoors.set(j, doors.get(j)::not);\n\t\t\tj = j + i;\n\t\t}\n\t\ti = i::inc;\n\t}\n\ti = 0;\n\twhile (i < 100) {\n\t\tprintf(\"%i %s\\n\", i+1, iif(doors.get(i), \"open\", \"closed\"));\n\t\ti = i::inc;\n\t}\n\treturn 0;\n]", "safe": true }, { "filename": "100_doors_512.txt", "content": "module var;\n\nextern printf;\n\n@Integer main [\n\tvar door = 1;\n\tvar incrementer = 0;\n\tvar current = 1;\n while (current <= 100)\n {\n\t\tprintf(\"Door %i \", current);\n\t\tif (current == door)\n\t\t{\n\t\t\tprintf(\"open\\n\");\n\t\t\tincrementer = incrementer::inc;\n\t\t\tdoor = door + 2 * incrementer + 1;\n\t\t}\n\t\telse\n\t\t\tprintf(\"closed\\n\");\n\t\t\n\t\tcurrent = current + 1;\n \n }\n\t\n\treturn 0;\n]", "safe": true }, { "filename": "100_doors_513.txt", "content": "", "safe": true }, { "filename": "100_doors_514.txt", "content": "", "safe": true }, { "filename": "100_doors_515.txt", "content": "doors(N) => \n Doors = new_array(N),\n foreach(I in 1..N) Doors[I]\u00a0:= 0 end,\n foreach(I in 1..N)\n foreach(J in I..I..N)\n Doors[J]\u00a0:= 1^Doors[J]\n end,\n if N <= 10 then\n print_open(Doors)\n end\n end,\n println(Doors),\n print_open(Doors),\n nl.\n\nprint_open(Doors) => println([I\u00a0: I in 1..Doors.length, Doors[I] == 1]).", "safe": true }, { "filename": "100_doors_516.txt", "content": "doors_opt(N) =>\n foreach(I in 1..N)\n Root = sqrt(I),\n println([I, cond(Root == 1.0*round(Root), open, closed)])\n end,\n nl.", "safe": true }, { "filename": "100_doors_517.txt", "content": "doors_opt2(N) => \n println([I**2\u00a0: I in 1..N, I**2 <= N]).", "safe": true }, { "filename": "100_doors_518.txt", "content": "(let Doors (need 100)\n (for I 100\n (for (D (nth Doors I) D (cdr (nth D I)))\n (set D (not (car D))) ) )\n (println Doors) )", "safe": true }, { "filename": "100_doors_519.txt", "content": "(let Doors (need 100)\n (for I (sqrt 100)\n (set (nth Doors (* I I)) T) )\n (println Doors) )", "safe": true }, { "filename": "100_doors_52.txt", "content": "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\n", "safe": true }, { "filename": "100_doors_520.txt", "content": "(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL\n NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL\n NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T\n NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL N\nIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T)", "safe": true }, { "filename": "100_doors_521.txt", "content": "(let Doors (need 100)\n (for I (sqrt 100)\n (set (nth Doors (* I I)) T) )\n (make\n (for (N . D) Doors\n (when D (link N)) ) ) )", "safe": true }, { "filename": "100_doors_522.txt", "content": "(1 4 9 16 25 36 49 64 81 100)", "safe": true }, { "filename": "100_doors_523.txt", "content": "array onehundreddoors()\n{\n array doors = allocate(100);\n foreach(doors; int i;)\n for(int j=i; j<100; j+=i+1)\n doors[j] = !doors[j];\n return doors;\n}", "safe": true }, { "filename": "100_doors_524.txt", "content": "array doors = map(enumerate(100,1,1), lambda(int x)\n { \n return sqrt((float)x)%1 == 0.0; \n });", "safe": true }, { "filename": "100_doors_525.txt", "content": "write(\"%{%d %d %d %d %d %d %d %d %d %d\\n%}\\n\", doors/10)", "safe": true }, { "filename": "100_doors_526.txt", "content": "1 0 0 1 0 0 0 0 1 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 0 0 0 0 1 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 1\n", "safe": true }, { "filename": "100_doors_527.txt", "content": "declare door(100) bit (1) aligned;\ndeclare closed bit (1) static initial ('0'b),\n open bit (1) static initial ('1'b);\ndeclare (i, inc) fixed binary;\n\ndoor = closed;\ninc = 1;\ndo until (inc >= 100);\n do i = inc to 100 by inc;\n door(i) = ^door(i); /* close door if open; open it if closed. */\n end;\n inc = inc+1;\nend;\n\ndo i = 1 to 100;\n put skip edit ('Door ', trim(i), ' is ') (a);\n if door(i) then put edit (' open.') (a);\n else put edit (' closed.') (a);\nend;", "safe": true }, { "filename": "100_doors_528.txt", "content": "/* Solution to the 100 doors problem in PLI-80 */\n\nhundred_doors:\n procedure options (main);\n\n %replace\n open_door by '1'b,\n closed_door by '0'b,\n numdoors by 100;\n\n dcl\n doors(1:numdoors) bit(1),\n (i, j) fixed bin(15);\n\n /* all doors are initially closed */\n do i = 1 to numdoors;\n doors(i) = closed_door;\n end;\n\n /* cycle through at increasing intervals and flip doors */\n do i = 1 to numdoors;\n j = i;\n do while (j <= numdoors);\n doors(j) = ^doors(j);\n j = j + i;\n end;\n end;\n\n /* show results - open doors should all be perfect squares */\n put skip list ('The open doors are:');\n do i = 1 to numdoors;\n if doors(i) = open_door then\n put edit (i) (F(4));\n end;\n\nend hundred_doors;", "safe": true }, { "filename": "100_doors_529.txt", "content": "The open doors are: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_53.txt", "content": "map(factorCountMod2, enumFromTo(1, 100))\n\non factorCountMod2(n)\n {n, (length of integerFactors(n)) mod 2 = 1}\nend factorCountMod2\n", "safe": true }, { "filename": "100_doors_530.txt", "content": "100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */\n\n /* BDOS SYSTEM CALL */\n BDOS: PROCEDURE( FN, ARG );\n DECLARE FN BYTE, ARG ADDRESS;\n GO TO 5;\n END BDOS;\n\n /* PRINTS A BYTE AS A CHARACTER */\n PRINT$CHAR: PROCEDURE( CH );\n DECLARE CH BYTE;\n CALL BDOS( 2, CH );\n END PRINT$CHAR;\n\n /* PRINTS A BYTE AS A NUMBER */\n PRINT$BYTE: PROCEDURE( N );\n DECLARE N BYTE;\n DECLARE ( V, D3, D2 ) BYTE;\n V = N;\n D3 = V MOD 10;\n IF ( V\u00a0:= V / 10 ) <> 0 THEN DO;\n D2 = V MOD 10;\n IF ( V\u00a0:= V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );\n CALL PRINT$CHAR( '0' + D2 );\n END;\n CALL PRINT$CHAR( '0' + D3 );\n END PRINT$BYTE;\n\n DECLARE DOOR$DCL LITERALLY '101';\n DECLARE FALSE LITERALLY '0';\n DECLARE CR LITERALLY '0DH';\n DECLARE LF LITERALLY '0AH';\n\n /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */\n DECLARE DOOR( DOOR$DCL ) BYTE;\n DECLARE ( I, J ) BYTE;\n\n /* SET ALL DOORS TO CLOSED */\n DO I = 0 TO LAST( DOOR ); DOOR( I ) = FALSE; END;\n /* REPEATEDLY FLIP THE DOORS */\n DO I = 1 TO LAST( DOOR );\n DO J = I TO LAST( DOOR ) BY I;\n DOOR( J ) = NOT DOOR( J );\n END;\n END;\n /* DISPLAY THE RESULTS */\n DO I = 1 TO LAST( DOOR );\n IF DOOR( I ) THEN DO;\n CALL PRINT$CHAR( ' ' );\n CALL PRINT$BYTE( I );\n END;\n END;\n CALL PRINT$CHAR( CR );\n CALL PRINT$CHAR( LF );\nEOF", "safe": true }, { "filename": "100_doors_531.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_532.txt", "content": "DECLARE\n TYPE doorsarray IS VARRAY(100) OF BOOLEAN;\n doors doorsarray\u00a0:= doorsarray();\nBEGIN\n\ndoors.EXTEND(100); --ACCOMMODATE 100 DOORS\n\nFOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE\n LOOP\n doors(i)\u00a0:= FALSE; \n END LOOP;\n\nFOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE\n LOOP\n FOR k IN 1 .. 100\n LOOP\n IF MOD(k,j)=0 THEN \n doors(k)\u00a0:= NOT doors(k); \n END IF;\n END LOOP;\n END LOOP;\n \nFOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION\n LOOP\n DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE' \n THEN 'OPEN' \n ELSE 'CLOSED' \n END);\n END LOOP;\n\nEND;", "safe": true }, { "filename": "100_doors_533.txt", "content": "To create some doors given a count:\n Loop.\n If a counter is past the count, exit.\n Allocate memory for a door.\n Clear the door's flag.\n Append the door to the doors.\n Repeat.\n\nA flag thing is a thing with a flag.\nA door is a flag thing.\n\nTo go through some doors given a number and some passes:\n Put 0 into a counter.\n Loop.\n Add the number to the counter.\n If the counter is greater than the passes, exit.\n Pick a door from the doors given the number.\n Invert the door's flag.\n Repeat.\n\nTo output the states of some doors:\n Loop.\n Bump a counter.\n Get a door from the doors.\n If the door is nil, exit.\n If the door's flag is set, \n Write \"Door \" then the counter then \" is open\" to the output; \n Repeat.\n Write \"Door \" then the counter then \" is closed\" to the output.\n Repeat.\n\nTo pass doors given a count and some passes:\n Create some doors given the count.\n Loop.\n If a counter is past the passes, break.\n Go through the doors given the counter and the passes.\n Repeat.\n Output the states of the doors.\n Destroy the doors.\n\nA pass is a number.\n\nTo pick a door from some doors given a number:\n Loop.\n If a counter is past the number, exit.\n Get the door from the doors.\n If the door is nil, exit.\n Repeat.\n\nTo run:\n Start up.\n Pass doors given 100 and 100 passes.\n Wait for the escape key.\n Shut down.", "safe": true }, { "filename": "100_doors_534.txt", "content": "Door 1 is open\nDoor 2 is closed\nDoor 3 is closed\nDoor 4 is open\nDoor 5 is closed\nDoor 6 is closed\nDoor 7 is closed\nDoor 8 is closed\nDoor 9 is open\nDoor 10 is closed\nDoor 11 is closed\nDoor 12 is closed\nDoor 13 is closed\nDoor 14 is closed\nDoor 15 is closed\nDoor 16 is open\nDoor 17 is closed\nDoor 18 is closed\nDoor 19 is closed\nDoor 20 is closed\nDoor 21 is closed\nDoor 22 is closed\nDoor 23 is closed\nDoor 24 is closed\nDoor 25 is open\nDoor 26 is closed\nDoor 27 is closed\nDoor 28 is closed\nDoor 29 is closed\nDoor 30 is closed\nDoor 31 is closed\nDoor 32 is closed\nDoor 33 is closed\nDoor 34 is closed\nDoor 35 is closed\nDoor 36 is open\nDoor 37 is closed\nDoor 38 is closed\nDoor 39 is closed\nDoor 40 is closed\nDoor 41 is closed\nDoor 42 is closed\nDoor 43 is closed\nDoor 44 is closed\nDoor 45 is closed\nDoor 46 is closed\nDoor 47 is closed\nDoor 48 is closed\nDoor 49 is open\nDoor 50 is closed\nDoor 51 is closed\nDoor 52 is closed\nDoor 53 is closed\nDoor 54 is closed\nDoor 55 is closed\nDoor 56 is closed\nDoor 57 is closed\nDoor 58 is closed\nDoor 59 is closed\nDoor 60 is closed\nDoor 61 is closed\nDoor 62 is closed\nDoor 63 is closed\nDoor 64 is open\nDoor 65 is closed\nDoor 66 is closed\nDoor 67 is closed\nDoor 68 is closed\nDoor 69 is closed\nDoor 70 is closed\nDoor 71 is closed\nDoor 72 is closed\nDoor 73 is closed\nDoor 74 is closed\nDoor 75 is closed\nDoor 76 is closed\nDoor 77 is closed\nDoor 78 is closed\nDoor 79 is closed\nDoor 80 is closed\nDoor 81 is open\nDoor 82 is closed\nDoor 83 is closed\nDoor 84 is closed\nDoor 85 is closed\nDoor 86 is closed\nDoor 87 is closed\nDoor 88 is closed\nDoor 89 is closed\nDoor 90 is closed\nDoor 91 is closed\nDoor 92 is closed\nDoor 93 is closed\nDoor 94 is closed\nDoor 95 is closed\nDoor 96 is closed\nDoor 97 is closed\nDoor 98 is closed\nDoor 99 is closed\nDoor 100 is open\n", "safe": true }, { "filename": "100_doors_535.txt", "content": "output =\n range(1, 100)\n |> map(visit(100))\n |> println\n\n----------------------------------------------------------\n\ntoggle(state) =\n if state == Closed then Open else Closed\n\n----------------------------------------------------------\n-- Door state on iteration i is recursively\n-- defined in terms of previous door state\n\nvisit(i, index) = cond {\n case (i == 0) Closed\n case (index\u00a0% i == 0) toggle(lastState)\n else lastState\n} where lastState = visit(i - 1, index)", "safe": true }, { "filename": "100_doors_536.txt", "content": "[Open, Closed, Closed, Open, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Closed, Open]", "safe": true }, { "filename": "100_doors_537.txt", "content": "/* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */\ndoors_100H: procedure options (main);\n\n/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */\n/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */\n /* PL/I */\n %replace dcldoors by 100;\n /* PL/M */ /*\n DECLARE DCLDOORS LITERALLY '101';\n /* */\n\n/* PL/I DEFINITIONS */\n%include 'pg.inc';\n/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /*\n DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';\n DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE';\n DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' ';\n DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1';\n DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.';\n BDOSF: PROCEDURE( FN, ARG )BYTE;\n DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; \n BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;\n PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;\n PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;\n PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;\n PRNUMBER: PROCEDURE( N );\n DECLARE N ADDRESS;\n DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;\n N$STR( W\u00a0:= LAST( N$STR ) ) = '$';\n N$STR( W\u00a0:= W - 1 ) = '0' + ( ( V\u00a0:= N ) MOD 10 );\n DO WHILE( ( V\u00a0:= V / 10 ) > 0 );\n N$STR( W\u00a0:= W - 1 ) = '0' + ( V MOD 10 );\n END; \n CALL BDOS( 9, .N$STR( W ) );\n END PRNUMBER;\n MODF: PROCEDURE( A, B )ADDRESS;\n DECLARE ( A, B ) ADDRESS;\n RETURN A MOD B;\n END MODF;\n/* END LANGUAGE DEFINITIONS */\n\n /* TASK */\n\n /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */\n DECLARE DOOR( DCLDOORS ) BIT;\n DECLARE ( I, J, MAXDOOR ) FIXED BINARY;\n\n MAXDOOR = HBOUND( DOOR ,1\n );\n\n /* SET ALL DOORS TO CLOSED */\n DO I = 0 TO MAXDOOR; DOOR( I ) = FALSE; END;\n /* REPEATEDLY FLIP THE DOORS */\n DO I = 1 TO MAXDOOR;\n DO J = I TO MAXDOOR BY I;\n DOOR( J ) = NOT( DOOR( J ) );\n END;\n END;\n /* DISPLAY THE RESULTS */\n DO I = 1 TO MAXDOOR;\n IF DOOR( I ) THEN DO;\n CALL PRCHAR( ' ' );\n CALL PRNUMBER( I );\n END;\n END;\n CALL PRNL;\n\nEOF: end doors_100H;", "safe": true }, { "filename": "100_doors_538.txt", "content": " 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_539.txt", "content": "actor Toggler\n let doors:Array[Bool]\n let env: Env\n new create(count:USize,_env:Env) =>\n var i:USize=0\n doors=Array[Bool](count)\n env=_env\n while doors.size() < count do\n doors.push(false)\n end\n be togglin(interval\u00a0: USize)=>\n var i:USize=0\n try\n while i < doors.size() do\n doors.update(i,not doors(i)?)?\n i=i+interval\n end\n else\n env.out.print(\"Errored while togglin'!\")\n end\n be printn(onlyOpen:Bool)=>\n try\n for i in doors.keys() do\n if onlyOpen and not doors(i)? then\n continue\n end\n env.out.print(\"Door \" + i.string() + \" is \" +\n if doors(i)? then\n \"Open\"\n else\n \"closed\"\n end)\n end\n else\n env.out.print(\"Error!\")\n end\n true\n\nactor OptimizedToggler\n let doors:Array[Bool]\n let env:Env\n new create(count:USize,_env:Env)=>\n env=_env\n doors=Array[Bool](count)\n while doors.size()\n var i:USize=0\n if alreadydone then\n return\n end\n try\n doors.update(0,true)?\n doors.update(1,true)?\n while i < doors.size() do\n i=i+1\n let z=i*i\n let x=z*z\n if z > doors.size() then\n break\n else\n doors.update(z,true)?\n end\n if x < doors.size() then\n doors.update(x,true)?\n end\n end\n end\n be printn(onlyOpen:Bool)=>\n try\n for i in doors.keys() do\n if onlyOpen and not doors(i)? then\n continue\n end\n env.out.print(\"Door \" + i.string() + \" is \" +\n if doors(i)? then\n \"Open\"\n else\n \"closed\"\n end)\n end\n else\n env.out.print(\"Error!\")\n end\n true\nactor Main\n new create(env:Env)=>\n var count: USize =100\n try\n let index=env.args.find(\"-n\",0,0,{(l,r)=>l==r})?\n try\n match env.args(index+1)?.read_int[USize]()?\n | (let x:USize, _)=>count=x\n end\n else\n env.out.print(\"You either neglected to provide an argument after -n or that argument was not an integer greater than zero.\")\n return\n end\n end\n if env.args.contains(\"optimized\",{(l,r)=>r==l}) then\n let toggler=OptimizedToggler(count,env)\n var i:USize = 1\n toggler.togglin()\n toggler.printn(env.args.contains(\"onlyopen\", {(l,r)=>l==r}))\n else\n let toggler=Toggler(count,env)\n var i:USize = 1\n while i < count do\n toggler.togglin(i)\n i=i+1\n end\n toggler.printn(env.args.contains(\"onlyopen\", {(l,r)=>l==r}))\n end", "safe": true }, { "filename": "100_doors_54.txt", "content": "-- perfectSquaresUpTo\u00a0:: Int -> [Int]\non perfectSquaresUpTo(n)\n script squared\n -- (Int -> Int)\n on |\u03bb|(x)\n x * x\n end |\u03bb|\n end script\n \n set realRoot to n ^ (1 / 2)\n set intRoot to realRoot as integer\n set blnNotPerfectSquare to not (intRoot = realRoot)\n \n map(squared, enumFromTo(1, intRoot - (blnNotPerfectSquare as integer)))\nend perfectSquaresUpTo\n\non run\n \n perfectSquaresUpTo(100)\n \nend run\n", "safe": true }, { "filename": "100_doors_540.txt", "content": "lvars i;\nlvars doors = {% for i from 1 to 100 do false endfor\u00a0%};\nfor i from 1 to 100 do\n for j from i by i to 100 do\n not(doors(j)) -> doors(j);\n endfor;\nendfor;\n;;; Print state\nfor i from 1 to 100 do\n printf('Door ' >< i >< ' is ' ><\n if doors(i) then 'open' else 'closed' endif, '%s\\n');\nendfor;", "safe": true }, { "filename": "100_doors_541.txt", "content": "for i to 100 do\n lvars root = sqrt(i);\n i; if root = round(root) then ' open' ><; else ' closed' ><; endif; =>\nendfor;", "safe": true }, { "filename": "100_doors_542.txt", "content": "/doors [ 100 { false } repeat ] def\n\n1 1 100 { dup 1 sub exch 99 {\n dup doors exch get not doors 3 1 roll put\n} for } for\ndoors pstack", "safe": true }, { "filename": "100_doors_543.txt", "content": "[true false false true false false false false true false ...<90 doors later>... true]", "safe": true }, { "filename": "100_doors_544.txt", "content": "square=1, i=3\n1 to 100(door):\n if (door == square):\n (\"door\", door, \"is open\") say\n square += i\n i += 2.\n.", "safe": true }, { "filename": "100_doors_545.txt", "content": "$doors = @(0..99)\nfor($i=0; $i -lt 100; $i++) {\n $doors[$i] = 0 # start with all doors closed\n}\nfor($i=0; $i -lt 100; $i++) {\n $step = $i + 1\n for($j=$i; $j -lt 100; $j = $j + $step) {\n $doors[$j] = $doors[$j] -bxor 1\n }\n}\nforeach($doornum in 1..100) {\n if($doors[($doornum-1)] -eq $true) {\"$doornum open\"}\n else {\"$doornum closed\"}\n}", "safe": true }, { "filename": "100_doors_546.txt", "content": "function Get-DoorState($NumberOfDoors)\n{\n begin \n {\n $Doors = @()\n $Multiple = 1\n }\n\n process\n {\n for ($i = 1; $i -le $NumberOfDoors; $i++)\n {\n $Door = [pscustomobject]@{\n Name = $i\n Open = $false\n }\n\n $Doors += $Door \n }\n\n While ($Multiple -le $NumberOfDoors)\n {\n\t Foreach ($Door in $Doors)\n\t {\n\t if ($Door.name\u00a0% $Multiple -eq 0)\n {\n\t If ($Door.open -eq $False){$Door.open = $True}\n\t Else {$Door.open = $False}\n\t }\n\t }\n\t\t\t\n $Multiple++\n }\n }\n\n end {$Doors}\n}", "safe": true }, { "filename": "100_doors_547.txt", "content": "$doors = 1..100 | ForEach-Object {0}\n1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_\u00a0% $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { \"door opened\" } else { \"door closed\" } }", "safe": true }, { "filename": "100_doors_548.txt", "content": "$doors = 1..100 | ForEach-Object {0}\n$visited = 1..100\n1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_\u00a0% $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { \"door opened\" } else { \"door closed\" } }", "safe": true }, { "filename": "100_doors_549.txt", "content": "1..100|foreach-object {$pipe += \"toggle $_ |\"} -begin {$pipe=\"\"}\nfilter toggle($pass) {$_.door = $_.door -xor\u00a0!($_.index\u00a0% $pass);$_}\ninvoke-expression \"1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host\"", "safe": true }, { "filename": "100_doors_55.txt", "content": "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}\n", "safe": true }, { "filename": "100_doors_550.txt", "content": "Workflow Calc-Doors {\n Foreach \u2013parallel ($number in 1..100) {\n \"Door \" + $number.ToString(\"0000\") + \": \" + @{$true=\"Closed\";$false=\"Open\"}[([Math]::pow($number, 0.5)%1) -ne 0]\n }\n}\nCalc-Doors | sort", "safe": true }, { "filename": "100_doors_551.txt", "content": "1..10|%{\"Door \"+ $_*$_ + \" is open\"}", "safe": true }, { "filename": "100_doors_552.txt", "content": "boolean[] doors = new boolean[100];\n\nvoid setup() {\n for (int i = 0; i < 100; i++) {\n doors[i] = false;\n }\n for (int i = 1; i < 100; i++) {\n for (int j = 0; j < 100; j += i) {\n doors[j] = !doors[j];\n }\n }\n println(\"Open:\");\n for (int i = 1; i < 100; i++) {\n if (doors[i]) {\n println(i);\n }\n }\n exit();\n}", "safe": true }, { "filename": "100_doors_553.txt", "content": "Open:\n1\n4\n9\n16\n25\n36\n49\n64\n81", "safe": true }, { "filename": "100_doors_554.txt", "content": "setup <- function() {\n for(door in doors(100, 100)) {\n stdout$print(paste(door, \"\"))\n }\n}\n\ndoors <- function(ndoors=100,passes=100) {\n doors <- rep(FALSE,ndoors)\n for (ii in seq(1,passes)) {\n mask <- seq(0,ndoors,ii)\n doors[mask] <- !doors[mask] \n }\n return (which(doors == TRUE))\n}", "safe": true }, { "filename": "100_doors_555.txt", "content": "1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_556.txt", "content": "enableextensions \nenabledelayedexpansion\neditvar /newvar /value=0 /title=closed\neditvar /newvar /value=1 /title=open\neditvar /newvar /range=1-100 /increment=1 /from=2\neditvar /newvar /value=2 /title=next\n:doors\nfor /alloccurrences (!next!-!102!) do editvar /modify /value=-open-\neditvar /modify /value=-next-=+1\nif -next- /hasvalue=100 goto :cont else goto :doors\n:cont\nprintline !1!-!102!\nstoptask", "safe": true }, { "filename": "100_doors_557.txt", "content": "main\u00a0:-\n forall(between(1,100,Door), ignore(display(Door))).\n\n% show output if door is open after the 100th pass\ndisplay(Door)\u00a0:-\n status(Door, 100, open),\n format(\"Door ~d is open~n\", [Door]).\n\n% true if Door has Status after Pass is done\nstatus(Door, Pass, Status)\u00a0:-\n Pass > 0,\n Remainder is Door mod Pass,\n toggle(Remainder, OldStatus, Status),\n OldPass is Pass - 1,\n status(Door, OldPass, OldStatus).\nstatus(_Door, 0, closed).\n\ntoggle(Remainder, Status, Status)\u00a0:-\n Remainder > 0.\ntoggle(0, open, closed).\ntoggle(0, closed, open).", "safe": true }, { "filename": "100_doors_558.txt", "content": "doors_unoptimized(N)\u00a0:-\n\tlength(L, N),\n\tmaplist(init, L),\n\tdoors(N, N, L, L1),\n\taffiche(N, L1).\n\ninit(close).\n\ndoors(Max, 1, L, L1)\u00a0:-\n\t!,\n inverse(1, 1, Max, L, L1).\n\ndoors(Max, N, L, L1)\u00a0:-\n\tN1 is N - 1,\n\tdoors(Max, N1, L, L2),\n\tinverse(N, 1, Max, L2, L1).\n\n\ninverse(N, Max, Max, [V], [V1])\u00a0:-\n\t!,\n\t0 =:= Max mod N -> inverse(V, V1); V1 = V.\n\ninverse(N, M, Max, [V|T], [V1|T1])\u00a0:-\n\tM1 is M+1,\n\tinverse(N, M1, Max, T, T1),\n\t( 0 =:= M mod N -> inverse(V, V1); V1 = V).\n\n\ninverse(open, close).\ninverse(close, open).\n\naffiche(N, L)\u00a0:-\n\tforall(between(1, N, I),\n\t ( nth1(I, L, open) -> format('Door ~w is open.~n', [I]); true)).", "safe": true }, { "filename": "100_doors_559.txt", "content": "doors(Num, Passes)\u00a0:-\n forall(( everyNth(1,Passes,1,Pass)\n , forall((everyNth(Pass,Num,Pass,Door), toggle(Door)))\n ))\n , show(Num)\n .\n\n\ntoggle(Door)\u00a0:-\n Opened = opened(Door)\n , ( clause(Opened,_) -> retract(Opened)\n \u00a0; asserta(Opened)\n ).\n\n\nshow(Num)\u00a0:-\n forall(( between(1,Num,Door)\n , (opened(Door) -> State = opened\u00a0; State = closed)\n , write(Door), write(' '), write(State), nl\n )).\n\n\n% utils\nforall(X)\u00a0:- findall(_, X, _).\n\neveryNth(From,To,Step,X)\u00a0:-\n From =< To\n , ( X = From\u00a0; From1 is From + Step, everyNth(From1,To,Step,X) )\n .\n\nmain\u00a0:- doors(100,100), halt.", "safe": true }, { "filename": "100_doors_56.txt", "content": "openshut(n):\n for x in [1..n]\n x%n==0\n\npass(n):\n if n==100\n openshut(n)\n else\n openshut(n) xor pass(n+1)\n\n100doors():\n pass(1) -> io", "safe": true }, { "filename": "100_doors_560.txt", "content": "doors_optimized(N)\u00a0:-\n\tMax is floor(sqrt(N)),\n\tforall(between(1, Max, I),\n\t ( J is I*I,format('Door ~w is open.~n',[J]))).", "safe": true }, { "filename": "100_doors_561.txt", "content": ";;; find the first few squares via the unoptimised door flipping method\nPROGRAM hundredDoors\nINCLUDE LIBRARY\nCON INT doorMax = 100\nBYTE door [ doorMax + 1 ]\u00a0; door( i ) is true if open, false if closed\nWORD i\nBYTE j\nBEGIN\nFOR i = 0 TO doorMax \u00a0; set all doors to closed\n door[ i ] = false\nFOR i = 1 TO doorMax \u00a0; repeatedly flip the doors\n j = i:<\n WHILE j <= doorMax\n door[ j ] = not door[ j ]\n j = j + i:<\nFOR i = 1 TO doorMax \u00a0; display the results\n IF door[ i ]\n OUTPUT \" #W\", i\nOUTPUT \"#C\"\nEND", "safe": true }, { "filename": "100_doors_562.txt", "content": "using system;\n\n// initialize doors as pairs: number, status where 0 means open\nlet doors = zip (1..100) (repeat 1);\n\ntoogle (x,y) = x,~y;\n\ntoogleEvery n d = map (tooglep n) d with\n tooglep n d@((x,_)) = toogle d if ~(x mod n);\n = d otherwise; end;\n\n// show description of given doors\nstatus (n,x) = (str n) + (case x of\n 1 = \" close\";\n 0 = \" open\"; end);\n\nlet result = foldl (\\a n -> toogleEvery n a) doors (1..100);\n\n// pretty print the result (only open doors)\nshowResult = do (puts.status) final when\n final = filter open result with\n open (_,x) = ~x;\n end; end;", "safe": true }, { "filename": "100_doors_563.txt", "content": " \n> showResult;\n1 open\n4 open\n9 open\n16 open\n25 open\n...\n", "safe": true }, { "filename": "100_doors_564.txt", "content": "100Doors.pd\n\n#N canvas 241 375 414 447 10;\n#X obj 63 256 expr doors[$f1] = doors[$f1] ^ 1;\n#X msg 83 118 \\; doors const 0;\n#X msg 44 66 bang;\n#X obj 44 92 t b b b;\n#X obj 43 28 table doors 101;\n#X obj 44 360 sel 0;\n#X obj 44 336 expr if (doors[$f1] == 1 \\, $f1 \\, 0);\n#X obj 63 204 t b f f;\n#X text 81 66 run;\n#X obj 71 384 print -n;\n#X text 132 310 print results (open doors);\n#X obj 63 179 loop 1 100 1;\n#X obj 63 231 loop 1 100 1;\n#X obj 44 310 loop 1 100 1;\n#X text 148 28 create array;\n#X text 151 180 100 passes;\n#X text 179 123 set values to 0;\n#X connect 2 0 3 0;\n#X connect 3 0 13 0;\n#X connect 3 1 11 0;\n#X connect 3 2 1 0;\n#X connect 5 1 9 0;\n#X connect 6 0 5 0;\n#X connect 7 0 12 0;\n#X connect 7 1 12 1;\n#X connect 7 2 12 3;\n#X connect 11 0 7 0;\n#X connect 12 0 0 0;\n#X connect 13 0 6 0;\n\nloop.pd\n\n#N canvas 656 375 427 447 10;\n#X obj 62 179 until;\n#X obj 102 200 f;\n#X obj 62 89 inlet;\n#X obj 303 158 f \\$3;\n#X obj 270 339 outlet;\n#X obj 223 89 inlet;\n#X obj 138 89 inlet;\n#X obj 324 89 inlet;\n#X obj 117 158 f \\$1;\n#X text 323 68 step;\n#X obj 202 158 f \\$2;\n#X obj 62 118 t b b b b;\n#X obj 270 315 spigot;\n#X obj 89 314 sel 0;\n#X obj 137 206 +;\n#X obj 102 237 expr $f1 \\; if ($f3 > 0 \\, if ($f1 > $f2 \\, 0 \\, 1)\n\\, if ($f3 < 0 \\, if ($f1 < $f2 \\, 0 \\, 1) \\, 0)), f 34;\n#X text 63 68 run;\n#X text 136 68 start;\n#X text 227 68 end;\n#X text 58 31 loop (abstraction);\n#X connect 0 0 1 0;\n#X connect 1 0 14 0;\n#X connect 1 0 15 0;\n#X connect 2 0 11 0;\n#X connect 3 0 14 1;\n#X connect 3 0 15 2;\n#X connect 5 0 10 1;\n#X connect 6 0 8 1;\n#X connect 7 0 3 1;\n#X connect 8 0 1 1;\n#X connect 10 0 15 1;\n#X connect 11 0 0 0;\n#X connect 11 1 8 0;\n#X connect 11 2 10 0;\n#X connect 11 3 3 0;\n#X connect 12 0 4 0;\n#X connect 13 0 0 1;\n#X connect 14 0 1 1;\n#X connect 15 0 12 0;\n#X connect 15 1 12 1;\n#X connect 15 1 13 0;", "safe": true }, { "filename": "100_doors_565.txt", "content": "Dim doors.i(100)\n \nFor x = 1 To 100\n y = x\n While y <= 100\n doors(y) = 1 - doors(y)\n y + x\n Wend\nNext\n \nOpenConsole()\nPrintN(\"Following Doors are open:\")\nFor x = 1 To 100\n If doors(x)\n Print(Str(x) + \", \")\n EndIf\nNext\nInput()", "safe": true }, { "filename": "100_doors_566.txt", "content": "OpenConsole()\nPrintN(\"Following Doors are open:\")\nFor i = 1 To 100\n root.f = Sqr(i)\n If root = Int(root)\n \tPrint (Str(i) + \", \")\n EndIf\nNext \nInput()", "safe": true }, { "filename": "100_doors_567.txt", "content": "Following Doors are open:\n1, 4, 9, 16, 25, 36, 49, 64, 81, 100,", "safe": true }, { "filename": "100_doors_568.txt", "content": "data Door:\n | open\n | closed\nend\n \nfun flip-door(d\u00a0:: Door) -> Door:\n cases(Door) d:\n | open => closed\n | closed => open\n end\nend\n \n\nfun flip-doors(doors\u00a0:: List) -> List:\n doc:```Given a list of door positions, repeatedly switch the positions of\n every nth door for every nth pass, and return the final list of door\n positions```\n for fold(flipped-doors from doors, n from range(1, doors.length() + 1)):\n for map_n(m from 1, d from flipped-doors):\n if num-modulo(m, n) == 0:\n flip-door(d)\n else:\n d\n end\n end\n end\nwhere:\n flip-doors([list: closed, closed, closed]) is\n [list: open, closed, closed]\n\n flip-doors([list: closed, closed, closed, closed]) is\n [list: open, closed, closed, open]\n\n flip-doors([list: closed, closed, closed, closed, closed, closed]) is\n [list: open, closed, closed, open, closed, closed]\n\n closed-100 = for map(_ from range(1, 101)): closed end\n answer-100 = for map(n from range(1, 101)):\n if num-is-integer(num-sqrt(n)): open\n else: closed\n end\n end\n\n flip-doors(closed-100) is answer-100\nend\n\nfun find-indices
(pred\u00a0:: (A -> Boolean), xs\u00a0:: List) -> List:\n doc:```Given a list and a predicate function, produce a list of index\n positions where there's a match on the predicate```\n ps = map_n(lam(n,e): if pred(e): n else: -1 end end, 1, xs)\n ps.filter(lam(x): x >= 0 end)\nwhere:\n find-indices((lam(i): i == true end), [list: true,false,true]) is [list:1,3]\nend\n\n\nfun run(n):\n doc:```Given a list of doors that are closed, make repeated passes \n over the list, switching the positions of every nth door for \n each nth pass. Return a list of positions in the list where the\n door is Open.```\n doors = repeat(n, closed)\n ys = flip-doors(doors)\n find-indices((lam(y): y == open end), ys)\nwhere:\n run(4) is [list: 1,4]\nend\n \nrun(100)", "safe": true }, { "filename": "100_doors_569.txt", "content": "doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\"\u00a0% (i+1), 'open' if doors[i] else 'close')", "safe": true }, { "filename": "100_doors_57.txt", "content": "use std, array\n\nclose all doors\nfor each pass from 1 to 100\n for (door = pass) (door <= 100) (door += pass)\n toggle door\n\nlet int pass, door.\n\n.: close all doors\u00a0:. {memset doors 0 size of doors}\n.:toggle :. { \u00a0!!(doors[door - 1]) }\n\nlet doors be an array of 100 bool\n\nfor each door from 1 to 100\n printf \"#%.3d %s\\n\" door (doors[door - 1])\u00a0? \"[ ]\", \"[X]\"", "safe": true }, { "filename": "100_doors_570.txt", "content": "for i in xrange(1, 101):\n root = i ** 0.5\n print \"Door %d:\"\u00a0% i, 'open' if root == int(root) else 'close'", "safe": true }, { "filename": "100_doors_571.txt", "content": "print '\\n'.join(['Door %s is %s'\u00a0% (i, ('closed', 'open')[(i**0.5).is_integer()]) for i in xrange(1, 101)])", "safe": true }, { "filename": "100_doors_572.txt", "content": "print '\\n'.join('Door %s is %s'\u00a0% (i, 'closed' if i**0.5\u00a0% 1 else 'open') for i in range(1, 101))", "safe": true }, { "filename": "100_doors_573.txt", "content": "for i in range(1, 101):\n if i**0.5\u00a0% 1:\n state='closed'\n else:\n state='open'\n print(\"Door {}:{}\".format(i, state))", "safe": true }, { "filename": "100_doors_574.txt", "content": "for i in range(1,11): print(\"Door %s is open\"\u00a0% i**2)", "safe": true }, { "filename": "100_doors_575.txt", "content": "`closed`open(100#0b){@[x;where y;not]}/100#'(til[100]#'0b),'1b", "safe": true }, { "filename": "100_doors_576.txt", "content": "`closed`open (1+til 100) in {x*x} 1+til 10", "safe": true }, { "filename": "100_doors_577.txt", "content": "@[100#`closed; -1+{x*x}1+til 10;\u00a0:; `open]", "safe": true }, { "filename": "100_doors_578.txt", "content": "Const Opened = -1, Closed = 0\nDim Doors(1 To 100) As Integer, Passes As Integer, Index As Integer\nRem Normal implementation\nPrint \"100doors Normal method\"\nFor Passes = 1 To 100 Step 1\n Doors(Passes) = Closed\nNext Passes\nFor Passes = 1 To 100 Step 1\n For Index = 0 To 100 Step Passes\n If Index > 100 Then Exit For\n If Index > 0 Then If Doors(Index) = Opened Then Doors(Index) = Closed Else Doors(Index) = Opened\n Next Index\nNext Passes\nPrint \"OPEN DOORS after 100th passes\"\nFor Passes = 1 To 100 Step 1\n If Doors(Passes) = Opened Then Print Passes; \" \";\nNext\n\nRem Alternative solution of perfect squares\n\nPrint \"Alternative method\"\nPasses = 0\nFor Passes = 1 To 100 Step 1\n Doors(Passes) = Closed\nNext Passes\nFor Passes = 1 To 100 Step 1\n If Sqr(Passes) = Int(Sqr(Passes)) Then Doors(Passes) = Opened\nNext\nPrint \"Opened doors found by SQR method\"\nFor Passes = 1 To 100 Step 1\n If Doors(Passes) = Opened Then Print Passes; \" \";\nNext Passes\nEnd", "safe": true }, { "filename": "100_doors_579.txt", "content": "/O> [ bit ^ ] is toggle ( f n --> f )\n... \n... [ 0\n... 100 times\n... [ i^ 1+ swap\n... 101 times\n... [ i^ toggle over step ]\n... nip ] ] is toggledoors ( --> f )\n... \n... [ 100 times\n... [ 1 >> dup 1 &\n... if [ i^ 1+ echo sp ] ]\n... drop ] is echodoors ( f --> )\n... \n... toggledoors\n... say \" These doors are open: \" echodoors cr\n... say \" The rest are closed.\" cr\n... \n These doors are open: 1 4 9 16 25 36 49 64 81 100 \n The rest are closed.\n\nStack empty.", "safe": true }, { "filename": "100_doors_58.txt", "content": "/* ARM assembly Raspberry PI */\n/* program 100doors.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \"The door \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\n .asciz \"is open.\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \nstTableDoors:\t.skip 4 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n @ display first line\n ldr r3,iAdrstTableDoors @ table address\n mov r5,#1 \n1:\n mov r4,r5\n2: @ begin loop\n ldr r2,[r3,r4,lsl #2] @ read doors index r4\n cmp r2,#0\n moveq r2,#1 @ if r2 = 0 1 -> r2\n movne r2,#0 @ if r2 = 1 0 -> r2\n str r2,[r3,r4,lsl #2] @ store value of doors\n add r4,r5 @ increment r4 with r5 value\n cmp r4,#NBDOORS @ number of doors\u00a0?\n ble 2b @ no -> loop\n add r5,#1 @ increment the increment\u00a0!!\n cmp r5,#NBDOORS @ number of doors\u00a0?\n ble 1b @ no -> loop\n\n @ loop display state doors\n mov r4,#0 \n3:\n ldr r2,[r3,r4,lsl #2] @ read state doors r4 index\n cmp r2,#0\n beq 4f\n mov r0,r4 @ open -> display message\n ldr r1,iAdrsMessValeur @ display value index\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n4:\n add r4,#1\n cmp r4,#NBDOORS\n ble 3b @ loop\n \n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrstTableDoors:\t\t.int stTableDoors\niAdrsMessResult:\t\t.int sMessResult\n\n/******************************************************************/\n/* display text with size calculation */ \n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t @ address message in r1 \n mov r0,#STDOUT \t\t @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ \n bx lr @ return \n/******************************************************************/\n/* Converting a register to a decimal unsigned */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n // and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n // and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\t\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\t\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n //mov r3,#0xCCCD @ r3 <- magic_number lower @ for Raspberry pi 3\n //movt r3,#0xCCCC @ r3 <- magic_number upper @ for Raspberry pi 3\n ldr r3,iMagicNumber @ for Raspberry pi 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: .int 0xCCCCCCCD", "safe": true }, { "filename": "100_doors_580.txt", "content": "doors_puzzle <- function(ndoors, passes = ndoors) {\n doors <- logical(ndoors)\n for (ii in seq(passes)) {\n mask <- seq(ii, ndoors, ii)\n doors[mask] <- !doors[mask]\t\n }\n which(doors)\n}\n\ndoors_puzzle(100)", "safe": true }, { "filename": "100_doors_581.txt", "content": "x <- rep(1, 100)\nfor (i in 1:100-1) {\n x <- xor(x, rep(c(rep(0,i),1), length.out=100))\n}\nwhich(!x)", "safe": true }, { "filename": "100_doors_582.txt", "content": "doors_puzzle <- function(ndoors=100,passes=100) {\nnames(which(table(unlist(sapply(1:passes, function(X) seq(0, ndoors, by=X))))\u00a0%% 2 == 1))\n}\n\ndoors_puzzle()", "safe": true }, { "filename": "100_doors_583.txt", "content": "H=100\nf=rep(F,H)\nwhich(Reduce(function(d,n) xor(replace(f,seq(n,H,n),T),d), 1:H, f))", "safe": true }, { "filename": "100_doors_584.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_585.txt", "content": "#lang racket\n\n;; Applies fun to every step-th element of seq, leaving the others unchanged.\n(define (map-step fun step seq)\n (for/list ([elt seq] [i (in-naturals)])\n ((if (zero? (modulo i step)) fun values) elt)))\n\n(define (toggle-nth n seq)\n (map-step not n seq))\n\n(define (solve seq)\n (for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)])\n (toggle-nth pass result)))\n\n(for ([door (solve (make-vector 101 #f))] [index (in-naturals)]\n #:when (and door (> index 0)))\n (printf \"~a is open~%\" index))", "safe": true }, { "filename": "100_doors_586.txt", "content": "#lang racket\n(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x)))\n (printf \"~a is open\\n\" x))", "safe": true }, { "filename": "100_doors_587.txt", "content": "#lang slideshow\n(define-syntax-rule (vector-neg! vec pos)\n (vector-set! vec pos (not (vector-ref vec pos))))\n\n(define (make-doors)\n (define doors (make-vector 100 #f))\n (for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j))\n doors)\n\n(displayln (list->string (for/list ([d (make-doors)]) (if d #\\o #\\-))))\n\n(define closed-door (inset (filled-rectangle 4 20) 2))\n(define open-door (inset (rectangle 4 20) 2))\n\n(for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)])\n (hc-append doors (if open? open-door closed-door)))", "safe": true }, { "filename": "100_doors_588.txt", "content": "my @doors = False xx 101;\n \n(.=not for @doors[0, $_ ... 100]) for 1..100;\n \nsay \"Door $_ is \", [ @doors[$_] ] for 1..100;", "safe": true }, { "filename": "100_doors_589.txt", "content": "say \"Door $_ is open\" for map {$^n ** 2}, 1..10;", "safe": true }, { "filename": "100_doors_59.txt", "content": "/*********************************************/\n/* optimized version */\n/*********************************************/\n/* ARM assembly Raspberry PI */\n/* program 100doors.s */\n\n/************************************/\n/* Constantes */\n/************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ NBDOORS, 100\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \"The door \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\n .asciz \"is open.\\n\"\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss \n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n @ display first line\n mov r5,#3 @ start value of increment\n mov r4,#1 @ start doors\n @ loop display state doors\n1:\n mov r0,r4 @ open -> display message\n ldr r1,iAdrsMessValeur @ display value index\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r4,r5 @ add increment\n add r5,#2 @ new increment\n cmp r4,#NBDOORS\n ble 1b @ loop\n \n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @ restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrsMessResult:\t\t.int sMessResult\n\n/******************************************************************/\n/* display text with size calculation */ \n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t @ address message in r1 \n mov r0,#STDOUT \t\t @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ \n bx lr @ return \n/******************************************************************/\n/* Converting a register to a decimal unsigned */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\t\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\t\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n //mov r3,#0xCCCD @ r3 <- magic_number lower @ for raspberry 3\n //movt r3,#0xCCCC @ r3 <- magic_number upper @ for raspberry 3\n ldr r3,iMagicNumber @ for raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: .int 0xCCCCCCCD", "safe": true }, { "filename": "100_doors_590.txt", "content": "say 'Door $_ is open' for (1..10)\u00bb\u00b2;", "safe": true }, { "filename": "100_doors_591.txt", "content": " say \"Door $_ is open\" for 1..10 X** 2;", "safe": true }, { "filename": "100_doors_592.txt", "content": "say \"Door $_ is \", [.sqrt == .sqrt.floor] for 1..100;", "safe": true }, { "filename": "100_doors_593.txt", "content": "sub output( @arr, $max ) {\n my $output = 1;\n for 1..^$max -> $index {\n\tif @arr[$index] {\n\t printf \"%4d\", $index;\n\t say '' if $output++\u00a0%% 10;\n\t}\n }\n say '';\n}\n\nsub MAIN ( Int\u00a0:$doors = 100 ) {\n my $doorcount = $doors + 1;\n my @door[$doorcount] = 0 xx ($doorcount);\n \n INDEX:\n for 1...^$doorcount -> $index {\n # flip door $index & its multiples, up to last door.\n #\n\tfor ($index, * + $index ... *)[^$doors] -> $multiple {\n\t next INDEX if $multiple > $doors;\n\t @door[$multiple] = @door[$multiple]\u00a0?? 0\u00a0!! 1;\n\t}\n }\n output @door, $doors+1;\n}", "safe": true }, { "filename": "100_doors_594.txt", "content": "$ ./100_doors.pl6 -doors=100\n 1 4 9 16 25 36 49 64 81\n", "safe": true }, { "filename": "100_doors_595.txt", "content": "dim x as integer, y as integer\ndim door(1 to 100) as byte\n\n'initialize array\nfor x = 1 to 100\u00a0: door(x) = 0\u00a0: next\n\n'set door values\nfor y = 1 to 100\n for x = y to 100 step y\n door(x) = not door(x)\n next x\nnext y\n\n'print result\nfor x = 1 to 100\n if door(x) then print \"Door \" + str$(x) + \" = open\"\nnext \n\nwhile inkey$=\"\":wend\nend", "safe": true }, { "filename": "100_doors_596.txt", "content": "Door 1 = open\nDoor 4 = open\nDoor 9 = open\nDoor 16 = open\nDoor 25 = open\nDoor 36 = open\nDoor 49 = open\nDoor 64 = open\nDoor 81 = open\nDoor 100 = open", "safe": true }, { "filename": "100_doors_597.txt", "content": "doors: array/initial 100 'closed\nrepeat i 100 [\n door: at doors i\n forskip door i [change door either 'open = first door ['closed] ['open]]\n]", "safe": true }, { "filename": "100_doors_598.txt", "content": "doors: array/initial 100 'closed\nrepeat i 10 [doors/(i * i): 'open]", "safe": true }, { "filename": "100_doors_599.txt", "content": "Red [\n Purpose: \"100 Doors Problem (Perfect Squares)\"\n Author: \"Barry Arthur\"\n Date: \"07-Oct-2016\"\n]\ndoors: make vector! [char! 8 100]\nrepeat i 100 [change at doors i #\".\"]\n\nrepeat i 100 [\n j: i\n while [j <= 100] [\n door: at doors j\n change door either #\"O\" = first door [#\".\"] [#\"O\"]\n j: j + i\n ]\n]\n\nrepeat i 10 [\n print copy/part at doors (i - 1 * 10 + 1) 10\n]", "safe": true }, { "filename": "100_doors_6.txt", "content": "; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html\n; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.\n; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC\n;\n; Notes:\n; Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will \n; be directly shown as pixels in the display.\n; $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops.\n; Y register holds Stride\n; X register holds Index\n; Zero Page address $01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction.\n\n \u00a0; First, zero door array\n LDA #00\n LDX #100\nZ_LOOP:\n STA 200,X\n DEX\n BNE Z_LOOP\n STA 200,X\n\n \u00a0; Now do doors repeated open/close\n LDY #01 \u00a0; Initial value of Stride\nS_LOOP:\n CPY #101\n BCS S_DONE\n TYA \u00a0; Initial value of Index\nI_LOOP:\n CMP #101\n BCS I_DONE\n TAX \u00a0; Use as Door array index\n INC $200,X \u00a0; Toggle bit 0 to reverse state of door\n STY 01 \u00a0; Add stride (Y) to index (X, via A)\n ADC 01\n BCC I_LOOP\nI_DONE:\n INY\n BNE S_LOOP\nS_DONE:\n\n \u00a0; Finally, format array values for output: 0 for closed, 1 for open\n LDX #100\nC_LOOP:\n LDA $200,X\n AND #$01\n STA $200,X\n DEX\n BNE C_LOOP", "safe": true }, { "filename": "100_doors_60.txt", "content": "isOpen: map 1..101 => false\n \nloop 1..100 'pass ->\n\tloop (range.step:pass pass 100) 'door [\n\t\tisOpen\\[door]: not? isOpen\\[door]\n\t]\n\nloop 1..100 'x ->\n\tif isOpen\\[x] [\n\t\tprint [\"Door\" x \"is open.\"]\n\t]\n", "safe": true }, { "filename": "100_doors_600.txt", "content": "Red [\"Doors\"]\n\ndoors: make bitset! len: 100\nrepeat step len [\n\trepeat n to-integer len / step [\n\t\tm: step * n \n\t\tdoors/:m: not doors/:m\n\t]\n]\nrepeat n len [if doors/:n [print n]]", "safe": true }, { "filename": "100_doors_601.txt", "content": "$ENTRY Go {\n = >>;\n};\n\nNDoors { = 100; };\nDoors { = Closed>; };\n\nRepeat {\n 0 s.val =\u00a0;\n s.N s.val = s.val s.val>\u00a0;\n}; \n\nToggle {\n 1 Closed e.rest = Open e.rest;\n 1 Open e.rest = Closed e.rest;\n s.N s.door e.rest = s.door e.rest>;\n};\n \nPass {\n s.pass s.door e.doors, >: '+'\n = e.doors;\n s.pass s.door e.doors\n = >;\n};\n\nWalk {\n s.pass e.doors, >: '+' \n = e.doors;\n s.pass e.doors\n = >;\n};\n\nShow {\n s.N Open e.rest = \n e.rest>;\n s.N Closed e.rest = e.rest>;\n s.N =\u00a0;\n};", "safe": true }, { "filename": "100_doors_602.txt", "content": "Door 1 is open\nDoor 4 is open\nDoor 9 is open\nDoor 16 is open\nDoor 25 is open\nDoor 36 is open\nDoor 49 is open\nDoor 64 is open\nDoor 81 is open\nDoor 100 is open", "safe": true }, { "filename": "100_doors_603.txt", "content": "relation door, state\nset i = 1\nwhile i <= 100\ninsert i, 1\nset i = i+1\nend while\nset i = 2\nwhile i <= 100\nupdate state = 1-state where not (door mod i)\nset i = i+1\nend while\nupdate state = \"open\" where state\nupdate state = \"closed\" where state\u00a0!== \"open\"\nprint", "safe": true }, { "filename": "100_doors_604.txt", "content": ":doors (n-) [ #1 repeat dup-pair n:square gt? 0; drop dup n:square n:put sp n:inc again ] do drop-pair\u00a0;\n#100 doors", "safe": true }, { "filename": "100_doors_605.txt", "content": "/*REXX pgm solves the 100 doors puzzle, doing it the hard way by opening/closing doors.*/\nparse arg doors . /*obtain the optional argument from CL.*/\nif doors=='' | doors==\",\" then doors=100 /*not specified? Then assume 100 doors*/\n /* 0 = the door is closed. */\n /* 1 = \" \" \" open. */\ndoor.=0 /*assume all doors are closed at start.*/\n do #=1 for doors /*process a pass\u2500through for all doors.*/\n do j=# by # to doors /* \u00b7\u00b7\u00b7 every Jth door from this point.*/\n door.j= \\door.j /*toggle the \"openness\" of the door. */\n end /*j*/\n end /*#*/\n\nsay 'After ' doors \" passes, the following doors are open:\"\nsay\n do k=1 for doors\n if door.k then say right(k, 20) /*add some indentation for the output. */\n end /*k*/ /*stick a fork in it, we're all done. */", "safe": true }, { "filename": "100_doors_606.txt", "content": "After 100 passes, the following doors are open:\n\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n 100\n", "safe": true }, { "filename": "100_doors_607.txt", "content": "/*REXX pgm solves the 100 doors puzzle, doing it the easy way by calculating squares.*/\nparse arg doors . /*obtain the optional argument from CL.*/\nif doors=='' | doors==\",\" then doors=100 /*not specified? Then assume 100 doors*/\nsay 'After ' doors \" passes, the following doors are open:\"\nsay\n do #=1 while #**2 <= doors /*process easy pass\u2500through (squares).*/\n say right(#**2, 20) /*add some indentation for the output. */\n end /*#*/ /*stick a fork in it, we're all done. */", "safe": true }, { "filename": "100_doors_608.txt", "content": "doors = list(100)\nfor i = 1 to 100\ndoors[i] = false\nnext\n\nFor pass = 1 To 100\n For door = pass To 100\n if doors[door] doors[door] = false else doors[door] = true ok\n door += pass-1\n Next\nNext\n\nFor door = 1 To 100\n see \"Door (\" + door + \") is \"\n If doors[door] see \"Open\" else see \"Closed\" ok\n see nl\nNext", "safe": true }, { "filename": "100_doors_609.txt", "content": "doors = list(100)\nfor i = 1 to 100\ndoors[i] = false\nnext\n\nFor p = 1 To 10\n doors[pow(p,2)] = True\nNext\n\nFor door = 1 To 100\n see \"Door (\" + door + \") is \"\n If doors[door] see \"Open\" else see \"Closed\" ok\n see nl\nNext", "safe": true }, { "filename": "100_doors_61.txt", "content": "Door 1 is open. \nDoor 4 is open. \nDoor 9 is open. \nDoor 16 is open. \nDoor 25 is open. \nDoor 36 is open. \nDoor 49 is open. \nDoor 64 is open. \nDoor 81 is open. \nDoor 100 is open.", "safe": true }, { "filename": "100_doors_610.txt", "content": " \u226a { }\n { 100 } 0 CON \n 1 100 FOR ii\n ii 100 FOR j\n DUP j GET NOT j SWAP PUT ii STEP \n IF DUP ii GET THEN SWAP ii + SWAP END\n NEXT DROP\n\u226b 'DOORS' STO\n", "safe": true }, { "filename": "100_doors_611.txt", "content": "DOORS ( -- { open_doors } ) \n doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n if doors[i} then print(i)\n// clean stack\n\n", "safe": true }, { "filename": "100_doors_612.txt", "content": "1: { 1 4 9 16 25 36 49 64 81 100 }\n", "safe": true }, { "filename": "100_doors_613.txt", "content": "\u226a { } 1 100 FOR ii IF ii \u221a FP NOT THEN ii + END NEXT \u226b\n", "safe": true }, { "filename": "100_doors_614.txt", "content": "doors = Array.new(101,0)\nprint \"Open doors \"\n(1..100).step(){ |i|\n(i..100).step(i) { |d|\n doors[d] = doors[d]^= 1\n if i == d and doors[d] == 1 then\n print \"#{i} \"\n end\n }\n}", "safe": true }, { "filename": "100_doors_615.txt", "content": "Open doors 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_616.txt", "content": "class Door\n attr_reader :state\n\n def initialize\n @state = :closed\n end\n \n def close\n @state = :closed\n end\n\n def open\n @state = :open\n end\n \n def closed?\n @state == :closed\n end\n \n def open?\n @state == :open\n end\n \n def toggle\n if closed? then open else close end\n end\n \n def to_s\n @state.to_s\n end\nend\n\ndoors = Array.new(100) { Door.new }\n1.upto(100) do |multiplier|\n doors.each_with_index do |door, i|\n door.toggle if (i + 1)\u00a0% multiplier == 0\n end\nend\n\ndoors.each_with_index { |door, i| puts \"Door #{i+1} is #{door}.\" }", "safe": true }, { "filename": "100_doors_617.txt", "content": "n = 100\nOpen = \"open\"\nClosed = \"closed\"\ndef Open.toggle\n Closed\nend\ndef Closed.toggle\n Open\nend\ndoors = [Closed] * (n + 1)\nfor mul in 1..n\n for x in (mul..n).step(mul)\n doors[x] = doors[x].toggle\n end\nend\ndoors.each_with_index do |b, i|\n puts \"Door #{i} is #{b}\" if i > 0\nend", "safe": true }, { "filename": "100_doors_618.txt", "content": "n = 100\n(1..n).each do |i| \n puts \"Door #{i} is #{i**0.5 == (i**0.5).round\u00a0? \"open\"\u00a0: \"closed\"}\"\nend", "safe": true }, { "filename": "100_doors_619.txt", "content": "doors = [false] * 100\n100.times do |i|\n (i ... doors.length).step(i + 1) do |j|\n doors[j] = !doors[j]\n end\nend\nputs doors.map.with_index(1){|d,i| \"Door #{i} is #{d\u00a0? 'open'\u00a0: 'closed'}.\"}", "safe": true }, { "filename": "100_doors_62.txt", "content": "var doors = falses(100)\n\nfor a in 1..100: for b in a..a..100:\n doors[b] = not doors[b]\n\nfor a in 1..100:\n print \"Door $a is ${(doors[a])\u00a0? 'open.': 'closed.'}\"\n", "safe": true }, { "filename": "100_doors_620.txt", "content": "Door 1 is open\nDoor 2 is closed\nDoor 3 is closed\nDoor 4 is open\nDoor 5 is closed\nDoor 6 is closed\nDoor 7 is closed\nDoor 8 is closed\nDoor 9 is open\nDoor 10 is closed\nDoor 11 is closed\nDoor 12 is closed\nDoor 13 is closed\nDoor 14 is closed\nDoor 15 is closed\nDoor 16 is open\nDoor 17 is closed\nDoor 18 is closed\nDoor 19 is closed\nDoor 20 is closed\nDoor 21 is closed\nDoor 22 is closed\nDoor 23 is closed\nDoor 24 is closed\nDoor 25 is open\nDoor 26 is closed\nDoor 27 is closed\nDoor 28 is closed\nDoor 29 is closed\nDoor 30 is closed\nDoor 31 is closed\nDoor 32 is closed\nDoor 33 is closed\nDoor 34 is closed\nDoor 35 is closed\nDoor 36 is open\nDoor 37 is closed\nDoor 38 is closed\nDoor 39 is closed\nDoor 40 is closed\nDoor 41 is closed\nDoor 42 is closed\nDoor 43 is closed\nDoor 44 is closed\nDoor 45 is closed\nDoor 46 is closed\nDoor 47 is closed\nDoor 48 is closed\nDoor 49 is open\nDoor 50 is closed\nDoor 51 is closed\nDoor 52 is closed\nDoor 53 is closed\nDoor 54 is closed\nDoor 55 is closed\nDoor 56 is closed\nDoor 57 is closed\nDoor 58 is closed\nDoor 59 is closed\nDoor 60 is closed\nDoor 61 is closed\nDoor 62 is closed\nDoor 63 is closed\nDoor 64 is open\nDoor 65 is closed\nDoor 66 is closed\nDoor 67 is closed\nDoor 68 is closed\nDoor 69 is closed\nDoor 70 is closed\nDoor 71 is closed\nDoor 72 is closed\nDoor 73 is closed\nDoor 74 is closed\nDoor 75 is closed\nDoor 76 is closed\nDoor 77 is closed\nDoor 78 is closed\nDoor 79 is closed\nDoor 80 is closed\nDoor 81 is open\nDoor 82 is closed\nDoor 83 is closed\nDoor 84 is closed\nDoor 85 is closed\nDoor 86 is closed\nDoor 87 is closed\nDoor 88 is closed\nDoor 89 is closed\nDoor 90 is closed\nDoor 91 is closed\nDoor 92 is closed\nDoor 93 is closed\nDoor 94 is closed\nDoor 95 is closed\nDoor 96 is closed\nDoor 97 is closed\nDoor 98 is closed\nDoor 99 is closed\nDoor 100 is open\n", "safe": true }, { "filename": "100_doors_621.txt", "content": "dim doors(100)\nprint \"Open doors \";\nfor i = 1 to 100 \n for door = i to 100 step i\n doors(door) = (doors(door) <> 1)\n if i = door and doors(door) = 1 then print i;\" \";\n next door\nnext i", "safe": true }, { "filename": "100_doors_622.txt", "content": "Open doors 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_623.txt", "content": "fn main() {\n let mut door_open = [false; 100];\n for pass in 1..101 {\n let mut door = pass;\n while door <= 100 {\n door_open[door - 1] = !door_open[door - 1];\n door += pass;\n }\n }\n for (i, &is_open) in door_open.iter().enumerate() {\n println!(\n \"Door {} is {}.\",\n i + 1,\n if is_open { \"open\" } else { \"closed\" }\n );\n }\n}", "safe": true }, { "filename": "100_doors_624.txt", "content": "fn main() {\n let doors = vec![false; 100]\n .iter_mut()\n .enumerate()\n .map(|(door, door_state)| {\n (1..100)\n .into_iter()\n .filter(|pass| (door + 1)\u00a0% pass == 0)\n .map(|_| {\n *door_state =\u00a0!*door_state;\n *door_state\n })\n .last()\n .unwrap()\n })\n .collect::>();\n\n println!(\"{:?}\", doors);\n}", "safe": true }, { "filename": "100_doors_625.txt", "content": "fn main() {\n let squares: Vec<_> = (1..11).map(|n| n * n).collect();\n let is_square = |num| squares.binary_search(&num).is_ok();\n\n for i in 1..101 {\n let state = if is_square(i) { \"open\" } else { \"closed\" };\n println!(\"Door {} is {}\", i, state);\n }\n}", "safe": true }, { "filename": "100_doors_626.txt", "content": "fn main() {\n for i in 1u32..11u32 {\n println!(\"Door {} is open\", i.pow(2));\n }\n}", "safe": true }, { "filename": "100_doors_627.txt", "content": "$constant DOOR_OPEN = 1\n$constant DOOR_CLOSED = 0\n$constant MAX_DOORS = 100\n\nvar i, j = integer\ndim integer doors(MAX_DOORS)\n\nrem - all doors are initially closed\nfor i = 1 to MAX_DOORS\n doors(i) = DOOR_CLOSED\nnext i\n\nrem - cycle through at increasing intervals and flip doors\nfor i = 1 to MAX_DOORS\n for j = i to MAX_DOORS step i\n doors(j) = 1 - doors(j)\n next j\nnext i\n\nrem - report results\nprint \"The open doors are:\"\nfor i = 1 to MAX_DOORS\n if doors(i) = DOOR_OPEN then\n print i;\nnext i\n\nend", "safe": true }, { "filename": "100_doors_628.txt", "content": "The open doors are:\n 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_629.txt", "content": "variable door,\n isOpen = Char_Type [101],\n pass;\n \nfor (door = 1; door <= 100; door++) {\n isOpen[door] = 0;\n}\n \nfor (pass = 1; pass <= 100; pass++) {\n for (door = pass; door <= 100; door += pass) {\n isOpen[door] = not isOpen[door];\n }\n}\n \nfor (door = 1; door <= 100; door++) {\n if (isOpen[door]) {\n print(\"Door \" + string(door) + \":open\");\n } else {\n print(\"Door \" + string(door) + \":close\");\n }\n}", "safe": true }, { "filename": "100_doors_63.txt", "content": "for(int i = 1; i < 100; ++i) {\n if (i % i^2 < 11) {\n write(\"Door \", i^2, suffix=none);\n write(\" is open\");\n }\n }\n", "safe": true }, { "filename": "100_doors_630.txt", "content": "variable open\u00a0:= <<(* --> false)>>;\nfor (pass; 1; pass <= 100)\n for (door_num; pass; door_num <= 100; pass)\n open[door_num]\u00a0:=\u00a0!(open[door_num]);;;\niterate (door_num; [1...100])\n print(\"Door \", door_num, \" is \",\n (open[door_num]\u00a0? \"open.\\n\"\u00a0: \"closed.\\n\"));;", "safe": true }, { "filename": "100_doors_631.txt", "content": "iterate (x; [1...10]) { iterate (y; [(x-1)*(x-1)+1...x*x-1]) { print(\"Door \", y, \" is closed.\\n\"); }; print(\"Door \", x*x, \" is open.\\n\"); };", "safe": true }, { "filename": "100_doors_632.txt", "content": "variable y:=1;for(x;1;x<101)\"Door \"~sprint(x)~\" is \"~(x==y*y?{++y;return\"open\";}:\"closed\")!;", "safe": true }, { "filename": "100_doors_633.txt", "content": "data _null_;\n open=1;\n close=0;\n array Door{100};\n do Pass = 1 to 100;\n do Current = Pass to 100 by Pass;\n if Door{Current} ne open \n then Door{Current} = open;\n else Door{Current} = close;\n end;\n end;\n NumberOfOpenDoors = sum(of Door{*});\n put \"Number of Open Doors: \" NumberOfOpenDoors; \nrun;", "safe": true }, { "filename": "100_doors_634.txt", "content": "class MAIN is\n main is\n doors :ARRAY{BOOL}\u00a0:= #(100);\n loop\n pass::= doors.ind!;\n loop\n i::= pass.stepto!(doors.size - 1, pass + 1);\n doors[i]\u00a0:= ~doors[i];\n end;\n end;\n loop\n #OUT + (doors.ind! + 1) + \" \" + doors.elt! + \"\\n\";\n end;\n end;\nend;", "safe": true }, { "filename": "100_doors_635.txt", "content": "for { i <- 1 to 100\n r = 1 to 100 map (i\u00a0% _ == 0) reduceLeft (_^_) \n } println (i +\" \"+ (if (r) \"open\" else \"closed\"))", "safe": true }, { "filename": "100_doors_636.txt", "content": "def openDoors(length\u00a0: Int = 100) = {\n var isDoorOpen = new Array[Boolean](length)\n\n for (i <- 0 until length) {\n for (j <- i until length by i + 1) {\n isDoorOpen(j) ^= true\n }\n }\n isDoorOpen\n}\n\nval doorState = scala.collection.immutable.Map(false -> \"closed\", true -> \"open\")\nval isDoorOpen = openDoors()\n\nfor (doorNo <- 0 until isDoorOpen.length) {\n println(\"Door %d is %s\".format(doorNo + 1, doorState(isDoorOpen(doorNo))))\n}", "safe": true }, { "filename": "100_doors_637.txt", "content": "val o = 1 to 10 map (i => i * i)\nprintln(\"open: \" + o)\nprintln(\"closed: \" + (1 to 100 filterNot o.contains))", "safe": true }, { "filename": "100_doors_638.txt", "content": "(define *max-doors* 100)\n\n(define (show-doors doors)\n (let door ((i 0)\n (l (vector-length doors)))\n (cond ((= i l) \n (newline))\n (else \n (printf \"~nDoor ~a is ~a\" \n (+ i 1) \n (if (vector-ref doors i) \"open\" \"closed\"))\n (door (+ i 1) l)))))\n\n(define (flip-doors doors)\n (define (flip-all i)\n (cond ((> i *max-doors*) doors)\n (else \n (let flip ((idx (- i 1)))\n (cond ((>= idx *max-doors*) \n (flip-all (+ i 1))) \n (else \n (vector-set! doors idx (not (vector-ref doors idx)))\n (flip (+ idx i))))))))\n (flip-all 1))\n\n(show-doors (flip-doors (make-vector *max-doors* #f)))", "safe": true }, { "filename": "100_doors_639.txt", "content": "(define (optimised-flip-doors doors)\n (define (flip-all i)\n (cond ((> i (floor (sqrt *max-doors*))) doors)\n (else \n (vector-set! doors (- (* i i) 1) #t)\n (flip-all (+ i 1)))))\n (flip-all 1))\n\n(show-doors (optimised-flip-doors (make-vector *max-doors* #f)))", "safe": true }, { "filename": "100_doors_64.txt", "content": "#include \"share/atspre_staload.hats\"\n\nimplement\nmain0((*void*)) = let\n//\nvar A = @[bool][100](false)\nval A = $UNSAFE.cast{arrayref(bool,100)}(addr@A)\n//\nfnx\nloop\n(\n pass: intGte(0)\n)\u00a0: void =\n if pass < 100\n then loop2 (pass, pass)\n // end of [if]\nand\nloop2\n(\n pass: natLt(100), door: intGte(0)\n)\u00a0: void =\n if door < 100\n then (A[door]\u00a0:= ~A[door]; loop2(pass, door+pass+1))\n else loop(pass+1)\n // end of [if]\n//\nfun\nloop3\n(\n door: intGte(0)\n)\u00a0: void =\n if door < 100\n then (\n println!(\"door #\", door+1, \" is \", (if A[door] then \"open\" else \"closed\"): string, \".\");\n loop3(door+1)\n ) (* end of [then] *)\n // end of [if]\n//\nin\n loop(0); loop3 (0)\nend // end of [main0]", "safe": true }, { "filename": "100_doors_640.txt", "content": "(define (N_doors N)\n (define (init)\n (define (str n)\n (if (> n N) '() (cons 0 (str (+ 1 n)))))\n (str 1))\n (define (toggle x str)\n (define (s n lis)\n (define (revert x)\n (if (eq? x 0) 1 0))\n (cond ((null? lis) '())\n ((zero? (remainder n x)) (cons (revert (car lis)) (s (+ n 1) (cdr lis))))\n (else (cons (car lis) (s (+ n 1) (cdr lis))))))\n (s 1 str))\n (define (iterate x lis)\n (if (> x N) lis (iterate (+ x 1) (toggle x lis))))\n (iterate 1 (init)))\n(N_doors 100)", "safe": true }, { "filename": "100_doors_641.txt", "content": "(1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)\n", "safe": true }, { "filename": "100_doors_642.txt", "content": "doors=zeros(1,100);\nfor i = 1:100\n for j = i:i:100\n doors(j) = ~doors(j);\n end\nend\nfor i = 1:100\n if ( doors(i) )\n s = \"open\";\n else\n s = \"closed\";\n end\n printf(\"%d %s\\n\", i, s);\nend", "safe": true }, { "filename": "100_doors_643.txt", "content": "1 open\n2 closed\n3 closed\n4 open\n5 closed\n6 closed\n7 closed\n8 closed\n9 open\n10 closed\n11 closed\n12 closed\n13 closed\n14 closed\n15 closed\n16 open\n17 closed\n18 closed\n19 closed\n20 closed\n21 closed\n22 closed\n23 closed\n24 closed\n25 open\n26 closed\n27 closed\n28 closed\n29 closed\n30 closed\n31 closed\n32 closed\n33 closed\n34 closed\n35 closed\n36 open\n37 closed\n38 closed\n39 closed\n40 closed\n41 closed\n42 closed\n43 closed\n44 closed\n45 closed\n46 closed\n47 closed\n48 closed\n49 open\n50 closed\n51 closed\n52 closed\n53 closed\n54 closed\n55 closed\n56 closed\n57 closed\n58 closed\n59 closed\n60 closed\n61 closed\n62 closed\n63 closed\n64 open\n65 closed\n66 closed\n67 closed\n68 closed\n69 closed\n70 closed\n71 closed\n72 closed\n73 closed\n74 closed\n75 closed\n76 closed\n77 closed\n78 closed\n79 closed\n80 closed\n81 open\n82 closed\n83 closed\n84 closed\n85 closed\n86 closed\n87 closed\n88 closed\n89 closed\n90 closed\n91 closed\n92 closed\n93 closed\n94 closed\n95 closed\n96 closed\n97 closed\n98 closed\n99 closed\n100 open\n", "safe": true }, { "filename": "100_doors_644.txt", "content": "$ include \"seed7_05.s7i\";\n \nconst proc: main is func\n local\n var array boolean: doorOpen is 100 times FALSE;\n var integer: pass is 0;\n var integer: index is 0;\n var array[boolean] string: closedOrOpen is [boolean] (\"closed\", \"open\");\n begin\n for pass range 1 to 100 do\n for key index range doorOpen do\n if index rem pass = 0 then\n doorOpen[index]\u00a0:= not doorOpen[index];\n end if;\n end for;\n end for;\n for key index range doorOpen do\n write(index lpad 3 <& \" is \" <& closedOrOpen[doorOpen[index]] rpad 7);\n if index rem 5 = 0 then\n writeln;\n end if;\n end for;\n end func;", "safe": true }, { "filename": "100_doors_645.txt", "content": "$ include \"seed7_05.s7i\";\n\nconst proc: main is func\n local\n var integer: index is 0;\n var integer: number is 0;\n var array[boolean] string: closedOrOpen is [boolean] (\"closed\", \"open\");\n begin\n for index range 1 to 100 do\n number\u00a0:= sqrt(index);\n write(index lpad 3 <& \" is \" <& closedOrOpen[number**2 = index] rpad 7);\n if index rem 5 = 0 then\n writeln;\n end if;\n end for;\n end func;", "safe": true }, { "filename": "100_doors_646.txt", "content": " 1 is open 2 is closed 3 is closed 4 is open 5 is closed \n 6 is closed 7 is closed 8 is closed 9 is open 10 is closed \n 11 is closed 12 is closed 13 is closed 14 is closed 15 is closed \n 16 is open 17 is closed 18 is closed 19 is closed 20 is closed \n 21 is closed 22 is closed 23 is closed 24 is closed 25 is open \n 26 is closed 27 is closed 28 is closed 29 is closed 30 is closed \n 31 is closed 32 is closed 33 is closed 34 is closed 35 is closed \n 36 is open 37 is closed 38 is closed 39 is closed 40 is closed \n 41 is closed 42 is closed 43 is closed 44 is closed 45 is closed \n 46 is closed 47 is closed 48 is closed 49 is open 50 is closed \n 51 is closed 52 is closed 53 is closed 54 is closed 55 is closed \n 56 is closed 57 is closed 58 is closed 59 is closed 60 is closed \n 61 is closed 62 is closed 63 is closed 64 is open 65 is closed \n 66 is closed 67 is closed 68 is closed 69 is closed 70 is closed \n 71 is closed 72 is closed 73 is closed 74 is closed 75 is closed \n 76 is closed 77 is closed 78 is closed 79 is closed 80 is closed \n 81 is open 82 is closed 83 is closed 84 is closed 85 is closed \n 86 is closed 87 is closed 88 is closed 89 is closed 90 is closed \n 91 is closed 92 is closed 93 is closed 94 is closed 95 is closed \n 96 is closed 97 is closed 98 is closed 99 is closed 100 is open \n", "safe": true }, { "filename": "100_doors_647.txt", "content": "put false repeated 100 times as a list into Doors100\n\nrepeat 1 to 100\n\tset step to it\n\trepeat step to 100 by step \n\t\tset newValue to not item it of Doors100\n\t\tset item it of Doors100 to newValue\n\tend repeat\nend repeat\n\nput the counter for each item of Doors100 which is true", "safe": true }, { "filename": "100_doors_648.txt", "content": "(1,4,9,16,25,36,49,64,81,100)", "safe": true }, { "filename": "100_doors_649.txt", "content": "import ;\n\nmain:=\n\tlet\n\t\tdoors\u00a0:= flipDoors(duplicate(false, 100), 1);\n\t\topen[i]\u00a0:= i when doors[i];\n\tin\n\t\topen;\n\t\nflipDoors(doors(1), count)\u00a0:=\n\tlet\n\t\tnewDoors[i]\u00a0:= not doors[i] when i mod count = 0 else doors[i];\n\tin\n\t\tdoors when count >= 100 else flipDoors(newDoors, count + 1);", "safe": true }, { "filename": "100_doors_65.txt", "content": "Loop, 100\n Door%A_Index% := \"closed\"\n\nLoop, 100 {\n x := A_Index, y := A_Index\n While (x <= 100)\n {\n CurrentDoor := Door%x%\n If CurrentDoor contains closed\n {\n Door%x% := \"open\"\n x += y\n }\n else if CurrentDoor contains open\n {\n Door%x% := \"closed\"\n x += y\n }\n }\n}\n\nLoop, 100 {\n CurrentDoor := Door%A_Index%\n If CurrentDoor contains open\n Res .= \"Door \" A_Index \" is open`n\"\n}\nMsgBox % Res\n", "safe": true }, { "filename": "100_doors_650.txt", "content": "main\u00a0:= flipDoors([1], 2);\n\nflipDoors(openDoors(1), i)\u00a0:=\n\topenDoors when i * i >= 100 else flipDoors(openDoors ++ [i * i], i + 1);", "safe": true }, { "filename": "100_doors_651.txt", "content": "program hundred_doors;\n\nconst toggle\u00a0:= {['open', 'closed'], ['closed', 'open']};\n\ndoorStates\u00a0:= ['closed'] * 100;\n\n(for interval in [1..100])\n doorStates\u00a0:= [if i mod interval = 0 then\n toggle(prevState) else\n prevState end:\n prevState = doorStates(i)];\nend;\n\n(for finalState = doorStates(i))\n print('door', i, 'is', finalState);\nend;\n\nend program;", "safe": true }, { "filename": "100_doors_652.txt", "content": "program hundred_doors;\n\ndoorStates\u00a0:= (+/ [['closed'] * oddNum with 'open': oddNum in [1,3..17]]);\n\n(for finalState = doorStates(i))\n print('door', i, 'is', finalState);\nend;\n\nend program;", "safe": true }, { "filename": "100_doors_653.txt", "content": "!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! I n i t i a l i z a t i o n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndoors% = 100\n\ndim doorArray?(doors%)\n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! M a i n L o g i c A r e a\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n// Initialize Array\nfor index% = 1 to doors%\n doorArray?(index%) = false\nnext index%\n\n// Execute routine\ntoggle_doors\n\n// Print results\nfor index% = 1 to doors%\n if doorArray?(index%) = true then print index%, ' is open'\nnext index%\n\n\nstop\n\n\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n! R o u t i n e s\n!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nroutine toggle_doors\n for index_outer% = 1 to doors%\n for index_inner% = 1 to doors%\n if mod(index_inner%, index_outer%) = 0 then\n doorArray?(index_inner%) = not doorArray?(index_inner%) \n end if\n next index_inner%\n next index_outer%\nend routine\n\n\nend", "safe": true }, { "filename": "100_doors_654.txt", "content": "var doors = []\n\n{ |pass|\n { |i|\n if (pass `divides` i) {\n doors[i]\u00a0:= false -> not!\n }\n } << 1..100\n} << 1..100\n\n{ |i|\n say (\"Door %3d is %s\"\u00a0% (i, doors[i]\u00a0? 'open'\u00a0: 'closed'))\n} << 1..100", "safe": true }, { "filename": "100_doors_655.txt", "content": "{ |i|\n \"Door\u00a0%3d is\u00a0%s\\n\".printf(i, [i.is_sqr])\n} << 1..100", "safe": true }, { "filename": "100_doors_656.txt", "content": "BEGIN\n INTEGER LIMIT = 100, door, stride;\n BOOLEAN ARRAY DOORS(1:LIMIT);\n TEXT intro;\n\n FOR stride\u00a0:= 1 STEP 1 UNTIL LIMIT DO\n FOR door\u00a0:= stride STEP stride UNTIL LIMIT DO\n DOORS(door)\u00a0:= NOT DOORS(door);\n\n intro\u00a0:- \"All doors closed but \";\n FOR door\u00a0:= 1 STEP 1 UNTIL LIMIT DO\n IF DOORS(door) THEN BEGIN\n OUTTEXT(intro); OUTINT(door, 0); intro\u00a0:- \", \"\n END;\n OUTIMAGE\nEND.", "safe": true }, { "filename": "100_doors_657.txt", "content": "All doors closed but 1, 4, 9, 16, 25, 36, 49, 64, 81, 100", "safe": true }, { "filename": "100_doors_658.txt", "content": "define: #a -> (Array newSize: 100).\na infect: [| :_ | False].\n\na keysDo: [| :pass |\n pass to: a indexLast by: pass do: [| :door |\n a at: door infect: #not `er]].\n\na keysAndValuesDo: [| :door :isOpen |\n inform: 'door #'\u00a0; door\u00a0; ' is '\u00a0; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].", "safe": true }, { "filename": "100_doors_659.txt", "content": "define: #a -> (Array newSize: 100).\na infect: [| :_ | False].\n\n0 below: 10 do: [| :door | a at: door squared put: True].\na keysAndValuesDo: [| :door :isOpen |\n inform: 'door #'\u00a0; door\u00a0; ' is '\u00a0; (isOpen ifTrue: ['open'] ifFalse: ['closed'])].", "safe": true }, { "filename": "100_doors_66.txt", "content": "increment := 3, square := 1 \nLoop, 100 \n If (A_Index = square) \n outstring .= \"`nDoor \" A_Index \" is open\" \n ,square += increment, increment += 2 \nMsgBox,, Succesfull, % SubStr(outstring, 2)\n", "safe": true }, { "filename": "100_doors_660.txt", "content": "|a|\na\u00a0:= Array new: 100 .\n1 to: 100 do: [ :i | a at: i put: false ].\n\n1 to: 100 do: [ :pass |\n pass to: 100 by: pass do: [ :door |\n a at: door put: (a at: door) not .\n ]\n].\n\n\"output\"\n1 to: 100 do: [ :door |\n ( 'door #%1 is %2'\u00a0%\n { door . (a at: door) ifTrue: [ 'open' ] ifFalse: [ 'closed' ] } ) displayNl\n]", "safe": true }, { "filename": "100_doors_661.txt", "content": "|a|\na\u00a0:= (1 to: 100) collect: [ :x | false ].\n1 to: 10 do: [ :i | a at: (i squared) put: true ].\n1 to: 100 do: [ :i |\n ( 'door #%1 is %2'\u00a0% { i . \n (a at: i) ifTrue: [ 'open' ] \n ifFalse: [ 'closed' ] }\n ) displayNl\n]", "safe": true }, { "filename": "100_doors_662.txt", "content": "| m w h smh smw delay closedDoor border subMorphList |\n\nclosedDoor\u00a0:= Color black.\nborder\u00a0:= Color veryLightGray.\ndelay\u00a0:= Delay forMilliseconds: 50.\nw\u00a0:= World bounds corner x.\nh\u00a0:= (World bounds corner y) / 2.\nsmw\u00a0:= w/100.\nsmh\u00a0:= h/2.\n\nm\u00a0:= BorderedMorph new position: 0@h.\nm height: smh; width: w; borderColor: border.\nm color: Color veryLightGray.\n\n1 to: 100 do: [ :pos || sm |\n\tsm\u00a0:= BorderedMorph new height: smh\u00a0; width: smw\u00a0; \n\t\tborderColor: border; color: closedDoor; \n\t\tposition: (smw*pos)@h.\n\tm addMorph: sm asElementNumber: pos].\n\nm openInWorld.\ndelay wait.\nsubMorphList\u00a0:= m submorphs.\n\"display every step\"\n[1 to: 100 do: [ :step |\n\tstep to: 100 by: step do: [ :pos | | subMorph |\n\t\tsubMorph\u00a0:= subMorphList at: pos.\n\t\tsubMorph color: subMorph color negated.\n\t\tdelay wait]]] fork.", "safe": true }, { "filename": "100_doors_663.txt", "content": "x=1!y=3!z=0\nPRINT \"Open doors: \";x;\" \";\nDO\n z=x+y\n PRINT z;\" \";\n x=z\n y=y+2\nUNTIL z>=100\nEND", "safe": true }, { "filename": "100_doors_664.txt", "content": "\t\tDEFINE('PASS(A,I),O')\t\t:(PASS.END)\nPASS\t\tO = 0\nPASS.LOOP\tO = O + I\n\t\tEQ(A,1)\t\t\t:S(PASS.1)F(PASS.0)\nPASS.0\t\tA = 1\t\t\t:S(PASS.LOOP)F(RETURN)\nPASS.1\t\tA = 0\t\t\t:S(PASS.LOOP)F(RETURN)\nPASS.END\n \nMAIN\t\tD = ARRAY(100,0)\n\t\tI = 0\n \nMAIN.LOOP\tI = LE(I,100) I + 1\t\t:F(OUTPUT)\n\t\tPASS(D,I)\t\t\t:(MAIN.LOOP)\n \nOUTPUT\t\tI = 1\u00a0; OPEN = 'Opened doors are: '\nOUTPUT.LOOP\tOPEN = OPEN EQ(D,1) \" \" I\n\t\tI = LE(I,100) I + 1\t\t:S(OUTPUT.LOOP)F(OUTPUT.WRITE)\nOUTPUT.WRITE\tOUTPUT = OPEN\n\nEND", "safe": true }, { "filename": "100_doors_665.txt", "content": "$ snobol4 100doors.sno \nThe Macro Implementation of SNOBOL4 in C (CSNOBOL4) Version 1.3+\n by Philip L. Budne, January 23, 2011\nSNOBOL4 (Version 3.11, May 19, 1975)\n Bell Telephone Laboratories, Incorporated\n\nNo errors detected in source program\n\nOpened doors are: 1 4 9 16 25 36 49 64 81 100\nNormal termination at level 0\n100doors.sno:18: Last statement executed was 19\n", "safe": true }, { "filename": "100_doors_666.txt", "content": "MAIN\t\tD = ARRAY(100,0)\n\t\tI = 1\n\nMAIN.LOOP\tLE(I, 10)\t\t\t:F(OUTPUT)\n\t\tD = 1\t\t\n\t\tI = I + 1\t\t\t:(MAIN.LOOP)\n\nOUTPUT\t\tI = 1\u00a0; O = 'Opened doors are: '\nOUTPUT.LOOP\tO = O EQ(D,1) \" \" I\n\t\tI = LE(I,100) I + 1\t\t:S(OUTPUT.LOOP)F(OUTPUT.WRITE)\nOUTPUT.WRITE\tOUTPUT = O\nEND", "safe": true }, { "filename": "100_doors_667.txt", "content": "#!/usr/local/bin/spar\npragma annotate( summary, \"doors\" )\n @( description, \"Problem: You have 100 doors in a row that are all initially closed. You\" )\n @( description, \"make 100 passes by the doors. The first time through, you visit every door\" )\n @( description, \"and toggle the door (if the door is closed, you open it; if it is open, you\" )\n @( description, \"close it). The second time you only visit every 2nd door (door #2, #4, #6,\" )\n @( description, \"...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you\" )\n @( description, \"only visit the 100th door.\" )\n @( description, \"Question: What state are the doors in after the last pass? Which are open,\" )\n @( description, \"which are closed?\" )\n @( see_also, \"http://rosettacode.org/wiki/100_doors\" )\n @( author, \"Ken O. Burtch\" );\npragma license( unrestricted );\n\npragma restriction( no_external_commands );\n\nprocedure Doors is\n type Door_State is (Closed, Open);\n type Door_List is array(1..100) of Door_State;\n The_Doors\u00a0: Door_List;\nbegin\n for I in 1..100 loop\n The_Doors(I)\u00a0:= Closed;\n end loop;\n for I in 1..100 loop\n for J in arrays.first(The_Doors)..arrays.last(The_Doors) loop\n if J mod I = 0 then\n if The_Doors(J) = Closed then\n The_Doors(J)\u00a0:= Open;\n else\n The_Doors(J)\u00a0:= Closed;\n end if;\n end if;\n end loop;\n end loop;\n for I in arrays.first(The_Doors)..arrays.last(The_Doors) loop\n put (I) @ (\" is \") @ (The_Doors(I));\n new_line;\n end loop;\nend Doors;", "safe": true }, { "filename": "100_doors_668.txt", "content": "/* declare the variables */\nvar isOpen = {};\nvar pass, door;\n\n/* initialize the doors */\nfor door = 0; door < 100; door++ {\n\tisOpen[door] = true;\n}\n\n/* do the 99 remaining passes */\nfor pass = 1; pass < 100; ++pass {\n\tfor door = pass; door < 100; door += pass+1 {\n \t\tisOpen[door] = !isOpen[door];\n\t}\n}\n\n/* print the results */\nvar states = { true: \"open\", false: \"closed\" };\nfor door = 0; door < 100; door++ {\n\tprintf(\"Door #%d is %s.\\n\", door+1, states[isOpen[door]]);\n}", "safe": true }, { "filename": "100_doors_669.txt", "content": "/* declare the variables */\nvar door_sqrt = 1;\nvar door;\n\n/* print the perfect square doors as open */\nfor door = 0; door < 100; door++ {\n\tif (door_sqrt*door_sqrt == door+1) {\n\t\tprintf(\"Door #%d is open.\\n\", door+1);\n\t\tdoor_sqrt ++;\n\t} else {\n\t\tprintf(\"Door #%d is closed.\\n\", door+1);\n\t}\n}", "safe": true }, { "filename": "100_doors_67.txt", "content": "While (Door := A_Index ** 2) <= 100\n Result .= \"Door \" Door \" is open`n\"\nMsgBox, %Result%\n", "safe": true }, { "filename": "100_doors_670.txt", "content": "con\n _clkmode = xtal1+pll16x\n _clkfreq = 80_000_000\n\nobj\n ser\u00a0: \"FullDuplexSerial.spin\"\n\npub init\n ser.start(31, 30, 0, 115200)\n\n doors\n\n waitcnt(_clkfreq + cnt)\n ser.stop\n cogstop(0)\n\nvar\n\n byte door[101] ' waste one byte by using only door[1..100]\n\npri doors | i,j\n\n repeat i from 1 to 100\n repeat j from i to 100 step i\n not door[j]\n\n ser.str(string(\"Open doors: \"))\n\n repeat i from 1 to 100\n if door[i]\n ser.dec(i)\n ser.tx(32)\n\n ser.str(string(13,10))", "safe": true }, { "filename": "100_doors_671.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100_doors_672.txt", "content": "DECLARE\t@sqr int,\n\t\t@i int,\n\t\t@door int;\n\t\t\nSELECT @sqr =1,\n\t@i = 3,\n\t@door = 1;\t\n\t\t\t\t\nWHILE(@door <=100)\nBEGIN\n\tIF(@door = @sqr)\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CAST(@door as char)) + ' is open.';\n\t\tSET @sqr= @sqr+@i;\n\t\tSET @i=@i+2;\n\tEND\n\tELSE\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CONVERT(char,@door)) + ' is closed.';\n\tEND\nSET @door = @door + 1\nEND", "safe": true }, { "filename": "100_doors_673.txt", "content": "with numbers as (\n select generate_series(1, 100) as n\n),\npasses as (\n select passes.n pass, doors.n door \n from numbers doors\n cross join numbers passes \n where doors.n\u00a0% passes.n = 0 -- modulo\n),\ncounting as (\n select door, count(pass) pass_number \n from passes\n group by door\n) \nselect door from counting\nwhere pass_number\u00a0% 2 = 1\norder by door", "safe": true }, { "filename": "100_doors_674.txt", "content": "with numbers as (\n select rownum as n from dual connect by level <= 100\n),\npasses as (\n select doors.n door, count(passes.n) pass_number\n from numbers doors\n cross join numbers passes \n where MOD(doors.n, passes.n) = 0 -- modulo\n group by doors.n\n)\nselect door from passes\nwhere MOD(pass_number, 2) = 1\norder by door", "safe": true }, { "filename": "100_doors_675.txt", "content": "door|\n----+\n 1|\n 4|\n 9|\n ...\n", "safe": true }, { "filename": "100_doors_676.txt", "content": "--#SET TERMINATOR @\n\nSET SERVEROUTPUT ON @\n\nBEGIN\n DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY [100];\n DECLARE DOORS DOORS_ARRAY;\n DECLARE I SMALLINT;\n DECLARE J SMALLINT;\n DECLARE STATUS CHAR(10);\n DECLARE SIZE SMALLINT DEFAULT 100;\n\n -- Initializes the array, with all spaces (doors) as false (closed).\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET DOORS[I] = FALSE;\n SET I = I + 1;\n END WHILE;\n\n -- Processes the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET J = 1;\n WHILE (J <= SIZE) DO\n IF (MOD(J, I) = 0) THEN\n IF (DOORS[J] = TRUE) THEN\n SET DOORS[J] = FALSE;\n ELSE\n SET DOORS[J] = TRUE;\n END IF;\n END IF;\n SET J = J + 1;\n END WHILE;\n SET I = I + 1;\n END WHILE;\n\n -- Prints the final status o the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END);\n CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS);\n SET I = I + 1;\n END WHILE;\nEND @", "safe": true }, { "filename": "100_doors_677.txt", "content": "db2 -td@\ndb2 => BEGIN\n...\ndb2 (cont.) => END @\nDB20000I The SQL command completed successfully.\n\nDoor 1 is OPEN \nDoor 2 is CLOSED \nDoor 3 is CLOSED \nDoor 4 is OPEN \nDoor 5 is CLOSED \nDoor 6 is CLOSED \nDoor 7 is CLOSED \nDoor 8 is CLOSED \nDoor 9 is OPEN \nDoor 10 is CLOSED \nDoor 11 is CLOSED \nDoor 12 is CLOSED \nDoor 13 is CLOSED \nDoor 14 is CLOSED \nDoor 15 is CLOSED \nDoor 16 is OPEN \nDoor 17 is CLOSED \nDoor 18 is CLOSED \nDoor 19 is CLOSED \nDoor 20 is CLOSED \nDoor 21 is CLOSED \nDoor 22 is CLOSED \nDoor 23 is CLOSED \nDoor 24 is CLOSED \nDoor 25 is OPEN \nDoor 26 is CLOSED \nDoor 27 is CLOSED \nDoor 28 is CLOSED \nDoor 29 is CLOSED \nDoor 30 is CLOSED \nDoor 31 is CLOSED \nDoor 32 is CLOSED \nDoor 33 is CLOSED \nDoor 34 is CLOSED \nDoor 35 is CLOSED \nDoor 36 is OPEN \nDoor 37 is CLOSED \nDoor 38 is CLOSED \nDoor 39 is CLOSED \nDoor 40 is CLOSED \nDoor 41 is CLOSED \nDoor 42 is CLOSED \nDoor 43 is CLOSED \nDoor 44 is CLOSED \nDoor 45 is CLOSED \nDoor 46 is CLOSED \nDoor 47 is CLOSED \nDoor 48 is CLOSED \nDoor 49 is OPEN \nDoor 50 is CLOSED \nDoor 51 is CLOSED \nDoor 52 is CLOSED \nDoor 53 is CLOSED \nDoor 54 is CLOSED \nDoor 55 is CLOSED \nDoor 56 is CLOSED \nDoor 57 is CLOSED \nDoor 58 is CLOSED \nDoor 59 is CLOSED \nDoor 60 is CLOSED \nDoor 61 is CLOSED \nDoor 62 is CLOSED \nDoor 63 is CLOSED \nDoor 64 is OPEN \nDoor 65 is CLOSED \nDoor 66 is CLOSED \nDoor 67 is CLOSED \nDoor 68 is CLOSED \nDoor 69 is CLOSED \nDoor 70 is CLOSED \nDoor 71 is CLOSED \nDoor 72 is CLOSED \nDoor 73 is CLOSED \nDoor 74 is CLOSED \nDoor 75 is CLOSED \nDoor 76 is CLOSED \nDoor 77 is CLOSED \nDoor 78 is CLOSED \nDoor 79 is CLOSED \nDoor 80 is CLOSED \nDoor 81 is OPEN \nDoor 82 is CLOSED \nDoor 83 is CLOSED \nDoor 84 is CLOSED \nDoor 85 is CLOSED \nDoor 86 is CLOSED \nDoor 87 is CLOSED \nDoor 88 is CLOSED \nDoor 89 is CLOSED \nDoor 90 is CLOSED \nDoor 91 is CLOSED \nDoor 92 is CLOSED \nDoor 93 is CLOSED \nDoor 94 is CLOSED \nDoor 95 is CLOSED \nDoor 96 is CLOSED \nDoor 97 is CLOSED \nDoor 98 is CLOSED \nDoor 99 is CLOSED \nDoor 100 is OPEN \n", "safe": true }, { "filename": "100_doors_678.txt", "content": "datatype Door = Closed | Opened\n\nfun toggle Closed = Opened\n | toggle Opened = Closed\n\nfun pass (step, doors) = List.map (fn (index, door) => if (index mod step) = 0\n\t\t\t\t\t\t then (index, toggle door)\n\t\t\t\t\t\t else (index, door))\n\t\t\t\t doors\n\n(* [1..n] *)\nfun runs n = List.tabulate (n, fn k => k+1)\n\nfun run n =\n let\n\tval initialdoors = List.tabulate (n, fn i => (i+1, Closed))\n\tval counter = runs n\n in\n\tfoldl pass initialdoors counter\n end\n\nfun opened_doors n = List.mapPartial (fn (index, Closed) => NONE\n\t\t\t\t | (index, Opened) => SOME (index))\n\t\t\t\t (run n)", "safe": true }, { "filename": "100_doors_679.txt", "content": "- opened_doors 100;\nval it = [1,4,9,16,25,36,49,64,81,100]\u00a0: int list\n", "safe": true }, { "filename": "100_doors_68.txt", "content": "#include \n$doors = 100\n\n;door array, 0 = closed, 1 = open\nLocal $door[$doors +1]\n\nFor $ii = 1 To $doors\n\tFor $i = $ii To $doors Step $ii\n\t\t$door[$i] = Not $door[$i]\n\tnext\nNext\n\n;display to screen\nFor $i = 1 To $doors\n\tConsoleWrite (Number($door[$i])& \" \")\n\tIf Mod($i,10) = 0 Then ConsoleWrite(@CRLF)\nNext\n", "safe": true }, { "filename": "100_doors_680.txt", "content": "clear\nset obs 100\ngen doors=0\ngen index=_n\nforvalues i=1/100 {\n\tquietly replace doors=!doors if mod(_n,`i')==0\n}\nlist index if doors, noobs noheader\n\n +-------+\n | 1 |\n | 4 |\n | 9 |\n | 16 |\n | 25 |\n |-------|\n | 36 |\n | 49 |\n | 64 |\n | 81 |\n | 100 |\n +-------+", "safe": true }, { "filename": "100_doors_681.txt", "content": "d \".\"\n#d\ni d\n#i\np \"door\" #i\n*p *p \".\"\ni d f \"oc\"\ni d #@f #*p\ni d .\\f \"o\" $ #i\ni i d\n#i +101 i \"\"\n#i\nd d \".\"\n#d +101 d \"\"\n#d", "safe": true }, { "filename": "100_doors_682.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100", "safe": true }, { "filename": "100_doors_683.txt", "content": "(\nvar n = 100, doors = false\u00a0! n;\nvar pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };\n(1..n-1).do(pass);\ndoors.selectIndices { |open| open }; // all are closed except [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ]\n)", "safe": true }, { "filename": "100_doors_684.txt", "content": "/* declare enum to identify the state of a door */\nenum DoorState\u00a0: String {\n case Opened = \"Opened\"\n case Closed = \"Closed\"\n}\n\n/* declare list of doors state and initialize them */\nvar doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)\n\n/* do the 100 passes */\nfor i in 1...100 {\n /* map on a strideTo instance to only visit the needed doors on each iteration */\n map(stride(from: i - 1, to: 100, by: i)) {\n doorsStateList[$0] = doorsStateList[$0] == .Opened\u00a0? .Closed\u00a0: .Opened\n }\n}\n\n/* print the results */\nfor (index, item) in enumerate(doorsStateList) {\n println(\"Door \\(index+1) is \\(item.rawValue)\")\n}", "safe": true }, { "filename": "100_doors_685.txt", "content": "/* declare enum to identify the state of a door */\nenum DoorState\u00a0: String {\n case Opened = \"Opened\"\n case Closed = \"Closed\"\n}\n\n/* declare list of doors state and initialize them */\nvar doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)\n\n/* set i^2 doors to opened */\nvar i = 1\ndo {\n doorsStateList[(i*i)-1] = DoorState.Opened\n ++i\n} while (i*i) <= doorsStateList.count\n\n/* print the results */\nfor (index, item) in enumerate(doorsStateList) {\n println(\"Door \\(index+1) is \\(item.rawValue)\")\n}", "safe": true }, { "filename": "100_doors_686.txt", "content": "var arr: [Bool] = Array(1...100).map{ remquo(exp(log(Float($0))/2.0),1).0 == 0 }", "safe": true }, { "filename": "100_doors_687.txt", "content": "source hundredDoors\n @: [ 1..100 -> 0 ];\n templates toggle\n def jump: $;\n $jump..100:$jump -> \\(\n when )> do @hundredDoors($): 1;\n otherwise @hundredDoors($): 0;\n \\) -> !VOID\n end toggle\n 1..100 -> toggle -> !VOID\n $@ -> \\[i](<=1> ' $i;'\u00a0!\\)\u00a0!\nend hundredDoors\n\n$hundredDoors -> 'Open doors:$...;' -> !OUT::write", "safe": true }, { "filename": "100_doors_688.txt", "content": "hundredDoors source\n @ set [ 1..100 -> 0 ];\n toggle templates\n jump is $;\n $jump..100:$jump -> templates\n when <|?($@hundredDoors($) matches <|=0>)> do @hundredDoors($) set 1;\n otherwise @hundredDoors($) set 0;\n end -> !VOID\n end toggle\n 1..100 -> toggle -> !VOID\n $@(.. as i; -> if <|=1> -> ' $i;')\u00a0!\nend hundredDoors\n\n$hundredDoors -> 'Open doors:$...;'\u00a0!", "safe": true }, { "filename": "100_doors_689.txt", "content": "Open doors: 1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_69.txt", "content": "BEGIN {\n for(i=1; i <= 100; i++)\n {\n doors[i] = 0 # close the doors\n }\n for(i=1; i <= 100; i++)\n {\n for(j=i; j <= 100; j += i)\n {\n doors[j] = (doors[j]+1) % 2\n }\n }\n for(i=1; i <= 100; i++)\n {\n print i, doors[i] ? \"open\" : \"close\"\n }\n}\n", "safe": true }, { "filename": "100_doors_690.txt", "content": "package require Tcl 8.5\nset n 100\nset doors [concat - [lrepeat $n 0]]\nfor {set step 1} {$step <= $n} {incr step} {\n for {set i $step} {$i <= $n} {incr i $step} {\n lset doors $i [expr {\u00a0! [lindex $doors $i]}]\n }\n}\nfor {set i 1} {$i <= $n} {incr i} {\n puts [format \"door %d is %s\" $i [expr {[lindex $doors $i]\u00a0? \"open\"\u00a0: \"closed\"}]]\n}", "safe": true }, { "filename": "100_doors_691.txt", "content": "package require Tcl 8.5\nset doors [lrepeat [expr {$n + 1}] closed]\nfor {set i 1} {$i <= sqrt($n)} {incr i} {\n lset doors [expr {$i ** 2}] open\n}\nfor {set i 1} {$i <= $n} {incr i} {\n puts [format \"door %d is %s\" $i [lindex $doors $i]]\n}", "safe": true }, { "filename": "100_doors_692.txt", "content": "package require Tcl 8.5\npackage require Tk\n\narray set door_status {}\n\n# create the gui\nset doors [list x]\nfor {set i 0} {$i < 10} {incr i} {\n for {set j 0} {$j < 10} {incr j} {\n set k [expr {1 + $j + 10*$i}]\n lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \\\n -indicatoron no -offrelief flat -width 3 -value open]\n grid [lindex $doors $k] -column $j -row $i\n }\n}\n\n# create the controls\nbutton .start -command go -text Start\nlabel .i_label -text \" door:\"\nentry .i -textvariable i -width 4\nlabel .step_label -text \" step:\"\nentry .step -textvariable step -width 4\ngrid .start - .i_label - .i - .step_label - .step - -row $i\ngrid configure .start -sticky ew\ngrid configure .i_label .step_label -sticky e\ngrid configure .i .step -sticky w\n\nproc go {} {\n global doors door_status i step\n\n # initialize the door_status (all closed)\n for {set d 1} {$d <= 100} {incr d} {\n set door_status($d) closed\n }\n \n # now, begin opening and closing\n for {set step 1} {$step <= 100} {incr step} {\n for {set i 1} {$i <= 100} {incr i} {\n if {$i\u00a0% $step == 0} {\n [lindex $doors $i] [expr {$door_status($i) eq \"open\"\u00a0? \"deselect\"\u00a0: \"select\"}]\n update\n after 50\n }\n }\n }\n}", "safe": true }, { "filename": "100_doors_693.txt", "content": "seq(0,X,1,100\nFor(X,1,100\n0 or Ans-not(fPart(cumSum(1 or Ans)/A\nEnd\nPause Ans\n", "safe": true }, { "filename": "100_doors_694.txt", "content": "Pause not(fPart(\u221a(seq(X,X,1,100\n", "safe": true }, { "filename": "100_doors_695.txt", "content": "Define doors(fast) = Func\n Local doors,i,j\n seq(false,x,1,100)\u00a0? doors\n If fast Then\n For i,1,10,1\n true\u00a0? doors[i^2]\n EndFor\n Else\n For i,1,100,1\n For j,i,100,i\n not doors[j]\u00a0? doors[j]\n EndFor\n EndFor\n EndIf\n Return doors\nEndFunc", "safe": true }, { "filename": "100_doors_696.txt", "content": "for(%steps = 1; %a <= 100; %a++)\n\tfor(%current = %steps; %current <= 100; %current += %steps)\n\t\t%door[%current] =\u00a0!%door[%current];\nfor(%a = 1; %a <= 100; %a++)\n\techo(\"Door #\" @ %a @ \" is\" SPC %door[%current]\u00a0? \"Open\"\u00a0: \"Closed\" @ \".\");", "safe": true }, { "filename": "100_doors_697.txt", "content": "WITH OneToTen (N)\nAS ( SELECT N\n FROM ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)\n ) V(N)\n )\n , InitDoors (Num, IsOpen)\nAS ( SELECT 1\n + 1 * Units.N\n + 10 * Tens.N As Num\n , Convert(Bit, 0) As IsOpen\n FROM OneToTen As Units\n CROSS JOIN OneToTen As Tens\n ) -- This part could be easier with a tally table or equivalent table-valued function\n , States (NbStep, Num, IsOpen)\nAS ( SELECT 0 As NbStep\n , Num\n , IsOpen\n FROM InitDoors As InitState\n UNION ALL\n SELECT 1 + NbStep\n , Num\n , CASE Num\u00a0% (1 + NbStep)\n WHEN 0 THEN ~IsOpen\n ELSE IsOpen\n END\n FROM States\n WHERE NbStep < 100\n )\nSELECT Num As DoorNumber\n , Concat( 'Door number ', Num, ' is '\n , CASE IsOpen\n WHEN 1 THEN ' open'\n ELSE ' closed'\n END ) As Result -- Concat needs SQL Server 2012\nFROM States\nWHERE NbStep = 100\nORDER By Num\n; -- Fortunately, maximum recursion is 100 in SQL Server.\n-- For more doors, the MAXRECURSION hint should be used.\n-- More doors would also need an InitDoors with more rows.", "safe": true }, { "filename": "100_doors_698.txt", "content": "SET NOCOUNT ON;\n\n-- Doors can be open or closed.\nDECLARE @open CHAR(1) = 'O';\nDECLARE @closed CHAR(1) = 'C';\n\n-- There are 100 doors in a row that are all initially closed.\nDECLARE @doorsCount INT = 100;\nDECLARE @doors TABLE (doorKey INT PRIMARY KEY, doorState CHAR(1));\nWITH sample100 AS (\n SELECT TOP(100) object_id\n FROM sys.objects\n)\nINSERT @doors\n SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS doorKey,\n @closed AS doorState\n FROM sample100 AS A\n CROSS JOIN sample100 AS B\n CROSS JOIN sample100 AS C\n CROSS JOIN sample100 AS D\n ORDER BY 1\n OFFSET 0 ROWS\n FETCH NEXT @doorsCount ROWS ONLY;\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.\nDECLARE @pass INT = 1;\nWHILE @pass <= @doorsCount BEGIN\n UPDATE @doors\n SET doorState = CASE doorState WHEN @open THEN @closed ELSE @open END\n WHERE doorKey >= @pass\n AND doorKey\u00a0% @pass = 0;\n\n SET @pass = @pass + 1;\nEND;\n\n-- Answer the question: what state are the doors in after the last pass?\n-- The answer as the query result is:\nSELECT doorKey, doorState FROM @doors;\n-- The answer as the console output is:\nDECLARE @log VARCHAR(max);\nDECLARE @doorKey INT = (SELECT MIN(doorKey) FROM @doors);\nWHILE @doorKey <= @doorsCount BEGIN\n SET @log = (\n SELECT TOP(1) CONCAT('Doors ', doorKey, ' are ',\n CASE doorState WHEN @open THEN ' open' ELSE 'closed' END, '.')\n FROM @doors\n WHERE doorKey = @doorKey\n );\n RAISERROR (@log, 0, 1) WITH NOWAIT;\n\n SET @doorKey = (SELECT MIN(doorKey) FROM @doors WHERE doorKey > @doorKey);\nEND;\n\n-- Which are open, which are closed?\n-- The answer as the query result is:\nSELECT doorKey, doorState FROM @doors WHERE doorState = @open;\nSELECT doorKey, doorState FROM @doors WHERE doorState = @closed;\n-- The answer as the console output is:\nSET @log = (\n SELECT CONCAT('These are open doors: ',\n STRING_AGG(CAST(doorKey AS VARCHAR(max)), ', '), '.')\n FROM @doors\n WHERE doorState = @open\n);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = (\n SELECT CONCAT('These are closed doors: ',\n STRING_AGG(CAST(doorKey AS VARCHAR(max)), ', '), '.')\n FROM @doors\n WHERE doorState = @closed\n);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\n\n-- Assert:\nDECLARE @expected TABLE (doorKey INT PRIMARY KEY);\nSET @doorKey = 1;\nWHILE @doorKey * @doorKey <= @doorsCount BEGIN\n INSERT @expected VALUES (@doorKey * @doorKey);\n SET @doorKey = @doorKey + 1;\nEND;\nIF NOT EXISTS (\n SELECT doorKey FROM @doors WHERE doorState = @open\n EXCEPT\n SELECT doorKey FROM @expected\n )\n AND NOT EXISTS (\n SELECT doorKey FROM @expected\n EXCEPT\n SELECT doorKey FROM @doors WHERE doorState = @open\n )\n PRINT 'The task is solved.';\nELSE\n THROW 50000, 'These aren''t the doors you''re looking for.', 1;", "safe": true }, { "filename": "100_doors_699.txt", "content": "#lang transd\n\nMainModule: {\n doors: Vector(100),\n _start: (\u03bb \n (for i in Seq(100) do\n (for k in Seq(i 100 (+ i 1)) do\n (set-el doors k (not (get doors k)))\n ))\n\n (for i in Seq(100) do\n (if (get doors i) (textout (+ i 1) \" \"))\n ))\n}", "safe": true }, { "filename": "100_doors_7.txt", "content": "\n \n \n \n \n \n \n n\n \n 2\n \n \n =\n 1\n +\n 3\n +\n 5\n +\n \u2026\n +\n (\n 2\n n\n \u2212\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle n^{2}=1+3+5+\\ldots +(2n-1)}}\n \n.\n", "safe": true }, { "filename": "100_doors_70.txt", "content": "BEGIN {\n for(i=1; i <= 100; i++) {\n doors[i] = 0 # close the doors\n }\n for(i=1; i <= 100; i++) {\n if ( int(sqrt(i)) == sqrt(i) ) {\n doors[i] = 1\n }\n }\n for(i=1; i <= 100; i++)\n {\n print i, doors[i] ? \"open\" : \"close\"\n }\n}\n", "safe": true }, { "filename": "100_doors_700.txt", "content": "1 4 9 16 25 36 49 64 81 100\n", "safe": true }, { "filename": "100_doors_701.txt", "content": "! Optimized solution with True BASIC\n\nOPTION NOLET\nx = 1 \ny = 3 \nz = 0\nPRINT STR$(x) & \" Open\"\nDO UNTIL z >= 100\nz = x + y\nPRINT STR$(z) & \" Open\"\nx = z \ny = y + 2\nLOOP\n\nEND", "safe": true }, { "filename": "100_doors_702.txt", "content": "// library: math: get: task: door: open: close100 1.0.0.0.11 (filenamemacro=getmaocl.s) [] [] [kn, ri, mo, 31-12-2012 22:03:16]\nPROC PROCMathGetTaskDoorOpenClose( INTEGER doorMaxI, INTEGER passMaxI )\n // e.g. PROC Main()\n // e.g. PROCMathGetTaskDoorOpenClose( 100, 100 )\n // e.g. END\n // e.g.\n // e.g. Main()\n //\n // ===\n //\n // The output will be:\n //\n // door 1 is open\n // door 4 is open\n // door 9 is open\n // door 16 is open\n // door 25 is open\n // door 36 is open\n // door 49 is open\n // door 64 is open\n // door 81 is open\n // door 100 is open\n // all other doors are closed\n //\n // ===\n //\n INTEGER passMinI = 1\n INTEGER passI = 0\n //\n INTEGER doorminI = 1\n INTEGER doorI = 0\n //\n STRING s[255] = \"\"\n //\n INTEGER bufferI = 0\n //\n PushPosition()\n bufferI = CreateTempBuffer()\n PopPosition()\n //\n FOR doorI = doorMinI TO doorMaxI\n //\n SetGlobalInt( Format( \"doorsI\", doorI ), 0 )\n //\n ENDFOR\n //\n FOR passI = passMinI TO passMaxI\n //\n doorI = passI - passI\n //\n REPEAT\n //\n doorI = doorI + passI\n //\n SetGlobalInt( Format( \"doorsI\", doorI ), NOT( GetGlobalInt( Format( \"doorsI\", doorI ) ) ) )\n //\n UNTIL ( doorI >= doorMaxI )\n //\n ENDFOR\n //\n FOR doorI = doorMinI TO doorMaxI\n //\n IF ( GetGlobalInt( Format( \"doorsI\", doorI ) ) > 0 )\n //\n s = \"open\"\n //\n AddLine( Format( \"door\", \" \", doorI, \" \", \"is\", \" \", s ), bufferI )\n //\n ELSE\n //\n s = \"closed\"\n //\n ENDIF\n //\n ENDFOR\n //\n AddLine( \"all other doors are closed\", bufferI )\n //\n GotoBufferId( bufferI )\n //\nEND\n\nPROC Main()\n PROCMathGetTaskDoorOpenClose( 100, 100 )\nEND", "safe": true }, { "filename": "100_doors_703.txt", "content": "$$ MODE TUSCRIPT\nDICT doors create\nCOMPILE\nLOOP door=1,100\n LOOP pass=1,100\n SET go=MOD (door,pass)\n DICT doors lookup door,num,cnt,status\n IF (num==0) THEN\n SET status=\"open\"\n DICT doors add door,num,cnt,status\n ELSE\n IF (go==0) THEN\n IF (status==\"closed\") THEN\n SET status=\"open\"\n ELSE\n SET status=\"closed\"\n ENDIF\n DICT doors update door,num,cnt,status\n ENDIF\n ENDIF\n ENDLOOP\nENDLOOP\nENDCOMPILE\nDICT doors unload door,num,cnt,status", "safe": true }, { "filename": "100_doors_704.txt", "content": " status = *\n 1 = open\n 2 = closed\n 3 = closed\n 4 = open\n 5 = closed\n 6 = closed\n 7 = closed\n 8 = closed\n 9 = open\n 10 = closed\n 11 = closed\n 12 = closed\n 13 = closed\n 14 = closed\n 15 = closed\n 16 = open\n 17 = closed\n 18 = closed\n 19 = closed\n 20 = closed\n 21 = closed\n 22 = closed\n 23 = closed\n 24 = closed\n 25 = open\n 26 = closed\n 27 = closed\n 28 = closed\n 29 = closed\n 30 = closed\n 31 = closed\n 32 = closed\n 33 = closed\n 34 = closed\n 35 = closed\n 36 = open\n 37 = closed\n 38 = closed\n 39 = closed\n 40 = closed\n 41 = closed\n 42 = closed\n 43 = closed\n 44 = closed\n 45 = closed\n 46 = closed\n 47 = closed\n 48 = closed\n 49 = open\n 50 = closed\n 51 = closed\n 52 = closed\n 53 = closed\n 54 = closed\n 55 = closed\n 56 = closed\n 57 = closed\n 58 = closed\n 59 = closed\n 60 = closed\n 61 = closed\n 62 = closed\n 63 = closed\n 64 = open\n 65 = closed\n 66 = closed\n 67 = closed\n 68 = closed\n 69 = closed\n 70 = closed\n 71 = closed\n 72 = closed\n 73 = closed\n 74 = closed\n 75 = closed\n 76 = closed\n 77 = closed\n 78 = closed\n 79 = closed\n 80 = closed\n 81 = open\n 82 = closed\n 83 = closed\n 84 = closed\n 85 = closed\n 86 = closed\n 87 = closed\n 88 = closed\n 89 = closed\n 90 = closed\n 91 = closed\n 92 = closed\n 93 = closed\n 94 = closed\n 95 = closed\n 96 = closed\n 97 = closed\n 98 = closed\n 99 = closed\n 100 = open\n", "safe": true }, { "filename": "100_doors_705.txt", "content": "interface Door {\n id: number;\n open: boolean;\n}\n\nfunction doors(): Door[] {\n var Doors: Door[] = [];\n\n for (let i = 1; i <= 100; i++) {\n Doors.push({id: i, open: false});\n }\n\n for (let secuence of Doors) {\n for (let door of Doors) {\n if (door.id\u00a0% secuence.id == 0) {\n door.open = !door.open;\n }\n }\n }\n\n return Doors.filter(a => a.open);\n}", "safe": true }, { "filename": "100_doors_706.txt", "content": "(defun hyaku-mai-tobira ()\n (let ((doors (vector 100)))\n (each ((i (range 0 99)))\n (each ((j (range i 99 (+ i 1))))\n (flip [doors j])))\n doors))\n\n(each ((counter (range 1))\n (door (hyaku-mai-tobira)))\n (put-line `door @counter is @(if door \"open\" \"closed\")`))", "safe": true }, { "filename": "100_doors_707.txt", "content": "FOR p = 1 TO 100\n FOR d = p TO 100 STEP p\n @(d) = @(d) = 0\n NEXT d\nNEXT p\n\nFOR d= 1 TO 100\n IF @(d) PRINT \"Door \";d;\" is open\"\nNEXT d", "safe": true }, { "filename": "100_doors_708.txt", "content": "\u25ff2/+=0\u229e\u25ff.+1\u21e1100\n +1\u21e1100 # 1-100\n \u229e\u25ff. # Mod each with 1-100\n =0 # Find where mod = 0, aka the divisors\n /+ # Sum to get num of divisors\n\u25ff2 # Num divisors is odd\n", "safe": true }, { "filename": "100_doors_709.txt", "content": "[1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]", "safe": true }, { "filename": "100_doors_71.txt", "content": "(open,closed,change,open?)\u00a0:= (true,false,not,test);\ndoors\u00a0:= bits(100,closed);\nfor i in 1..#doors repeat\n for j in i..#doors by i repeat\n doors.j\u00a0:= change doors.j\n[i for i in 1..#doors | open? doors.i]", "safe": true }, { "filename": "100_doors_710.txt", "content": "entry LP_DO_IT\n\n variables\n string V_DOORS\n boolean V_DOOR_STATE\n string V_DOOR_STATE_S\n numeric V_IDX\n numeric V_TOTAL_DOORS\n string V_DOOR_STATE_LIST\n numeric V_LOOP_COUNT\n endvariables\n\n V_TOTAL_DOORS = 100\n putitem V_DOORS, V_TOTAL_DOORS, 0\n\n V_DOORS = $replace (V_DOORS, 1, \"\u00b7;\", \"\u00b7;0\", -1)\n\n putitem/id V_DOOR_STATE_LIST, \"1\", \"Open\"\n putitem/id V_DOOR_STATE_LIST, \"0\", \"Close\"\n\n V_LOOP_COUNT = 1\n while (V_LOOP_COUNT <= V_TOTAL_DOORS)\n V_IDX = 0\n V_IDX = V_IDX + V_LOOP_COUNT\n\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n while (V_IDX <= V_TOTAL_DOORS)\n\n V_DOOR_STATE = !V_DOOR_STATE\n getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)\n putitem V_DOORS, V_IDX, V_DOOR_STATE\n\n V_IDX = V_IDX + V_LOOP_COUNT\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n endwhile\n\n V_LOOP_COUNT = V_LOOP_COUNT + 1\n\n endwhile\n\n V_IDX = 1\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n while (V_IDX <= V_TOTAL_DOORS)\n getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)\n if (V_DOOR_STATE)\n putmess \"Door\u00a0%%V_IDX%%% is finally\u00a0%%V_DOOR_STATE_S%%%\"\n endif\n\n V_IDX = V_IDX + 1\n getitem V_DOOR_STATE, V_DOORS, V_IDX\n endwhile\n\nend\u00a0; LP_DO_IT", "safe": true }, { "filename": "100_doors_711.txt", "content": "\n\nDoor 1 is finally Open\nDoor 4 is finally Open\nDoor 9 is finally Open\nDoor 16 is finally Open\nDoor 25 is finally Open\nDoor 36 is finally Open\nDoor 49 is finally Open\nDoor 64 is finally Open\nDoor 81 is finally Open\nDoor 100 is finally Open\n\n", "safe": true }, { "filename": "100_doors_712.txt", "content": "hundredDoors\u00a0: [Boolean]\nhundredDoors =\n toggleEachNth\u00a0: Nat -> [Boolean] -> [Boolean]\n toggleEachNth n doors =\n go counter = cases\n [] -> []\n (d +: ds) -> if counter == n\n then (not d) +: go 1 ds\n else d +: go (counter+1) ds\n\n go 1 doors\n\n foldr toggleEachNth (replicate 100 'false) (range 1 101)\n\nresults = filterMap (cases (open, ix) -> if open then Some (ix+1) else None)\n (indexed hundredDoors)", "safe": true }, { "filename": "100_doors_713.txt", "content": "#! /bin/bash\n\ndeclare -a doors\nfor((i=1; i <= 100; i++)); do\n doors[$i]=0\ndone\n\nfor((i=1; i <= 100; i++)); do\n for((j=i; j <= 100; j += i)); do\n\techo $i $j\n\tdoors[$j]=$(( doors[j] ^ 1 ))\n done\ndone\n\nfor((i=1; i <= 100; i++)); do\n if [[ ${doors[$i]} -eq 0 ]]; then\n\top=\"closed\"\n else\n\top=\"open\"\n fi\n echo $i $op\ndone", "safe": true }, { "filename": "100_doors_714.txt", "content": "#!/bin/bash\n\nfor i in {1..100}; do\n door[$i*$i]=1\n [ -z ${door[$i]} ] && echo \"$i closed\" || echo \"$i open\"\ndone", "safe": true }, { "filename": "100_doors_715.txt", "content": "#\n# 100 doors\n#\n\ndecl int i j\ndecl boolean<> doors\n\n# append 101 boolean values to doors stream\nfor (set i 0) (or (< i 100) (= i 100)) (inc i)\n append false doors\nend for\n\n# loop through, opening and closing doors\nfor (set i 1) (or (< i 100) (= i 100)) (inc i)\n for (set j i) (or (< j 100) (= j 100)) (inc j)\n if (= (mod j i) 0)\n set doors (not doors)\n end if\n end for\nend for\n\n# loop through and output which doors are open\nfor (set i 1) (or (< i 100) (= i 100)) (inc i)\n out \"Door \" i \": \" console\n if doors\n out \"open\" endl console\n else\n out \"closed\" endl console\n end if\nend if", "safe": true }, { "filename": "100_doors_716.txt", "content": "#import std\n#import nat\n\ndoors = 0!* iota 100\n\npass(\"n\",\"d\") = remainder\\\"n\"?l(~&r,not ~&r)* num \"d\"\n\n#cast %nL\n\nmain = ~&rFlS num pass=>doors nrange(100,1)", "safe": true }, { "filename": "100_doors_717.txt", "content": "#import nat\n\n#cast %nL\n\nmain = product*tiiXS iota10", "safe": true }, { "filename": "100_doors_718.txt", "content": "<1,4,9,16,25,36,49,64,81>\n", "safe": true }, { "filename": "100_doors_719.txt", "content": "\u00b7\u00b7\u00b7\nhttp://rosettacode.org/wiki/100_doors\n\u00b7\u00b7\u00b7\n\u25a0 HundredDoors \n \u00a7 static\n \u25b6 main\n \u2022 args\u2982 String[]\n open\u2982 boolean: true\n closed\u2982 boolean: false\n doors\u2982 boolean[1+100] \u00b7 all initially closed\n \ud83d\udd01 pass from 1 to 100\n \u2200 visited \u2208 pass\u2025100 by pass\n \u00b7 toggle the visited doors\n if the doors[visited] are closed\n let the doors[visited] be open\n else\n let the doors[visited] be closed\n for each door #n in doors\u2982 boolean\n if the door is open\n System.out.println \"Door #\u2e28n\u2e29 is open.\"", "safe": true }, { "filename": "100_doors_72.txt", "content": "[i for i in 1..100 | perfectSquare? i] -- or\n[i^2 for i in 1..sqrt(100)::Integer]", "safe": true }, { "filename": "100_doors_720.txt", "content": "int main() {\n\tbool doors_open[101];\n\tfor(int i = 1; i < doors_open.length; i++) {\n\t\tfor(int j = 1; i*j < doors_open.length; j++) {\n\t\t\tdoors_open[i*j] = !doors_open[i*j];\n\t\t}\n\t\tstdout.printf(\"%d: %s\\n\", i, (doors_open[i]\u00a0? \"open\"\u00a0: \"closed\"));\n\t}\n\treturn 0;\n}", "safe": true }, { "filename": "100_doors_721.txt", "content": "1: open\n2: closed\n3: closed\n4: open\n5: closed\n6: closed\n7: closed\n8: closed\n9: open\n10: closed\n11: closed\n...", "safe": true }, { "filename": "100_doors_722.txt", "content": "int main() {\n\tint i = 1;\n\twhile(i*i <= 100) {\n\t\tstdout.printf(\"${i*i} open\\n\");\n\t\ti++;\n\t}\n\treturn 0;\n}", "safe": true }, { "filename": "100_doors_723.txt", "content": "1 open\n4 open\n9 open\n16 open\n25 open\n36 open\n49 open\n64 open\n81 open\n100 open", "safe": true }, { "filename": "100_doors_724.txt", "content": " 00000064 0000 1 n = 100\n 0000 0000 2 .entry\tdoors, ^m<>\n 26'AF 9F 0002 3 \tpushab\tb^arr\t\t\t\t; offset signed byte\n 50 64 8F 9A 0005 4 \tmovzbl\t#n, r0\n 50 DD 0009 5 \tpushl\tr0\t\t\t\t; (sp) -> .ascid arr\n 000B 6 10$:\n 51 50 D0 000B 7 \tmovl\tr0, r1\t\t\t\t; step = start index\n 000E 8 20$:\n 25'AF41 01 8C 000E 9 \txorb2\t#^a\"0\" \\^a\"1\", b^arr-1[r1]\t; \\ xor toggle \"1\"<->\"0\"\n FFF5 51 50 6E F1 0013 10 \tacbl\t(sp), r0, r1, 20$\t\t; limit, step, index\n EF 50 F5 0019 11 \tsobgtr\tr0, 10$\t\t\t\t; n..1\n 001C 12 \n 5E DD 001C 13 \tpushl\tsp\t\t\t\t; descriptor by reference\n 00000000'GF 01 FB 001E 14 \tcalls\t#1, g^lib$put_output\t\t; show result\n 04 0025 15 \tret\n 0026 16 \n30'30'30'30'30'30'30'30'30'30'30'30' 0026 17 arr:\t.byte\t^a\"0\"[n]\n30'30'30'30'30'30'30'30'30'30'30'30' 0032 \n30'30'30'30'30'30'30'30'30'30'30'30' 003E \n30'30'30'30'30'30'30'30'30'30'30'30' 004A \n30'30'30'30'30'30'30'30'30'30'30'30' 0056 \n30'30'30'30'30'30'30'30'30'30'30'30' 0062 \n30'30'30'30'30'30'30'30'30'30'30'30' 006E \n30'30'30'30'30'30'30'30'30'30'30'30' 007A \n 30'30'30'30' 0086 \n 008A 18 .end\tdoors\n$ run doors\n1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001", "safe": true }, { "filename": "100_doors_725.txt", "content": "Sub Rosetta_100Doors()\nDim Door(100) As Boolean, i As Integer, j As Integer\nFor i = 1 To 100 Step 1\n For j = i To 100 Step i\n Door(j) = Not Door(j)\n Next j\n If Door(i) = True Then\n Debug.Print \"Door \" & i & \" is Open\"\n Else\n Debug.Print \"Door \" & i & \" is Closed\"\n End If\nNext i\nEnd Sub\n\n\n*** USE THIS ONE, SEE COMMENTED LINES, DONT KNOW WHY EVERYBODY FOLLOWED OTHERS ANSWERS AND CODED THE PROBLEM DIFFERENTLY ***\n*** ALWAYS USE AND TEST A READABLE, EASY TO COMPREHEND CODING BEFORE 'OPTIMIZING' YOUR CODE AND TEST THE 'OPTIMIZED' CODE AGAINST THE 'READABLE' ONE.\nPanikkos Savvides.\n\n\nSub Rosetta_100Doors2()\nDim Door(100) As Boolean, i As Integer, j As Integer\nDim strAns As String\n' There are 100 doors in a row that are all initially closed.\n' You make 100 passes by the doors.\nFor j = 1 To 100\n ' The first time through, visit every door and toggle the door\n ' (if the door is closed, open it; if it is open, close it).\n For i = 1 To 100 Step 1\n Door(i) = Not Door(i)\n Next i\n ' The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.\n For i = 2 To 100 Step 2\n Door(i) = Not Door(i)\n Next i\n ' The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n For i = 3 To 100 Step 3\n Door(i) = Not Door(i)\n Next i\nNext j\n\nFor j = 1 To 100\n If Door(j) = True Then\n strAns = j & strAns & \", \"\n End If\nNext j\n\nIf Right(strAns, 2) = \", \" Then strAns = Left(strAns, Len(strAns) - 2)\nIf Len(strAns) = 0 Then strAns = \"0\"\nDebug.Print \"Doors [\" & strAns & \"] are open, the rest are closed.\"\n' Doors [0] are open, the rest are closed., AKA ZERO DOORS OPEN\nEnd Sub", "safe": true }, { "filename": "100_doors_726.txt", "content": "Dim doorIsOpen(100), pass, currentDoor, text\n\nFor currentDoor = 0 To 99\n\tdoorIsOpen(currentDoor) = False\nNext\n\nFor pass = 0 To 99\n\tFor currentDoor = pass To 99 Step pass + 1\n\t\tdoorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)\n\tNext\nNext\n\nFor currentDoor = 0 To 99\n\ttext = \"Door #\" & currentDoor + 1 & \" is \"\n\tIf doorIsOpen(currentDoor) Then\n\t\ttext = text & \"open.\"\n\tElse\n\t\ttext = text & \"closed.\"\n\tEnd If\n\tWScript.Echo(text)\nNext", "safe": true }, { "filename": "100_doors_727.txt", "content": "Buf_Switch(Buf_Free)\nIns_Char('-', COUNT, 100) // All doors closed\nfor (#1 = 1; #1 <= 100; #1++) {\n for (#2 = #1; #2 <= 100; #2 += #1) {\n Goto_Col(#2)\n Ins_Char((Cur_Char^0x62), OVERWRITE) // Toggle between '-' and 'O'\n }\n}", "safe": true }, { "filename": "100_doors_728.txt", "content": "Buf_Switch(Buf_Free)\nIns_Char('-', COUNT, 100)\nfor (#1=1; #1 <= 10; #1++) {\n Goto_Col(#1*#1)\n Ins_Char('O', OVERWRITE)\n}", "safe": true }, { "filename": "100_doors_729.txt", "content": "O--O----O------O--------O----------O------------O--------------O----------------O------------------O\n", "safe": true }, { "filename": "100_doors_73.txt", "content": "main()\n{\n auto doors[100]; /*\u00a0!= 0 means open */\n auto pass, door;\n\n door = 0;\n while( door<100 ) doors[door++] = 0;\n\n pass = 0;\n while( pass<100 )\n {\n door = pass;\n while( door<100 )\n {\n doors[door] = !doors[door];\n door =+ pass+1;\n }\n ++pass;\n }\n\n door = 0;\n while( door<100 )\n {\n printf(\"door #%d is %s.*n\", door+1, doors[door]\u00a0? \"open\"\u00a0: \"closed\");\n ++door;\n }\n\n return(0);\n}", "safe": true }, { "filename": "100_doors_730.txt", "content": "module main;\n integer i;\n \n initial begin\n $display(\"Las siguientes puertas est\u00e1n abiertas:\");\n for (i=1; i<=10; i=i+1) if (i%i*i<11) $display(i*i);\n $finish\u00a0;\n end\nendmodule", "safe": true }, { "filename": "100_doors_731.txt", "content": "library IEEE;\nuse IEEE.STD_LOGIC_1164.ALL;\n\nentity DOORS is\n\tport (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100));\nend DOORS;\n\narchitecture Behavioral of DOORS is\nbegin\n\tprocess (CLK)\n\tvariable TEMP: std_logic_vector(1 to 100);\n\tbegin\n\t\t--setup closed doors\n\t\tTEMP\u00a0:= (others => '0');\n\t\t\n\t\t--looping through\n\t\tfor i in 1 to TEMP'length loop\n\t\t\tfor j in i to TEMP'length loop\n\t\t\t\tif (j mod i) = 0 then\n\t\t\t\t\tTEMP(j)\u00a0:= not TEMP(j);\n\t\t\t\tend if;\n\t\t\tend loop;\n\t\tend loop;\n\t\t\n\t\t--assign output\n\t\tOUTPUT <= TEMP;\n\tend process;\nend Behavioral;", "safe": true }, { "filename": "100_doors_732.txt", "content": "LIBRARY ieee;\nUSE ieee.std_logic_1164.all;\n\n\nentity doors is\n port (\n clk \u00a0: in std_logic;\n reset\u00a0: in std_logic;\n door \u00a0: buffer std_logic_vector(1 to 100)\n );\nend entity doors;\n\n\narchitecture rtl of doors is\n signal step\u00a0: integer range 1 to 101;\n signal addr\u00a0: integer range 1 to 201;\nbegin\n proc_step: process(clk, reset)\n begin\n if reset = '1' then\n step <= 1;\n addr <= 1;\n door <= (others => '0');\n elsif rising_edge(clk) then\n if addr <= 100 then\n door(addr) <= not door(addr);\n addr <= addr + step;\n elsif step <= 100 then\n addr <= step + 1;\n step <= step + 1;\n end if;\n end if;\n end process;\nend;", "safe": true }, { "filename": "100_doors_733.txt", "content": "Public Sub Doors100()\n ' the state of a door is represented by the data type boolean (false = door closed, true = door opened)\n Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false'\n Dim i As Long, j As Long\n \n For i = 1 To 100\n For j = i To 100 Step i\n doorstate(j) = Not doorstate(j)\n Next j\n Next i\n \n Debug.Print \"The following doors are open:\"\n For i = 1 To 100\n ' print number if door is openend\n If doorstate(i) Then Debug.Print CStr(i)\n Next i\nEnd Sub", "safe": true }, { "filename": "100_doors_734.txt", "content": "The following doors are open:\n1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100_doors_735.txt", "content": "Module Module1\n\n Sub Main()\n Dim doors(100) As Boolean 'Door 1 is at index 0\n\n For pass = 1 To 100\n For door = pass - 1 To 99 Step pass\n doors(door) = Not doors(door)\n Next\n Next\n\n For door = 0 To 99\n Console.WriteLine(\"Door # \" & (door + 1) & \" is \" & If(doors(door), \"Open\", \"Closed\"))\n Next\n\n Console.ReadLine()\n End Sub\n\nEnd Module", "safe": true }, { "filename": "100_doors_736.txt", "content": "Module Module1\n\n Sub Main()\n Dim doors(100) As Boolean 'Door 1 is at index 0\n\n For i = 1 To 10\n doors(i ^ 2 - 1) = True\n Next\n\n For door = 0 To 99\n Console.WriteLine(\"Door # \" & (door + 1) & \" is \" & If(doors(door), \"Open\", \"Closed\"))\n Next\n\n Console.ReadLine()\n End Sub\n\nEnd Module", "safe": true }, { "filename": "100_doors_737.txt", "content": "const number_doors = 101\n\nfn main() {\n mut closed_doors\u00a0:= []bool{len: number_doors, init: true} \n for pass in 0..number_doors {\n for door\u00a0:= 0; door < number_doors; door += pass + 1 {\n closed_doors[door] = !closed_doors[door]\n }\n }\n for pass in 1..number_doors {\n if !closed_doors[pass] {\n println('Door #$pass Open')\n }\n }\n}", "safe": true }, { "filename": "100_doors_738.txt", "content": "Door #1 Open\nDoor #4 Open\nDoor #9 Open\nDoor #16 Open\nDoor #25 Open\nDoor #36 Open\nDoor #49 Open\nDoor #64 Open\nDoor #81 Open\nDoor #100 Open\n", "safe": true }, { "filename": "100_doors_739.txt", "content": "const door_number = 100\n\nfn main(){\n mut doors\u00a0:= []bool{ len: door_number, init: false } //true open false closed\n\n mut door_nbr\u00a0:= 1\n mut increment\u00a0:= 0\n\n for current in 1..( door_number + 1) {\n if current == door_nbr {\n doors[current - 1] = true\n increment++\n door_nbr += 2 * increment + 1\n\t\t\tprint('O')\n\t\t} else {\n\t\t\tprint('=')\n\t\t}\n }\n println('')\n}", "safe": true }, { "filename": "100_doors_74.txt", "content": " * NB: the implementation is rather vanilla\n * besides using the idiomatic buffer overrun.\n * LOOP is what PERFORM in COBOL is, with defaults.\n * MOVE in this language acts like OVE CORRESPONDING,\n * which is actually good here.\n IDENTIFICATION DIVISION.\n PROGRAM-ID. ONE HUNDRED DOORS.\n DATA DIVISION.\n 01 I PICTURE IS 9(3).\n 01 J LIKE I.\n 01 DOOR PICTURE IS 9 OCCURS 100 TIMES.\n 01 STOP LIKE DOOR.\n PROCEDURE DIVISION.\n * Initialise the data\n MOVE HIGH-VALUES TO STOP\n MOVE SPACES TO DOOR.\n * Do the main algorithm\n LOOP VARYING I UNTIL DOOR(I) = 9\n LOOP VARYING J FROM I TO 100 BY I\n SUBTRACT DOOR (J) FROM 1 GIVING DOOR (J)\n END\n END.\n * Print the results\n LOOP VARYING I UNTIL DOOR(I) = 9\n DISPLAY \"Door\" I \"is\" WITH NO ADVANCING\n IF DOOR (I) = 1\n THEN DISPLAY \"open\"\n ELSE DISPLAY \"closed\".\n END.\n", "safe": true }, { "filename": "100_doors_740.txt", "content": "O==O====O======O========O==========O============O==============O================O==================O\n", "safe": true }, { "filename": "100_doors_741.txt", "content": "fn main() {\n\tfor i in 1..11 {\n\t\tprint ( \" Door ${i*i} is open.\\n\" )\n\t}\n}", "safe": true }, { "filename": "100_doors_742.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.\n", "safe": true }, { "filename": "100_doors_743.txt", "content": "10 D=1\n20 :D)=0\n30 D=D+1\n40 #=100>D*20\n50 P=1\n60 D=P\n70 :D)=:D)=0\n80 D=D+P\n90 #=100>D*70\n100 P=P+1\n110 #=100>P*60\n120 D=1\n130 #=:D)*170\n140 D=D+1\n150 #=100>D*130\n160 #=999\n170\u00a0?=\"DOOR \";\n180\u00a0?=D\n190\u00a0?=\" IS OPEN\"\n200 #=!", "safe": true }, { "filename": "100_doors_744.txt", "content": "DOOR 1 IS OPEN\nDOOR 4 IS OPEN\nDOOR 9 IS OPEN\nDOOR 16 IS OPEN\nDOOR 25 IS OPEN\nDOOR 36 IS OPEN\nDOOR 49 IS OPEN\nDOOR 64 IS OPEN\nDOOR 81 IS OPEN\nDOOR 100 IS OPEN", "safe": true }, { "filename": "100_doors_745.txt", "content": "def (doors n)\n let door (table)\n for step 1 (step <= n) ++step\n for j 0 (j < n) (j <- j+step)\n zap! not door.j\n\n for j 0 (j < n) ++j\n when door.j\n pr j\n pr \" \"", "safe": true }, { "filename": "100_doors_746.txt", "content": "let a => import 'arrays';\nlet s => import 'stream';\nlet io => import 'io';\n\nlet toggle doors m =>\n\ta.stream doors\n\t-> s.enumerate\n\t-> s.map (@ s n => [+ (a.at n 0) 1; a.at n 1])\n\t-> s.map (@ s n => switch n {\n\t\t\t(@ s n => == (% (a.at n 0) m) 0) =>\u00a0! (a.at n 1);\n\t\t\ttrue => a.at n 1;\n\t\t})\n\t-> s.collect\n\t;\n\ns.range 100\n-> s.map false\n-> s.collect\u00a0: doors\n-> s.range 1 100\n-> s.reduce doors toggle\n-> a.stream\n-> s.map (@ s n => switch 0 {\n\t\tn => 'Open';\n\t\ttrue => 'Closed';\n\t} -- io.writeln io.stdout)\n-> s.drain\n;", "safe": true }, { "filename": "100_doors_747.txt", "content": "; unoptimized\n+^[\n @var doors []\n \n @for i rangei [1 100]\n @for j rangei [i 100 i]\n \u00a0:!@not `j doors\n \n @for i rangei [1 100]\n @if `i doors\n !console.log \"door {i} is open\"\n]\n; optimized, map square over 1 to 10\n!*^@sq @to 10", "safe": true }, { "filename": "100_doors_748.txt", "content": "MOD Doors;\n\nIMP Agg.Table;\nIMP Std.String;\nIMP IO.Terminal USE Out;\n\nVAR door <- {}; EVERY door[1:to(100), \"closed\"];\n\nDEF toggle(num) door[num] <- door[num] = \"open\" => \"closed\" // \"open\";\n\nEVERY WITH pass <- 1:to(100), num <- pass:to(100, pass) DO toggle(num);\n\nOut:write('Doors {door @ String.T}.');\n\nEND Doors.", "safe": true }, { "filename": "100_doors_749.txt", "content": "MOD Doors;\n\nIMP IO.Terminal USE Out;\n\nDEF open <- ALL 1:to(100) ^ 2 \\ $ <= 100;\nDEF closed <- ALL 1:to(100) \\ NOT $ IN open;\n\nOut:write('Doors {open} are open.\\n');\nOut:write('Doors {closed} are closed.\\n');\n\nEND Doors.", "safe": true }, { "filename": "100_doors_75.txt", "content": "OPTION BASE 1\n\nDECLARE doors[100]\n\nFOR size = 1 TO 100\n FOR pass = 0 TO 100 STEP size\n\tdoors[pass] = NOT(doors[pass])\n NEXT\nNEXT\n\nFOR which = 1 TO 100\n IF doors[which] THEN PRINT which\nNEXT\n", "safe": true }, { "filename": "100_doors_750.txt", "content": "var doors = [true] * 100\nfor (i in 1..100) {\n var j = i\n while (j < 100) {\n doors[j] = !doors[j]\n j = j + i + 1\n }\n}\n\nfor (i in 0...100) {\n if (doors[i]) System.write(\"%(i + 1) \")\n}\nSystem.print()", "safe": true }, { "filename": "100_doors_751.txt", "content": "var door = 1\nvar increment = 3\nwhile (door <= 100) {\n System.write(\"%(door) \")\n door = door + increment\n increment = increment + 2\n}\nSystem.print()", "safe": true }, { "filename": "100_doors_752.txt", "content": "1 4 9 16 25 36 49 64 81 100 \n", "safe": true }, { "filename": "100_doors_753.txt", "content": "\t\t.NOLIST\n\n; The task can be completed in 48 and \"half\" steps:\n; On the first pass ALL doors are opened.\n; On the second pass every EVEN door is closed.\n; So, instead of all closed, the doors can initially be:\n; Every odd door open, every even door closed and start at pass 3.\n; On 51st and all the next passes, only one door is visited per pass:\n; On 51st pass door 51, on 52nd pass door 52 etc.\n; So, after pass 50, we can make \"half a pass\" starting with door 51\n; and toggling every door up to and including 100.\n; The code uses only volatile registers, so, no string (STOS etc) instructions.\n\n\t\tTITLE\t100 Doors\n\t\tPAGE\t, 132\n\t\t.686\n\t\t.MODEL\tFLAT\n\t\tOPTION\tCASEMAP:NONE\n\n\t\t.SFCOND\n\t\t.LIST\n\n; =============================================================================\n\n\t\t.DATA?\n\nDoors\t\tBYTE\t100 DUP (\u00a0? )\n\n; =============================================================================\n\n\t\t.CODE\n\nPass_Doors\tPROC\n\n\t\tMOV\tEDX, OFFSET Doors\t; Initialize all doors.\n\t\tMOV\tECX, SIZEOF Doors / SIZEOF DWORD\n\t\tMOV\tEAX, 01010101h\t\t; This does first and second pass.\n\nClose_Doors:\tMOV\t[ EDX ], EAX\n\t\tADD\tEDX, SIZEOF DWORD\n\t\tLOOP\tClose_Doors\n\n\t\tMOV\tECX, 2\t\t\t; Pass and step.\n\nPass_Loop:\tMOV\tEDX, OFFSET Doors\n\n\t\tASSUME\tEDX:PTR BYTE\n\nDoors_Loop:\tXOR\t[ EDX ], 1\t\t; Toggle this door.\n\t\tADD\tEDX, ECX \u00a0; Advance.\n\t\tCMP\tEDX, OFFSET Doors[ SIZEOF Doors ]\n\n\t\tJB\tDoors_Loop\n\n\t\tINC\tECX\n\t\tCMP\tECX, SIZEOF Doors\n\n\t\tJB\tPass_Loop\n\n\t\tXOR\tDoors[ SIZEOF Doors -1 ], 1\u00a0; This is pass 100.\n\t\tRET\n\nPass_Doors\tENDP\n\n; =============================================================================\n\n\t\tEND", "safe": true }, { "filename": "100_doors_754.txt", "content": "PROGRAM \"100doors\"\nVERSION \"0.0001\"\n\nIMPORT \"xma\"\nIMPORT \"xst\"\n\nDECLARE FUNCTION Entry()\n\nFUNCTION Entry()\n maxpuertas = 100\n cont = 0\n DIM puertas[100]\n\n FOR p = 1 TO maxpuertas\n IF INT(SQRT(p)) = SQRT(p) THEN puertas[p] = 1\n NEXT p\n\n PRINT \"The doors are open: \";\n FOR p = 1 TO maxpuertas\n IF puertas[p] = 1 THEN\n PRINT p; \" \";\n INC cont\n END IF\n NEXT p\n\n PRINT CHR$(10); \"Are \"; STR$(cont); \" open doors.\"\n\nEND FUNCTION\nEND PROGRAM", "safe": true }, { "filename": "100_doors_755.txt", "content": "// True=Open; False=Closed\nDim doors(100) As Boolean // Booleans default to false\nFor j As Integer = 1 To 100\n For i As Integer = 1 to 100\n If i Mod j = 0 Then doors(i) = Not doors(i)\n Next\nNext", "safe": true }, { "filename": "100_doors_756.txt", "content": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nint Door(100); \\You have 100 doors in a row\ndefine Open, Closed;\nint D, Pass, Step;\n\n[for D:= 0 to 100-1 do \\that are all initially closed\n Door(D):= Closed;\n\nStep:= 1; \\The first time through, you visit every door\nfor Pass:= 1 to 100 do \\You make 100 passes by the doors\n [D:= Step-1;\n repeat \\if the door is closed, you open it; if it is open, you close it\n if Door(D)=Closed then Door(D):= Open else Door(D):= Closed;\n D:= D+Step;\n until D>=100;\n Step:= Step+1; \\The second time you only visit every 2nd door\n ]; \\The third time, every 3rd door\n \\until you only visit the 100th door\n\\What state are the doors in after the last pass?\nText(0, \"Open: \"); \\Which are open?\nfor D:= 0 to 100-1 do \n if Door(D)=Open then [IntOut(0, D+1); ChOut(0,^ )];\nCrLf(0);\n\nText(0, \"Closed: \"); \\Which are closed?\nfor D:= 0 to 100-1 do \n if Door(D)=Closed then [IntOut(0, D+1); ChOut(0,^ )];\nCrLf(0);\n\n\\Optimized: The only doors that remain open are those that are perfect squares\nText(0, \"Open: \");\nD:= 1;\nrepeat IntOut(0, D*D); ChOut(0,^ );\n D:= D+1;\nuntil D*D>100;\nCrLf(0);\n]", "safe": true }, { "filename": "100_doors_757.txt", "content": "\n closed\n closed\n closed\n closed\n ... etc ...\n closed\n", "safe": true }, { "filename": "100_doors_758.txt", "content": "\n\n\n\n \n \n \n\n \n\n \n \n \n \n !\n \n \n \n \n \n \n open\n \n \n closed\n \n \n \n\n \n", "safe": true }, { "filename": "100_doors_759.txt", "content": "\n\n\n\n \n \n \n \n \n \n \n \n\n \n", "safe": true }, { "filename": "100_doors_76.txt", "content": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100\n", "safe": true }, { "filename": "100_doors_760.txt", "content": "n = 100\t// doors\nppa = 1\t// next open door\np2 = 1\n\nfor i = 1 to n\n\tprint \"Door \", i, \" is \";\n\tif i < p2 then\n\t\tprint \"closed.\"\n\telse\n\t\tppa = ppa + 1\n\t\tp2 = ppa^2\n\t\tprint \"OPEN.\"\n\tend if\nnext", "safe": true }, { "filename": "100_doors_761.txt", "content": "for i = 1 to sqrt(100)\u00a0: print \"Door \", i**2, \" is open\"\u00a0: next", "safe": true }, { "filename": "100_doors_762.txt", "content": "!yamlscript/v0\n\ndefn main():\n open =:\n reduce _ vec([true] * 100) (1 .. 100):\n fn(doors i):\n loop j i, doors doors:\n if j < 100:\n recur (j + i).++:\n update-in doors [j]: \\(doors.$j.!)\n else: doors\n say: -\"Open doors after 100 passes:\\ \" +\n (1 .. 100).map(\\(_.--:open && _))\n .filter(a).join(', ')", "safe": true }, { "filename": "100_doors_763.txt", "content": "$ ys 100-doors.ys\nOpen doors after 100 passes: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100\n", "safe": true }, { "filename": "100_doors_764.txt", "content": "doors = array(0, 100);\nfor(i = 1; i <= 100; i++)\n for(j = i; j <= 100; j += i)\n doors(j) ~= 1;\nprint, where(doors);", "safe": true }, { "filename": "100_doors_765.txt", "content": "doors = array(0, 100);\nfor(i = 1; i <= 100; i++)\n doors(i::i) ~= 1;\nprint, where(doors);", "safe": true }, { "filename": "100_doors_766.txt", "content": "print, indgen(1:long(sqrt(100)))^2", "safe": true }, { "filename": "100_doors_767.txt", "content": "[1,4,9,16,25,36,49,64,81,100]\n", "safe": true }, { "filename": "100_doors_768.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n \n var doors = [_]bool{false} ** 101;\n var pass: u8 = 1;\n var door: u8 = undefined;\n \n while (pass <= 100)\u00a0: (pass += 1) {\n door = pass;\n while (door <= 100)\u00a0: (door += pass)\n doors[door] = !doors[door];\n }\n \n for (doors, 0..) |open, num|\n if (open) \n try stdout.print(\"Door {d} is open.\\n\", .{num});\n}", "safe": true }, { "filename": "100_doors_769.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n \n var square: u8 = 1;\n var increment: u8 = 3;\n var door: u8 = 1;\n while (door <= 100)\u00a0: (door += 1) {\n if (door == square) {\n try stdout.print(\"Door {d} is open\\n\", .{door});\n square += increment;\n increment += 2;\n }\n }\n}", "safe": true }, { "filename": "100_doors_77.txt", "content": "const NUM_DOORS\u00a0:= 100\n\nfun main() {\n\t// All doors are closed by default (`false`)\n\tmut is_open\u00a0:= []bool{length = NUM_DOORS}\n\n\t// Make 100 passes by the doors\n\tfor pass\u00a0:= 0; pass < 100; pass += 1 {\n\t\t// Only visit every `pass + 1`th door\n\t\tfor door\u00a0:= pass; door < NUM_DOORS; door += pass + 1 {\n\t\t\tis_open[door] = not is_open[door]\n\t\t}\n\t}\n\n\t// Print the doors that are open\n\tfor i, open in is_open {\n\t\tif open {\n\t\t\tprintln(\"Door #${i + 1} is open.\")\n\t\t}\n\t}\n\n}", "safe": true }, { "filename": "100_doors_770.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n\n var square: u8 = 1;\n var increment: u8 = 3;\n for (1..101) |door| {\n if (door == square) {\n try stdout.print(\"Door {d} is open\\n\", .{door});\n square += increment;\n increment += 2;\n }\n }\n}", "safe": true }, { "filename": "100_doors_771.txt", "content": "pub fn main() !void {\n const stdout = @import(\"std\").io.getStdOut().writer();\n\n var door: u8 = 1;\n while (door * door <= 100)\u00a0: (door += 1) {\n try stdout.print(\"Door {d} is open\\n\", .{door * door});\n }\n}", "safe": true }, { "filename": "100_doors_772.txt", "content": "Door 1 is open.\nDoor 4 is open.\nDoor 9 is open.\nDoor 16 is open.\nDoor 25 is open.\nDoor 36 is open.\nDoor 49 is open.\nDoor 64 is open.\nDoor 81 is open.\nDoor 100 is open.", "safe": true }, { "filename": "100_doors_773.txt", "content": "doors:=List.createLong(100,False);\t// list of 100 Falses\nforeach n,m in (100,[n..99,n+1]){ doors[m]=(not doors[m]); } //foreach{ foreach{} }\ndoors.filterNs().apply('+(1)).println();", "safe": true }, { "filename": "100_doors_774.txt", "content": "L(1,4,9,16,25,36,49,64,81,100)", "safe": true }, { "filename": "100_doors_775.txt", "content": " 10 REM 100 doors open/closed?\n 20 DIM d(100)\n 25 LET o=0\n 30 FOR a=1 TO 100\n 40 FOR b=a TO 100 STEP a\n 50 LET d(b)=NOT d(b)\n 55 LET o=o+(d(b)=1)-(d(b)=0)\n 60 NEXT b\n 70 NEXT a\n 80 PRINT o;\" open doors\"\n", "safe": true }, { "filename": "100_doors_776.txt", "content": " 10 REM 100 doors open/closed?\n 20 DIM d(100)\n 25 GO SUB 170\n 30 FOR a=1 TO 100\n 35 PRINT AT 0,0;\"step \";a\n 40 FOR b=a TO 100 STEP a\n 45 PRINT AT 0,10;\"door:\";b;\" \"\n 50 LET d(b)=NOT d(b)\n 55 GO SUB 150\n 60 NEXT b\n 70 NEXT a\n 80 GO SUB 170\n 90 STOP \n150 REM print door status\n151 LET p=(b-1)/10\n152 LET q=1+10*(p-INT p)\n153 LET p=INT p\n154 LET op=op+(d(b)=1)-(d(b)=0)\n156 PRINT AT 2*p+2,2*q;d(b);AT 0,27;op;\" \"\n160 RETURN \n165 REM print step status\n170 LET op=0\n175 FOR p=0 TO 9\n180 FOR q=1 TO 10\n185 PRINT AT 2*p+2,2*q;d(p*10+q)\n188 LET op=op+d(p*10+q)\n190 NEXT q\n200 NEXT p\n205 PRINT AT 0,22;\"open:\";op;\" \"\n210 RETURN\n", "safe": true }, { "filename": "100_doors_78.txt", "content": "Door #1 is open.\nDoor #4 is open.\nDoor #9 is open.\nDoor #16 is open.\nDoor #25 is open.\nDoor #36 is open.\nDoor #49 is open.\nDoor #64 is open.\nDoor #81 is open.\nDoor #100 is open.\n", "safe": true }, { "filename": "100_doors_79.txt", "content": " 100 :\n 110 REM 100 DOORS PROBLEM\n 120 :\n 130 DIM D(100)\n 140 FOR P = 1 TO 100\n 150 FOR T = P TO 100 STEP P\n 160 D(T) = NOT D(T): NEXT T\n 170 NEXT P\n 180 FOR I = 1 TO 100\n 190 IF D(I) THEN PRINT I;\" \";\n 200 NEXT I\n", "safe": true }, { "filename": "100_doors_8.txt", "content": " ;assumes memory at $02xx is initially set to 0 and stack pointer is initialized\n ;the 1 to 100 door byte array will be at $0200-$0263 (decimal 512 to 611)\n ;Zero-page location $01 will hold delta\n ;At end, closed doors = $00, open doors = $01\n\nstart: ldx #0 ;initialize index - first door will be at $200 + $0\n stx $1\n inc $1 ;start out with a delta of 1 (0+1=1)\nopenloop: inc $200,X ;open X'th door\n inc $1 ;add 2 to delta\n inc $1\n txa ;add delta to X by transferring X to A, adding delta to A, then transferring back to X\n clc \u00a0; clear carry before adding (6502 has no add-without-carry instruction)\n adc $1\n tax\n cpx #$64 ;check to see if we're at or past the 100th door (at $200 + $63)\n bmi openloop ;jump back to openloop if less than 100", "safe": true }, { "filename": "100_doors_80.txt", "content": " \n]RUN\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_81.txt", "content": "# 100 doors problem\ndim d(100)\n\n# simple solution\nprint \"simple solution\"\ngosub initialize\nfor t = 1 to 100\n for j = t to 100 step t\n d[j-1] = not d[j-1]\n next j\nnext t\ngosub showopen\n\n# more optimized solution\nprint \"more optimized solution\"\ngosub initialize\nfor t = 1 to 10\n d[t^2-1] = true\nnext t\ngosub showopen\nend\n\ninitialize:\nfor t = 1 to d[?]\n d[t-1] = false\t # closed\nnext t\nreturn\n\nshowopen:\nfor t = 1 to d[?]\n print d[t-1]+ \" \";\n if t%10 = 0 then print\nnext t\nreturn", "safe": true }, { "filename": "100_doors_82.txt", "content": "for i = 1 to 10 : if i % i^2 < 11 then print \"La puerta \"; int(i^2); \" esta abierta\" : end if : next i : end\n", "safe": true }, { "filename": "100_doors_83.txt", "content": "dim doors%(100)\n\nprint \"Finding solution to the 100 Doors Problem\"\n\nrem - all doors are initially closed\nfor i% = 1 to 100\n doors%(i%) = 0\nnext i%\n\nrem - pass through at increasing intervals\nfor i% = 1 to 100\n for j% = i% to 100 step i%\n rem - flip each door encountered\n doors%(j%) = 1 - doors%(j%)\n next j%\nnext i%\n\nrem - show which doors are open\nprint \"The open doors are: \";\nfor i% = 1 to 100\n if doors%(i%) = 1 then print i%;\nnext i%\n\nprint\nprint \"Thanks for consulting the puzzle guru!\"\n\nend\n", "safe": true }, { "filename": "100_doors_84.txt", "content": "Finding solution to the 100 Doors Problem\nThe open doors are: 1 4 9 15 25 36 47 64 81 100\nThanks for consulting the puzzle guru!\n", "safe": true }, { "filename": "100_doors_85.txt", "content": "100 CLS : REM 10 HOME for Applesoft BASIC\n110 DIM D(100)\n120 FOR P = 1 TO 100\n130 FOR T = P TO 100 STEP P\n140 D(T) = NOT D(T)\n150 NEXT T\n160 NEXT P\n170 ' Print \"opened\" doors\n180 FOR I = 1 TO 100\n190 IF D(I) THEN PRINT I;\" \";\n200 NEXT I\n210 END\n", "safe": true }, { "filename": "100_doors_86.txt", "content": ">RUN\n1 4 9 16 25 36 49 64 81 100 >", "safe": true }, { "filename": "100_doors_87.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=I TO 100 STEP I\n40 D(J) = NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I,\n90 NEXT I\n", "safe": true }, { "filename": "100_doors_88.txt", "content": "100 CLS : REM 10 HOME for Applesoft BASIC\n110 DIM D(100)\n120 FOR P = 1 TO 100\n130 FOR T = P TO 100 STEP P\n140 D(T) = NOT D(T)\n150 NEXT T\n160 NEXT P\n170 ' Print \"opened\" doors\n180 FOR I = 1 TO 100\n190 IF D(I) THEN PRINT I;\" \";\n200 NEXT I\n210 END\n", "safe": true }, { "filename": "100_doors_89.txt", "content": " 1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_9.txt", "content": "*-----------------------------------------------------------\n* Title : 100Doors.X68\n* Written by : G. A. Tippery\n* Date : 2014-01-17\n* Description: Solves \"100 Doors\" problem, see: http://rosettacode.org/wiki/100_doors\n* Notes : Translated from C \"Unoptimized\" version, http://rosettacode.org/wiki/100_doors#unoptimized\n* : No optimizations done relative to C version; \"for(\"-equivalent loops could be optimized.\n*-----------------------------------------------------------\n\n*\n* System-specific general console I/O macros (Sim68K, in this case)\n*\nPUTS MACRO\n ** Print a null-terminated string w/o CRLF **\n ** Usage: PUTS stringaddress\n ** Returns with D0, A1 modified\n MOVEQ #14,D0 ; task number 14 (display null string)\n LEA \\1,A1 ; address of string\n TRAP #15 ; display it\n ENDM\n*\nPRINTN MACRO\n ** Print decimal integer from number in register\n ** Usage: PRINTN register\n ** Returns with D0,D1 modified\n IFNC '\\1','D1' ;if some register other than D1\n MOVE.L \\1,D1 ;put number to display in D1\n ENDC\n MOVE.B #3,D0\n TRAP #15 ;display number in D1\n*\n* Generic constants\n*\nCR EQU 13 ;ASCII Carriage Return\nLF EQU 10 ;ASCII Line Feed\n\n*\n* Definitions specific to this program\n*\n* Register usage:\n* D3 == pass (index)\n* D4 == door (index)\n* A2 == Doors array pointer\n*\nSIZE EQU 100 ;Define a symbolic constant for # of doors\n\n ORG $1000 ;Specify load address for program -- actual address system-specific\nSTART: ; Execution starts here\n LEA Doors,A2 ; make A2 point to Doors byte array\n MOVEQ #0,D3\nPassLoop:\n CMP #SIZE,D3\n BCC ExitPassLoop ; Branch on Carry Clear - being used as Branch on Higher or Equal\n MOVE D3,D4\nDoorLoop:\n CMP #SIZE,D4\n BCC ExitDoorLoop\n NOT.B 0(A2,D4)\n ADD D3,D4\n ADDQ #1,D4\n BRA DoorLoop\nExitDoorLoop:\n ADDQ #1,D3\n BRA PassLoop\nExitPassLoop:\n\n* $28 = 40. bytes of code to this point. 32626 cycles so far.\n* At this point, the result exists as the 100 bytes starting at address Doors.\n* To get output, we must use methods specific to the particular hardware, OS, or\n* emulator system that the code is running on. I use macros to \"hide\" some of the\n* system-specific details; equivalent macros would be written for another system.\n\n MOVEQ #0,D4\nPrintLoop:\n CMP #SIZE,D4\n BCC ExitPrintLoop\n PUTS DoorMsg1\n MOVE D4,D1\n ADDQ #1,D1 ; Convert index to 1-based instead of 0-based\n PRINTN D1\n PUTS DoorMsg2\n TST.B 0(A2,D4) ; Is this door open (!= 0)?\n BNE ItsOpen\n PUTS DoorMsgC\n BRA Next\nItsOpen:\n PUTS DoorMsgO\nNext:\n ADDQ #1,D4\n BRA PrintLoop\nExitPrintLoop:\n\n* What to do at end of program is also system-specific\n SIMHALT ;Halt simulator\n*\n* $78 = 120. bytes of code to this point, but this will depend on how the I/O macros are actually written.\n* Cycle count is nearly meaningless, as the I/O hardware and routines will dominate the timing.\n\n*\n* Data memory usage\n*\n ORG $2000\nDoors DCB.B SIZE,0 ;Reserve 100 bytes, prefilled with zeros\n\nDoorMsg1 DC.B 'Door ',0\nDoorMsg2 DC.B ' is ',0\nDoorMsgC DC.B 'closed',CR,LF,0\nDoorMsgO DC.B 'open',CR,LF,0\n\n END START ;last line of source\n", "safe": true }, { "filename": "100_doors_90.txt", "content": "100 PROGRAM \"100doors.bas\"\n110 NUMERIC D(1 TO 100)\n120 FOR I=1 TO 100\n130 LET D(I)=0\n140 NEXT\n150 FOR I=1 TO 100\n160 FOR J=I TO 100 STEP I\n170 LET D(J)=NOT D(J)\n180 NEXT \n190 NEXT\n200 FOR I=1 TO 100\n210 IF D(I) THEN PRINT I\n220 NEXT", "safe": true }, { "filename": "100_doors_91.txt", "content": "100 PROGRAM \"100doors.bas\"\n110 LET NR=1:LET D=3\n120 DO\n130 PRINT NR\n140 LET NR=NR+D:LET D=D+2\n150 LOOP WHILE NR<=100", "safe": true }, { "filename": "100_doors_92.txt", "content": "10 PRINT \"FOLLOWING DOORS ARE OPEN:\"\n20 LET I = 0\n30 REM LOOP\n40 LET I = I + 1\n50 PRINT I * I; \" \";\n60 IF I * I < 100 THEN 30\n70 END\n", "safe": true }, { "filename": "100_doors_93.txt", "content": "10 DIM D(100)\n20 FOR I=1 TO 100\n30 FOR J=i TO 100 STEP I\n40 D(J)=NOT D(J)\n50 NEXT J\n60 NEXT I\n70 FOR I=1 TO 100\n80 IF D(I) THEN PRINT I;\n90 NEXT I\n100 END\n", "safe": true }, { "filename": "100_doors_94.txt", "content": " \n]RUN\n1 4 9 16 25 36 49 64 81 100", "safe": true }, { "filename": "100_doors_95.txt", "content": "REM \"100 Doors\" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler.\nREM Author: G. A. Tippery\nREM Date: 12-Feb-2014\nREM\nREM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors\n\nDEFINT A-Z\nCONST N = 100\nDIM door(N)\n\nFOR stride = 1 TO N\n FOR index = stride TO N STEP stride\n LET door(index) = NOT (door(index))\n NEXT index\nNEXT stride\n\nPRINT \"Open doors:\"\nFOR index = 1 TO N\n IF door(index) THEN PRINT index\nNEXT index\n\nEND\n", "safe": true }, { "filename": "100_doors_96.txt", "content": "DIM doors(0 TO 99)\nFOR pass = 0 TO 99\n\tFOR door = pass TO 99 STEP pass + 1\n\t\tPRINT doors(door)\n\t\tPRINT NOT doors(door)\n\t\tdoors(door) = NOT doors(door)\n\tNEXT door\nNEXT pass\nFOR i = 0 TO 99\n\tPRINT \"Door #\"; i + 1; \" is \";\n\tIF NOT doors(i) THEN\n\t\tPRINT \"closed\"\n\tELSE\n\t\tPRINT \"open\"\n\tEND IF\nNEXT i\n", "safe": true }, { "filename": "100_doors_97.txt", "content": "DIM doors(0 TO 99)\nFOR door = 0 TO 99\n\tIF INT(SQR(door)) = SQR(door) THEN doors(door) = -1\nNEXT door\nFOR i = 0 TO 99\n\tPRINT \"Door #\"; i + 1; \" is \";\n\tIF NOT doors(i) THEN\n\t\tPRINT \"closed\"\n\tELSE\n\t\tPRINT \"open\"\n\tEND IF\nNEXT i\n", "safe": true }, { "filename": "100_doors_98.txt", "content": "100 ARRAY D\n110 FOR P = 1 TO 100\n120 FOR T = P TO 100 STEP P\n130 LET D[T] = (D[T] <> 1)\n140 NEXT T\n150 NEXT P\n160 FOR I = 1 TO 100\n170 IF D[I] THEN PRINT I;\" \";\n180 NEXT I\n190 END\n", "safe": true }, { "filename": "100_doors_99.txt", "content": " PRINT \"Open doors are:\"\n\n LET I = 1\n10 IF I = 100 THEN END \n rem funcion SQR\n LET B = I*I\n rem funcion MODULO\n LET A = I - (I / B) * B\n IF A < 11 THEN PRINT B\n LET I = I + 1\n GOTO 10", "safe": true }, { "filename": "100_prisoners_1.txt", "content": "F play_random(n)\n V pardoned = 0\n V in_drawer = Array(0.<100)\n V sampler = Array(0.<100)\n L 0 .< n\n random:shuffle(&in_drawer)\n V found = 0B\n L(prisoner) 100\n found = 0B\n L(reveal) random:sample(sampler, 50)\n V card = in_drawer[reveal]\n I card == prisoner\n found = 1B\n L.break\n I !found\n L.break\n I found\n pardoned++\n R Float(pardoned) / n * 100\n\nF play_optimal(n)\n V pardoned = 0\n V in_drawer = Array(0.<100)\n L 0 .< n\n random:shuffle(&in_drawer)\n V found = 0B\n L(prisoner) 100\n V reveal = prisoner\n found = 0B\n L 50\n V card = in_drawer[reveal]\n I card == prisoner\n found = 1B\n L.break\n reveal = card\n I !found\n L.break\n I found\n pardoned++\n R Float(pardoned) / n * 100\n\nV n = 100'000\nprint(\u2018 Simulation count: \u2019n)\nprint(\u2018 Random play wins: #2.1% of simulations\u2019.format(play_random(n)))\nprint(\u2018Optimal play wins: #2.1% of simulations\u2019.format(play_optimal(n)))", "safe": true }, { "filename": "100_prisoners_10.txt", "content": "Optimal Strategy = 31.80%\nRandom Strategy = 0.00%\n", "safe": true }, { "filename": "100_prisoners_100.txt", "content": "a:=[seq(max(GroupTheory[PermCycleType](Perm(Statistics[Shuffle]([$1..100])))),i=1..100000)]:\nnops(select(n->n<=50,a))/nops(a);\nevalf(%);\n# 31239/100000\n# 0.3123900000", "safe": true }, { "filename": "100_prisoners_101.txt", "content": "1-(harmonic(100)-harmonic(50));\nevalf(%);\n\n# 21740752665556690246055199895649405434183/69720375229712477164533808935312303556800\n# 0.3118278207", "safe": true }, { "filename": "100_prisoners_102.txt", "content": "ClearAll[PlayRandom, PlayOptimal]\nPlayRandom[n_] := \n Module[{pardoned = 0, sampler, indrawer, found, reveal},\n sampler = indrawer = Range[100];\n Do[\n indrawer //= RandomSample;\n found = 0;\n Do[\n reveal = RandomSample[sampler, 50];\n If[MemberQ[indrawer[[reveal]], p],\n found++;\n ]\n ,\n {p, 100}\n ];\n If[found == 100, pardoned++];\n ,\n {n}\n ];\n N[pardoned/n]\n ]\nPlayOptimal[n_] := \n Module[{pardoned = 0, indrawer, reveal, found, card},\n indrawer = Range[100];\n Do[\n indrawer //= RandomSample;\n Do[\n reveal = p;\n found = False;\n Do[\n card = indrawer[[reveal]];\n If[card == p,\n found = True;\n Break[];\n ];\n reveal = card;\n ,\n {g, 50}\n ];\n If[! found, Break[]];\n ,\n {p, 100}\n ];\n If[found, pardoned++];\n ,\n {n}\n ];\n N[pardoned/n]\n ];\nPlayRandom[1000]\nPlayOptimal[10000]\n", "safe": true }, { "filename": "100_prisoners_103.txt", "content": "0.\n0.3116", "safe": true }, { "filename": "100_prisoners_104.txt", "content": "function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)\n %numP is the number of prisoners\n %numG is the number of guesses\n %numT is the number of trials\n randSuccess=0;\n \n %Random\n for trial=1:numT\n drawers=randperm(numP);\n won=1;\n for i=1:numP\n correct=0;\n notopened=drawers;\n for j=1:numG\n ind=randi(numel(notopened));\n m=notopened(ind);\n if m==i\n correct=1;\n break;\n end\n notopened(ind)=[];\n end\n if correct==0\n won=0;\n break;\n end\n end\n randSuccess=randSuccess*(trial-1)/trial+won/trial;\n end\n \n\n %Ideal\n idealSuccess=0;\n\n for trial=1:numT\n drawers=randperm(numP);\n won=1;\n for i=1:numP\n correct=0;\n guess=i;\n for j=1:numG\n m=drawers(guess);\n if m==i\n correct=1;\n break;\n end\n guess=m;\n end\n if correct==0\n won=0;\n break;\n end\n end\n idealSuccess=idealSuccess*(trial-1)/trial+won/trial;\n end\n disp(['Probability of success with random strategy: ' num2str(randSuccess*100) '%']);\n disp(['Probability of success with ideal strategy: ' num2str(idealSuccess*100) '%']);\nend\n", "safe": true }, { "filename": "100_prisoners_105.txt", "content": ">> [randSuccess,idealSuccess]=prisoners(100,50,10000);\nProbability of success with random strategy: 0%\nProbability of success with ideal strategy: 31.93%", "safe": true }, { "filename": "100_prisoners_106.txt", "content": "playRandom = function(n)\n // using 0-99 instead of 1-100\n pardoned = 0\n numInDrawer = range(99)\n choiceOrder = range(99)\n for round in range(1, n)\n \tnumInDrawer.shuffle\n choiceOrder.shuffle\n for prisoner in range(99)\n found = false\n for card in choiceOrder[:50]\n if card == prisoner then\n found = true\n break\n end if\n end for\n if not found then break\n end for\n if found then pardoned = pardoned + 1\n end for\n return pardoned / n * 100\nend function\n\nplayOptimal = function(n)\n // using 0-99 instead of 1-100\n pardoned = 0\n numInDrawer = range(99)\n for round in range(1, n)\n \tnumInDrawer.shuffle\n for prisoner in range(99)\n found = false\n\t drawer = prisoner\n for i in range(1,50)\n card = numInDrawer[drawer]\n if card == prisoner then\n found = true\n break\n end if\n drawer = card\n end for\n if not found then break\n end for\n if found then pardoned = pardoned + 1\n end for\n return pardoned / n * 100\nend function\n\nprint \"Random: \" + playRandom(10000) + \"%\"\nprint \"Optimal: \" + playOptimal(10000) + \"%\"\n", "safe": true }, { "filename": "100_prisoners_107.txt", "content": "Random: 0%\nOptimal: 31.06%", "safe": true }, { "filename": "100_prisoners_108.txt", "content": "import random, sequtils, strutils\n\ntype\n Sample = tuple\n succ: int\n fail: int\n\nconst\n numPrisoners = 100\n numDrawsEachPrisoner = numPrisoners div 2\n numDrawings: Positive = 1_000_000 div 1\n\nproc `$`(s: Sample): string =\n \"Succs: $#\\tFails: $#\\tTotal: $#\\tSuccess Rate: $#%.\" % [$s.succ, $s.fail, $(s.succ + s.fail), $(s.succ.float / (s.succ + s.fail).float * 100.0)]\n\nproc prisonersWillBeReleasedSmart(): bool =\n result = true\n var drawers = toSeq(0..0)/LOOP\n R \u2190 R \u00f7 M\n\u2207\n\n\u2395TS\n'>>>>>'\n1000 timesSimPrisoners 100 50\n'>>>>>'\n\u2395TS\n", "safe": true }, { "filename": "100_prisoners_110.txt", "content": "program Prisoners100;\n\nconst\n rounds = 100000;\n\ntype\n tValue = Uint32;\n tPrisNum = array of tValue;\nvar\n drawers,\n PrisonersChoice : tPrisNum;\n\nprocedure shuffle(var N:tPrisNum);\nvar\n i,j,lmt : nativeInt;\n tmp: tValue;\nBegin\n lmt := High(N);\n For i := lmt downto 1 do\n begin\n //take on from index i..limit\n j := random(i+1);\n //exchange with i\n tmp := N[i];N[i]:= N[j];N[j]:= tmp;\n end;\nend;\n\nfunction PardonedRandom(maxTestNum: NativeInt):boolean;\nvar\n PrisNum,TestNum,Lmt : NativeUint;\n Pardoned : boolean;\nBegin\n IF maxTestNum <=0 then\n Begin\n PardonedRandom := false;\n EXIT;\n end;\n Lmt := High(drawers);\n IF (maxTestNum >= Lmt) then\n Begin\n PardonedRandom := true;\n EXIT;\n end;\n\n shuffle(drawers);\n PrisNum := 0;\n repeat\n //every prisoner uses his own list of drawers\n shuffle(PrisonersChoice);\n TestNum := 0;\n repeat\n Pardoned := drawers[PrisonersChoice[TestNum]] = PrisNum;\n inc(TestNum);\n until Pardoned OR (TestNum>=maxTestNum);\n IF Not(Pardoned) then\n BREAK;\n inc(PrisNum);\n until PrisNum>=Lmt;\n PardonedRandom:= Pardoned;\nend;\n\nfunction PardonedOptimized(maxTestNum: NativeUint):boolean;\nvar\n PrisNum,TestNum,NextNum,Cnt,Lmt : NativeUint;\n Pardoned : boolean;\nBegin\n IF maxTestNum <=0 then\n Begin\n PardonedOptimized := false;\n EXIT;\n end;\n Lmt := High(drawers);\n IF (maxTestNum >= Lmt) then\n Begin\n PardonedOptimized := true;\n EXIT;\n end;\n\n shuffle(drawers);\n Lmt := High(drawers);\n IF maxTestNum >= Lmt then\n Begin\n PardonedOptimized := true;\n EXIT;\n end;\n PrisNum := 0;\n repeat\n Cnt := 0;\n NextNum := PrisNum;\n repeat\n TestNum := NextNum;\n NextNum := drawers[TestNum];\n inc(cnt);\n Pardoned := NextNum = PrisNum;\n until Pardoned OR (cnt >=maxTestNum);\n\n IF Not(Pardoned) then\n BREAK;\n inc(PrisNum);\n until PrisNum>Lmt;\n PardonedOptimized := Pardoned;\nend;\n\nprocedure CheckRandom(testCount : NativeUint);\nvar\n i,cnt : NativeInt;\nBegin\n cnt := 0;\n For i := 1 to rounds do\n IF PardonedRandom(TestCount) then\n inc(cnt);\n writeln('Randomly ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);\nend;\n\nprocedure CheckOptimized(testCount : NativeUint);\nvar\n i,cnt : NativeInt;\nBegin\n cnt := 0;\n For i := 1 to rounds do\n IF PardonedOptimized(TestCount) then\n inc(cnt);\n writeln('Optimized ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);\nend;\n\nprocedure OneCompareRun(PrisCnt:NativeInt);\nvar\n i,lmt :nativeInt;\nbegin\n setlength(drawers,PrisCnt);\n For i := 0 to PrisCnt-1 do\n drawers[i] := i;\n PrisonersChoice := copy(drawers);\n\n //test\n writeln('Checking ',PrisCnt,' prisoners');\n\n lmt := PrisCnt;\n repeat\n CheckOptimized(lmt);\n dec(lmt,PrisCnt DIV 10);\n until lmt < 0;\n writeln;\n\n lmt := PrisCnt;\n repeat\n CheckRandom(lmt);\n dec(lmt,PrisCnt DIV 10);\n until lmt < 0;\n writeln;\n writeln;\nend;\n\nBegin\n //init\n randomize;\n OneCompareRun(20);\n OneCompareRun(100);\nend.\n", "safe": true }, { "filename": "100_prisoners_111.txt", "content": "Checking 20 prisoners\nOptimized 100.00% get pardoned out of 100000 checking max 20\nOptimized 89.82% get pardoned out of 100000 checking max 18\nOptimized 78.25% get pardoned out of 100000 checking max 16\nOptimized 65.31% get pardoned out of 100000 checking max 14\nOptimized 50.59% get pardoned out of 100000 checking max 12\nOptimized 33.20% get pardoned out of 100000 checking max 10\nOptimized 15.28% get pardoned out of 100000 checking max 8\nOptimized 3.53% get pardoned out of 100000 checking max 6\nOptimized 0.10% get pardoned out of 100000 checking max 4\nOptimized 0.00% get pardoned out of 100000 checking max 2\nOptimized 0.00% get pardoned out of 100000 checking max 0\n\nRandomly 100.00% get pardoned out of 100000 checking max 20\nRandomly 13.55% get pardoned out of 100000 checking max 18\nRandomly 1.38% get pardoned out of 100000 checking max 16\nRandomly 0.12% get pardoned out of 100000 checking max 14\nRandomly 0.00% get pardoned out of 100000 checking max 12\nRandomly 0.00% get pardoned out of 100000 checking max 10\nRandomly 0.00% get pardoned out of 100000 checking max 8\nRandomly 0.00% get pardoned out of 100000 checking max 6\nRandomly 0.00% get pardoned out of 100000 checking max 4\nRandomly 0.00% get pardoned out of 100000 checking max 2\nRandomly 0.00% get pardoned out of 100000 checking max 0\n\n\nChecking 100 prisoners\nOptimized 100.00% get pardoned out of 100000 checking max 100\nOptimized 89.48% get pardoned out of 100000 checking max 90\nOptimized 77.94% get pardoned out of 100000 checking max 80\nOptimized 64.48% get pardoned out of 100000 checking max 70\nOptimized 49.35% get pardoned out of 100000 checking max 60\nOptimized 31.10% get pardoned out of 100000 checking max 50\nOptimized 13.38% get pardoned out of 100000 checking max 40\nOptimized 2.50% get pardoned out of 100000 checking max 30\nOptimized 0.05% get pardoned out of 100000 checking max 20\nOptimized 0.00% get pardoned out of 100000 checking max 10\nOptimized 0.00% get pardoned out of 100000 checking max 0\n\nRandomly 100.00% get pardoned out of 100000 checking max 100\nRandomly 0.01% get pardoned out of 100000 checking max 90\nRandomly 0.00% get pardoned out of 100000 checking max 80\nRandomly 0.00% get pardoned out of 100000 checking max 70\nRandomly 0.00% get pardoned out of 100000 checking max 60\nRandomly 0.00% get pardoned out of 100000 checking max 50\nRandomly 0.00% get pardoned out of 100000 checking max 40\nRandomly 0.00% get pardoned out of 100000 checking max 30\nRandomly 0.00% get pardoned out of 100000 checking max 20\nRandomly 0.00% get pardoned out of 100000 checking max 10\nRandomly 0.00% get pardoned out of 100000 checking max 0", "safe": true }, { "filename": "100_prisoners_112.txt", "content": "program Prisoners100;\n{$IFDEF FPC}\n {$MODE DELPHI}{$OPTIMIZATION ON,ALL}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\ntype\n tValue = NativeUint;\n tpValue = pNativeUint;\n tPrisNum = array of tValue;\n\nconst\n rounds = 1000000;\n cAlreadySeen = High(tValue);\nvar\n drawers,\n Visited,\n CntToPardoned : tPrisNum;\n PrisCount : NativeInt;\n\nprocedure shuffle(var N:tPrisNum;lmt : nativeInt = 0);\nvar\n pN : tpValue;\n i,j : nativeInt;\n tmp: tValue;\nBegin\n pN := @N[0];\n if lmt = 0 then\n lmt := High(N);\n For i := lmt downto 1 do\n begin\n //take one from index [0..i]\n j := random(i+1);\n //exchange with i\n tmp := pN[i];pN[i]:= pN[j];pN[j]:= tmp;\n end;\nend;\n\nprocedure CopyDrawers2Visited;\n//drawers and Visited are of same size, so only moving values\nBegin\n Move(drawers[0],Visited[0],SizeOf(tValue)*PrisCount);\nend;\n\nfunction GetMaxCycleLen:NativeUint;\nvar\n pVisited : tpValue;\n cycleLen,MaxCycLen,Num,NumBefore : NativeUInt;\nBegin\n CopyDrawers2Visited;\n pVisited := @Visited[0];\n MaxCycLen := 0;\n cycleLen := MaxCycLen;\n Num := MaxCycLen;\n repeat\n NumBefore := Num;\n Num := pVisited[Num];\n pVisited[NumBefore] := cAlreadySeen;\n inc(cycleLen);\n IF (Num= NumBefore) or (Num = cAlreadySeen) then\n begin\n IF Num = cAlreadySeen then\n dec(CycleLen);\n IF MaxCycLen < cycleLen then\n MaxCycLen := cycleLen;\n Num := 0;\n while (Num< PrisCount) AND (pVisited[Num] = cAlreadySeen) do\n inc(Num);\n //all cycles found\n IF Num >= PrisCount then\n BREAK;\n cycleLen :=0;\n end;\n until false;\n GetMaxCycleLen := MaxCycLen-1;\nend;\n\nprocedure CheckOptimized(testCount : NativeUint);\nvar\n factor: extended;\n i,sum,digit,delta : NativeInt;\nBegin\n For i := 1 to rounds do\n begin\n shuffle(drawers);\n inc(CntToPardoned[GetMaxCycleLen]);\n end;\n\n digit := 0;\n sum := rounds;\n while sum > 100 do\n Begin\n inc(digit);\n sum := sum DIV 10;\n end;\n factor := 100.0/rounds;\n\n delta :=0;\n sum := 0;\n For i := 0 to High(drawers) do\n Begin\n inc(sum,CntToPardoned[i]);\n dec(delta);\n IF delta <= 0 then\n Begin\n writeln(sum*factor:Digit+5:Digit,'% get pardoned checking max ',i+1);\n delta := delta+Length(drawers) DIV 10;\n end;\n end;\nend;\n\nprocedure OneCompareRun(PrisCnt:NativeInt);\nvar\n i,lmt :nativeInt;\nbegin\n PrisCount := PrisCnt;\n setlength(drawers,PrisCnt);\n For i := 0 to PrisCnt-1 do\n drawers[i] := i;\n setlength(Visited,PrisCnt);\n setlength(CntToPardoned,PrisCnt);\n //test\n writeln('Checking ',PrisCnt,' prisoners for ',rounds,' rounds');\n lmt := PrisCnt;\n CheckOptimized(lmt);\n writeln;\n\n setlength(CntToPardoned,0);\n setlength(Visited,0);\n setlength(drawers,0);\nend;\n\nBegin\n randomize;\n OneCompareRun(10);\n OneCompareRun(100);\n OneCompareRun(1000);\nend.\n", "safe": true }, { "filename": "100_prisoners_113.txt", "content": "Checking 10 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.2584% get pardoned checking max 2\n 4.7431% get pardoned checking max 3\n 17.4409% get pardoned checking max 4\n 35.4983% get pardoned checking max 5\n 52.1617% get pardoned checking max 6\n 66.4807% get pardoned checking max 7\n 78.9761% get pardoned checking max 8\n 90.0488% get pardoned checking max 9\n 100.0000% get pardoned checking max 10\n\nChecking 100 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.0000% get pardoned checking max 10\n 0.0459% get pardoned checking max 20\n 2.5996% get pardoned checking max 30\n 13.5071% get pardoned checking max 40\n 31.2258% get pardoned checking max 50\n 49.3071% get pardoned checking max 60\n 64.6128% get pardoned checking max 70\n 77.8715% get pardoned checking max 80\n 89.5385% get pardoned checking max 90\n 100.0000% get pardoned checking max 100\n\nChecking 1000 prisoners for 1000000 rounds\n 0.0000% get pardoned checking max 1\n 0.0000% get pardoned checking max 100\n 0.0374% get pardoned checking max 200\n 2.3842% get pardoned checking max 300\n 13.1310% get pardoned checking max 400\n 30.7952% get pardoned checking max 500\n 48.9710% get pardoned checking max 600\n 64.3555% get pardoned checking max 700\n 77.6950% get pardoned checking max 800\n 89.4515% get pardoned checking max 900\n 100.0000% get pardoned checking max 1000\n\nreal 0m9,975s", "safe": true }, { "filename": "100_prisoners_114.txt", "content": "use strict;\nuse warnings;\nuse feature 'say';\nuse List::Util 'shuffle';\n\nsub simulation {\n my($population,$trials,$strategy) = @_;\n my $optimal = $strategy =~ /^o/i ? 1 : 0;\n my @prisoners = 0..$population-1;\n my $half = int $population / 2;\n my $pardoned = 0;\n\n for (1..$trials) {\n my @drawers = shuffle @prisoners;\n my $total = 0;\n for my $prisoner (@prisoners) {\n my $found = 0;\n if ($optimal) {\n my $card = $drawers[$prisoner];\n if ($card == $prisoner) {\n $found = 1;\n } else {\n for (1..$half-1) {\n $card = $drawers[$card];\n ($found = 1, last) if $card == $prisoner\n }\n }\n } else {\n for my $card ( (shuffle @drawers)[0..$half]) {\n ($found = 1, last) if $card == $prisoner\n }\n }\n last unless $found;\n $total++;\n }\n $pardoned++ if $total == $population;\n }\n $pardoned / $trials * 100\n}\n\nmy $population = 100;\nmy $trials = 10000;\nsay \" Simulation count: $trials\\n\" .\n(sprintf \" Random strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'random' ) .\n(sprintf \"Optimal strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'optimal');\n\n$population = 10;\n$trials = 100000;\nsay \" Simulation count: $trials\\n\" .\n(sprintf \" Random strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'random' ) .\n(sprintf \"Optimal strategy pardons: %6.3f%% of simulations\\n\", simulation $population, $trials, 'optimal');\n", "safe": true }, { "filename": "100_prisoners_115.txt", "content": " Simulation count: 10000\n Random strategy pardons: 0.000% of simulations\nOptimal strategy pardons: 31.510% of simulations\n\n Simulation count: 1000000\n Random strategy pardons: 0.099% of simulations\nOptimal strategy pardons: 35.420% of simulations", "safe": true }, { "filename": "100_prisoners_116.txt", "content": "(de shuffle (Lst)\n (by '(NIL (rand)) sort Lst) )\n\n# Extend this class with a `next-guess>` method and a `str>` method.\n(class +Strategy +Entity)\n(dm prev-drawer> (Num)\n (=: prev Num) )\n\n(class +Random +Strategy)\n(dm T (Prisoner)\n (=: guesses (nth (shuffle (range 1 100)) 51)) )\n(dm next-guess> ()\n (pop (:: guesses)) )\n(dm str> ()\n \"Random\" )\n\n(class +Optimal +Strategy)\n(dm T (Prisoner)\n (=: prisoner-id Prisoner) )\n(dm next-guess> ()\n (or (: prev) (: prisoner-id)) )\n(dm str> ()\n \"Optimal/Wikipedia\" )\n\n\n(de test-strategy (Strategy)\n \"Simulate one round of 100 prisoners who use `Strategy`\"\n (let Drawers (shuffle (range 1 100))\n (for Prisoner (range 1 100)\n (NIL # Break and return NIL if any prisoner fails their test.\n (let Strat (new (list Strategy) Prisoner)\n (do 50 # Try 50 iterations of `Strat`. Break and return T iff success.\n (T (= Prisoner (prev-drawer> Strat (get Drawers (next-guess> Strat))))\n T ) ) ) )\n T ) ) )\n\n(de test-strategy-n-times (Strategy N)\n \"Simulate `N` rounds of 100 prisoners who use `Strategy`\"\n (let Successes 0\n (do N\n (when (test-strategy Strategy)\n (inc 'Successes) ) )\n (prinl \"We have a \" (/ (* 100 Successes) N) \"% success rate with \" N \" trials.\")\n (prinl \"This is using the \" (str> Strategy) \" strategy.\") ) )", "safe": true }, { "filename": "100_prisoners_117.txt", "content": "(test-strategy-n-times '+Random 10000)\n(test-strategy-n-times '+Optimal 10000)", "safe": true }, { "filename": "100_prisoners_118.txt", "content": "We have a 0% success rate with 10000 trials.\nThis is using the Random strategy.\nWe have a 31% success rate with 10000 trials.\nThis is using the Optimal/Wikipedia strategy.", "safe": true }, { "filename": "100_prisoners_119.txt", "content": "function play(integer prisoners, iterations, bool optimal)\n sequence drawers = shuffle(tagset(prisoners))\n integer pardoned = 0\n bool found = false\n for i=1 to iterations do\n drawers = shuffle(drawers)\n for prisoner=1 to prisoners do\n found = false\n integer drawer = iff(optimal?prisoner:rand(prisoners))\n for j=1 to prisoners/2 do\n drawer = drawers[drawer]\n if drawer==prisoner then found = true exit end if\n if not optimal then drawer = rand(prisoners) end if\n end for\n if not found then exit end if\n end for\n pardoned += found\n end for\n return 100*pardoned/iterations\nend function\n \nconstant iterations = 100_000\nprintf(1,\"Simulation count: %d\\n\",iterations)\nfor prisoners in {10,100} do\n atom random = play(prisoners,iterations,false),\n optimal = play(prisoners,iterations,true)\n printf(1,\"Prisoners:%d, random:%g, optimal:%g\\n\",{prisoners,random,optimal})\nend for\n", "safe": true }, { "filename": "100_prisoners_12.txt", "content": "2023 3 26 17 43 32 983\n>>>>>\n0 0.307\n>>>>>\n2023 3 26 17 53 48 531\n", "safe": true }, { "filename": "100_prisoners_120.txt", "content": "Simulation count: 100000\nPrisoners:10, random:0.006, optimal:35.168\nPrisoners:100, random:0, optimal:31.098\n", "safe": true }, { "filename": "100_prisoners_121.txt", "content": "/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners\nby Galileo, 05/2022 #/\n\ninclude ..\\Utilitys.pmt\n\ndef random rand * 1 + int enddef\n\ndef shuffle\n len var l\n l for var a\n l random var b\n b get var p\n a get b set\n p a set\n endfor\nenddef\n\ndef play var optimal var iterations var prisoners\n 0 var pardoned\n\n ( prisoners for endfor )\n \n iterations for drop\n shuffle\n prisoners for var prisoner\n false var found\n optimal if prisoner else prisoners random endif\n prisoners 2 / int for drop\n get dup prisoner == if true var found exitfor\n else\n optimal not if drop prisoners random endif\n endif\n endfor\n found not if exitfor endif\n drop\n endfor\n pardoned found + var pardoned\n endfor\n drop\n pardoned 100 * iterations /\nenddef\n\n\"Please, be patient ...\"\u00a0?\n\n( \"Optimal: \" 100 10000 true play\n \" Random: \" 100 10000 false play\n \" Prisoners: \" prisoners ) lprint", "safe": true }, { "filename": "100_prisoners_122.txt", "content": "Please, be patient ...\nOptimal: 31.65 Random: 0 Prisoners: 100\n=== Press any key to exit ===", "safe": true }, { "filename": "100_prisoners_123.txt", "content": "100H:\n/* PARAMETERS */\nDECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */\nDECLARE N$ATTEMPTS LITERALLY '50'; /* ATTEMPTS PER PRISONER */\nDECLARE N$SIMS LITERALLY '2000'; /* N. OF SIMULATIONS TO RUN */ \nDECLARE RAND$SEED LITERALLY '193'; /* RANDOM SEED */\n\n/* CP/M CALLS */\nBDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;\nEXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;\nPRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;\n\n/* PRINT NUMBER */\nPRINT$NUMBER: PROCEDURE (N);\n DECLARE S (6) BYTE INITIAL ('.....$');\n DECLARE (P, N) ADDRESS, C BASED P BYTE;\n P = .S(5);\nDIGIT:\n P = P - 1;\n C = N MOD 10 + '0';\n N = N / 10;\n IF N > 0 THEN GO TO DIGIT;\n CALL PRINT(P);\nEND PRINT$NUMBER;\n\n/* RANDOM NUMBER GENERATOR */\nRAND$BYTE: PROCEDURE BYTE;\n DECLARE (X, A, B, C) BYTE \n INITIAL (RAND$SEED, RAND$SEED, RAND$SEED, RAND$SEED);\n X = X+1;\n A = A XOR C XOR X;\n B = B+A;\n C = C+SHR(B,1)+A;\n RETURN C;\nEND RAND$BYTE;\n\n/* GENERATE RANDOM NUMBER FROM 0 TO MAX */\nRAND$MAX: PROCEDURE (MAX) BYTE;\n DECLARE (X, R, MAX) BYTE;\n X = 1;\n DO WHILE X < MAX;\n X = SHL(X,1);\n END;\n X = X-1;\n DO WHILE 1;\n R = RAND$BYTE AND X;\n IF R < MAX THEN RETURN R;\n END;\nEND RAND$MAX;\n\n/* PLACE CARDS RANDOMLY IN DRAWERS */\nINIT$DRAWERS: PROCEDURE (DRAWERS);\n DECLARE DRAWERS ADDRESS, (D BASED DRAWERS, I, J, K) BYTE;\n DO I=0 TO N$DRAWERS-1;\n D(I) = I;\n END;\n DO I=0 TO N$DRAWERS-1;\n J = I + RAND$MAX(N$DRAWERS-I);\n K = D(I);\n D(I) = D(J);\n D(J) = K;\n END;\nEND INIT$DRAWERS;\n\n/* PRISONER OPENS RANDOM DRAWERS */\nRANDOM$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;\n DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;\n DECLARE (P, I, TRIES) BYTE;\n \n /* KEEP TRACK OF WHICH DRAWERS HAVE BEEN OPENED */\n DECLARE OPEN (N$DRAWERS) BYTE;\n DO I=0 TO N$DRAWERS-1;\n OPEN(I) = 0;\n END;\n \n /* OPEN RANDOM DRAWERS */\n TRIES = N$ATTEMPTS;\n DO WHILE TRIES > 0;\n IF NOT OPEN(I\u00a0:= RAND$MAX(N$DRAWERS)) THEN DO;\n /* IF WE FIND OUR NUMBER, SUCCESS */\n IF D(I) = P THEN RETURN 1;\n OPEN(I) = 1; \n TRIES = TRIES - 1;\n END;\n END;\n \n RETURN 0; /* WE DID NOT FIND OUR NUMBER */\nEND RANDOM$STRATEGY;\n\n/* PRISONER USES OPTIMAL STRATEGY */\nOPTIMAL$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;\n DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;\n DECLARE (P, I, TRIES) BYTE;\n TRIES = N$ATTEMPTS;\n I = P;\n DO WHILE TRIES > 0;\n I = D(I); /* OPEN DRAWER W/ CURRENT NUMBER */\n IF I = P THEN RETURN 1; /* DID WE FIND IT? */\n TRIES = TRIES - 1;\n END;\n RETURN 0;\nEND OPTIMAL$STRATEGY;\n\n/* RUN A SIMULATION */\nDECLARE RANDOM LITERALLY '0';\nDECLARE OPTIMAL LITERALLY '1';\nSIMULATE: PROCEDURE (STRAT) BYTE;\n DECLARE (STRAT, P, R) BYTE;\n \n /* PLACE CARDS IN DRAWERS */\n DECLARE DRAWERS (N$DRAWERS) BYTE;\n CALL INIT$DRAWERS(.DRAWERS);\n \n /* TRY EACH PRISONER */\n DO P=0 TO N$DRAWERS-1;\n DO CASE STRAT;\n R = RANDOM$STRATEGY(.DRAWERS, P);\n R = OPTIMAL$STRATEGY(.DRAWERS, P);\n END;\n \n /* IF ONE PRISONER FAILS THEY ALL HANG */\n IF NOT R THEN RETURN 0;\n END;\n \n RETURN 1; /* IF THEY ALL SUCCEED NONE HANG */\nEND SIMULATE;\n\n/* RUN MANY SIMULATIONS AND COUNT THE SUCCESSES */\nRUN$SIMULATIONS: PROCEDURE (N, STRAT) ADDRESS;\n DECLARE STRAT BYTE, (I, N, SUCC) ADDRESS;\n SUCC = 0;\n DO I=1 TO N;\n SUCC = SUCC + SIMULATE(STRAT);\n END;\n RETURN SUCC;\nEND RUN$SIMULATIONS;\n\n/* RUN AND PRINT SIMULATIONS */\nRUN$AND$PRINT: PROCEDURE (NAME, STRAT, N);\n DECLARE (NAME, N, S) ADDRESS, STRAT BYTE;\n CALL PRINT(NAME);\n CALL PRINT(.' STRATEGY: $');\n S = RUN$SIMULATIONS(N, STRAT);\n CALL PRINT$NUMBER(S);\n CALL PRINT(.' OUT OF $');\n CALL PRINT$NUMBER(N);\n CALL PRINT(.' - $');\n CALL PRINT$NUMBER( S*10 / (N/10) );\n CALL PRINT(.(37,13,10,'$'));\nEND RUN$AND$PRINT;\n\nCALL RUN$AND$PRINT(.'RANDOM$', RANDOM, N$SIMS);\nCALL RUN$AND$PRINT(.'OPTIMAL$', OPTIMAL, N$SIMS);\nCALL EXIT;\nEOF", "safe": true }, { "filename": "100_prisoners_124.txt", "content": "RANDOM STRATEGY: 0 OUT OF 2000 - 0%\nOPTIMAL STRATEGY: 653 OUT OF 2000 - 32%", "safe": true }, { "filename": "100_prisoners_125.txt", "content": "optimalSeq(drawers, n) =\n iterate(ind => drawers[ind - 1], n)\n |> takeUntil(ind => drawers[ind - 1] == n)\n\noptimalTrial(drawers) =\n range(1, 100)\n |> map(optimalSeq(drawers))\n\nrandomSeq(drawers, n) =\n iterate(ind => randRange(1, 100), randRange(1, 100))\n |> takeUntil(ind => drawers[ind - 1] == n)\n\nrandomTrial(drawers) =\n range(1, 100)\n |> map(randomSeq(drawers))\n\ncheckLength(seq) =\n length(take(51, seq)) <= 50\n\nnumTrials = 3000\n\nrunTrials(trialFunc) =\n for t in range(1, numTrials)\n yield\n range(1, 100)\n |> shuffle\n |> toArray\n |> trialFunc\n |> map(checkLength)\n |> all\n\ncountSuccess(trialFunc) =\n runTrials(trialFunc)\n |> filter(id)\n |> length\n\noptimalCount = countSuccess(optimalTrial)\nrandomCount = countSuccess(randomTrial)\n\noutput =\n format(\"optimal: {} / {} = {} prob\\nrandom: {} / {} = {} prob\", [\n optimalCount, numTrials, optimalCount / numTrials,\n randomCount, numTrials, randomCount / numTrials,\n ])\n |> println\n", "safe": true }, { "filename": "100_prisoners_126.txt", "content": "optimal: 923 / 3000 = 0.30766666666666664 prob\nrandom: 0 / 3000 = 0.0 prob", "safe": true }, { "filename": "100_prisoners_127.txt", "content": "### Clear Screen from old Output\nClear-Host\n\nFunction RandomOpening () \n {\n $Prisoners = 1..100 | Sort-Object {Get-Random}\n $Cupboard = 1..100 | Sort-Object {Get-Random}\n ## Loop for the Prisoners\n $Survived = $true\n for ($I=1;$I -le 100;$i++)\n {\n $OpeningListe = 1..100 | Sort-Object {Get-Random}\n $Gefunden = $false\n ## Loop for the trys of every prisoner\n for ($X=1;$X -le 50;$X++)\n {\n $OpenNumber = $OpeningListe[$X]\n IF ($Cupboard[$OpenNumber] -eq $Prisoners[$I])\n {\n $Gefunden = $true\n }\n ## Cancel loop if prisoner found his number (yeah i know, dirty way ^^ ) \n IF ($Gefunden)\n {\n $X = 55\n }\n }\n IF ($Gefunden -eq $false)\n {\n $I = 120\n $Survived = $false\n } \n }\n Return $Survived\n }\n\n Function StrategyOpening () \n {\n $Prisoners = 1..100 | Sort-Object {Get-Random}\n $Cupboard = 1..100 | Sort-Object {Get-Random}\n $Survived = $true\n for ($I=1;$I -le 100;$i++)\n {\n $Gefunden = $false\n $OpeningNumber = $Prisoners[$I-1]\n for ($X=1;$X -le 50;$X++)\n {\n IF ($Cupboard[$OpeningNumber-1] -eq $Prisoners[$I-1])\n {\n $Gefunden = $true\n }\n else \n {\n $OpeningNumber = $Cupboard[$OpeningNumber-1] \n } \n IF ($Gefunden)\n {\n $X = 55\n }\n }\n IF ($Gefunden -eq $false)\n {\n $I = 120\n $Survived = $false\n } \n }\n Return $Survived\n }\n\n$MaxRounds = 10000\n\nFunction TestRandom\n {\n $WinnerRandom = 0\n for ($Round = 1; $Round -le $MaxRounds;$Round++)\n {\n IF (($Round%1000) -eq 0)\n {\n $Time = Get-Date\n Write-Host \"Currently we are at rount $Round at $Time\"\n }\n $Rueckgabewert = RandomOpening\n IF ($Rueckgabewert)\n {\n $WinnerRandom++\n }\n }\n \n $Prozent = (100/$MaxRounds)*$WinnerRandom\n Write-Host \"There are $WinnerRandom survivors whit random opening. This is $Prozent percent\"\n }\n\nFunction TestStrategy\n {\n $WinnersStrategy = 0 \n for ($Round = 1; $Round -le $MaxRounds;$Round++)\n {\n IF (($Round%1000) -eq 0)\n {\n $Time = Get-Date\n Write-Host \"Currently we are at $Round at $Time\"\n }\n $Rueckgabewert = StrategyOpening\n IF ($Rueckgabewert)\n {\n $WinnersStrategy++\n }\n }\n \n $Prozent = (100/$MaxRounds)*$WinnersStrategy\n Write-Host \"There are $WinnersStrategy survivors whit strategic opening. This is $Prozent percent\"\n }\n\nFunction Main () \n {\n Clear-Host\n TestRandom\n TestStrategy\n }\n\nMain\n", "safe": true }, { "filename": "100_prisoners_128.txt", "content": "# of executions: 10000\nThere are 0 survivors whit random opening. This is 0 percent\nThere are 3104 survivors whit strategic opening. This is 31,04 percent\"\n", "safe": true }, { "filename": "100_prisoners_129.txt", "content": "IntList drawers = new IntList();\nint trials = 100000;\nint succes_count;\n\nvoid setup() {\n for (int i = 0; i < 100; i++) {\n drawers.append(i);\n }\n println(trials + \" trials\\n\");\n\n //Random strategy\n println(\"Random strategy\");\n succes_count = trials;\n for (int i = 0; i < trials; i++) {\n drawers.shuffle();\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n boolean found = false;\n for (int attempt = 0; attempt < 50; attempt++) {\n if (drawers.get(int(random(drawers.size()))) == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n succes_count--;\n break;\n }\n }\n }\n println(\" Succeses: \" + succes_count);\n println(\" Succes rate: \" + 100.0 * succes_count / trials + \"%\\n\");\n\n //Optimal strategy\n println(\"Optimal strategy\");\n succes_count = trials;\n for (int i = 0; i < trials; i++) {\n drawers.shuffle();\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n boolean found = false;\n int next = prisoner;\n for (int attempt = 0; attempt < 50; attempt++) {\n next = drawers.get(next);\n if (next == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n succes_count--;\n break;\n }\n }\n }\n println(\" Succeses: \" + succes_count);\n print(\" Succes rate: \" + 100.0 * succes_count / trials + \"%\");\n}", "safe": true }, { "filename": "100_prisoners_13.txt", "content": "0 GOTO 9\n\n1 FOR X = 0 TO N:J(X) = X: NEXT: FOR I = 0 TO N:FOR X = 0 TO N:T = J(X):NP = INT ( RND (1) * H):J(X) = J(NP):J(NP) = T: NEXT :FOR G = 1 TO W:IF D(J(G)) = I THEN IP = IP + 1: NEXT I: RETURN \n2 NEXT G:RETURN \n\n3 FOR I = 0 TO N:NG = I: FOR G = 0 TO W:CD = D(NG):IF CD = I THEN IP = IP + 1: NEXT I: RETURN \n4 NG = CD:IF CD = I THEN STOP\n5 NEXT G: RETURN \n\n9 H=100:N=H-1:DIM D(99),J(99):FOR I = 0 TO N:D(I) = I: NEXT:W=INT(H/2)-1:M$=CHR$(13):M$(1)=\"RANDOM GUESSING\":M$(2)=\"CHAINED NUMBER PICKING\"\n\n1000 FOR Q = 0 TO 1 STEP 0 : HOME : PRINT \"100 PRISONERS\"M$: INPUT \"HOW MANY TRIALS FOR EACH METHOD? \"; TT\n1010 VTAB 2:CALL-958:PRINT M$\"RESULTS:\"M$\n1020 FOR M = 1 TO 2: SU(M) = 0:FA(M) = 0\n1030 FOR TN = 1 TO TT\n1040 VTAB 4:PRINT M$ \" OUT OF \" TT \" TRIALS, THE RESULTS ARE\"M$\" AS FOLLOWS...\";\n1050 IP = 0: X = RND ( - TI): FOR I = 0 TO N:R = INT ( RND (1) * N):T = D(I):D(I) = D(R):D(R) = T: NEXT\n1060 ON M GOSUB 1,3 : SU(M) = SU(M) + (IP = H):FA(M) = FA(M) + (IP < H)\n1070 FOR Z = 1 TO 2\n1071 PRINT M$M$Z\". \"M$(Z)\":\"M$\n1073 PRINT \" \"SU(Z)\" SUCCESSES\"TAB(21)\n1074 PRINT \" \"FA(Z)\" FAILURES\"M$\n1075 PRINT \" \"(SU(Z) / TT) * 100\"% SUCCESS RATE.\";:CALL-868\n1090 NEXT Z,TN,M\n\n1100 PRINT M$M$\"AGAIN?\"\n1110 GET K$\n1120 Q = K$ <> \"Y\" AND K$ <> CHR$(ASC(\"Y\") + 32) : NEXT Q\n", "safe": true }, { "filename": "100_prisoners_130.txt", "content": "100000 trials\n\nRandom strategy\n Succeses: 0\n Succes rate: 0.0%\n\nOptimal strategy\n Succeses: 31134\n Succes rate: 31.134%", "safe": true }, { "filename": "100_prisoners_131.txt", "content": "#PRISONERS=100\n#DRAWERS =100\n#LOOPS = 50\n#MAXPROBE = 10000\nOpenConsole()\n\nDim p1(#PRISONERS,#DRAWERS)\nDim p2(#PRISONERS,#DRAWERS)\nDim d(#DRAWERS)\n\nFor i=1 To #DRAWERS : d(i)=i : Next\nStart:\nFor probe=1 To #MAXPROBE\n RandomizeArray(d(),1,100)\n c1=0 : c2=0 \n For m=1 To #PRISONERS\n p2(m,1)=d(m) : If d(m)=m : p2(m,0)=1 : EndIf\n For n=1 To #LOOPS\n p1(m,n)=d(Random(100,1))\n If p1(m,n)=m : p1(m,0)=1 : EndIf\n If n>1 : p2(m,n)=d(p2(m,n-1)) : If p2(m,n)=m : p2(m,0)=1 : EndIf : EndIf\n Next n\n Next m\n \n For m=1 To #PRISONERS\n If p1(m,0) : c1+1 : p1(m,0)=0 : EndIf \n If p2(m,0) : c2+1 : p2(m,0)=0 : EndIf\n Next m\n \n If c1=#PRISONERS : w1+1 : EndIf\n If c2=#PRISONERS : w2+1 : EndIf\nNext probe\nPrint(\"TRIALS: \"+Str(#MAXPROBE))\nPrint(\" RANDOM= \"+StrF(100*w1/#MAXPROBE,2)+\"% STATEGY= \"+StrF(100*w2/#MAXPROBE,2)+\"%\")\nPrintN(~\"\\tFIN =q.\") : inp$=Input()\nw1=0 : w2=0\nIf inp$<>\"q\" : Goto Start : EndIf\n", "safe": true }, { "filename": "100_prisoners_132.txt", "content": "TRIALS: 10000 RANDOM= 0.00% STATEGY= 30.83%\tFIN =q.\n\nTRIALS: 10000 RANDOM= 0.00% STATEGY= 31.60%\tFIN =q.\n\nTRIALS: 10000 RANDOM= 0.00% STATEGY= 31.20%\tFIN =q.", "safe": true }, { "filename": "100_prisoners_133.txt", "content": "import random\n\ndef play_random(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n sampler = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n found = False\n for prisoner in range(100):\n found = False\n for reveal in random.sample(sampler, 50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 #\u00a0%\n\ndef play_optimal(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n for prisoner in range(100):\n reveal = prisoner\n found = False\n for go in range(50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n reveal = card\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 #\u00a0%\n\nif __name__ == '__main__':\n n = 100_000\n print(\" Simulation count:\", n)\n print(f\" Random play wins: {play_random(n):4.1f}% of simulations\")\n print(f\"Optimal play wins: {play_optimal(n):4.1f}% of simulations\")\n", "safe": true }, { "filename": "100_prisoners_134.txt", "content": " Simulation count: 100000\n Random play wins: 0.0% of simulations\nOptimal play wins: 31.1% of simulations", "safe": true }, { "filename": "100_prisoners_135.txt", "content": "# http://rosettacode.org/wiki/100_prisoners\n\nimport random\n\n\ndef main():\n NUM_DRAWERS = 10\n NUM_REPETITIONS = int(1E5)\n\n print('{:15}: {:5} ({})'.format('approach', 'wins', 'ratio'))\n for approach in PrisionersGame.approaches:\n num_victories = 0\n for _ in range(NUM_REPETITIONS):\n game = PrisionersGame(NUM_DRAWERS)\n num_victories += PrisionersGame.victory(game.play(approach))\n\n print('{:15}: {:5} ({:.2%})'.format(\n approach.__name__, num_victories, num_victories / NUM_REPETITIONS))\n\n\nclass PrisionersGame:\n \"\"\"docstring for PrisionersGame\"\"\"\n def __init__(self, num_drawers):\n assert num_drawers % 2 == 0\n self.num_drawers = num_drawers\n self.max_attempts = int(self.num_drawers / 2)\n self.drawer_ids = list(range(1, num_drawers + 1))\n shuffled = self.drawer_ids[:]\n random.shuffle(shuffled)\n self.drawers = dict(zip(self.drawer_ids, shuffled))\n\n def play_naive(self, player_number):\n \"\"\" Randomly open drawers \"\"\"\n for attempt in range(self.max_attempts):\n if self.drawers[random.choice(self.drawer_ids)] == player_number:\n return True\n\n return False\n\n def play_naive_mem(self, player_number):\n \"\"\" Randomly open drawers but avoiding repetitions \"\"\"\n not_attemped = self.drawer_ids[:]\n for attempt in range(self.max_attempts):\n guess = random.choice(not_attemped)\n not_attemped.remove(guess)\n\n if self.drawers[guess] == player_number:\n return True\n\n return False\n\n def play_optimum(self, player_number):\n \"\"\" Open the drawer that matches the player number and then open the drawer\n with the revealed number.\n \"\"\"\n prev_attempt = player_number\n for attempt in range(self.max_attempts):\n if self.drawers[prev_attempt] == player_number:\n return True\n else:\n prev_attempt = self.drawers[prev_attempt]\n\n return False\n\n @classmethod\n def victory(csl, results):\n \"\"\"Defines a victory of a game: all players won\"\"\"\n return all(results)\n\n approaches = [play_naive, play_naive_mem, play_optimum]\n\n def play(self, approach):\n \"\"\"Plays this game and returns a list of booleans with\n True if a player one, False otherwise\"\"\"\n return [approach(self, player) for player in self.drawer_ids]\n\n\nif __name__ == '__main__':\n main()\n", "safe": true }, { "filename": "100_prisoners_136.txt", "content": "With 10 drawers (100k runs)\napproach \u00a0: wins (ratio)\nplay_naive \u00a0: 14 (0.01%)\nplay_naive_mem\u00a0: 74 (0.07%)\nplay_optimum \u00a0: 35410 (35.41%)\n\nWith 100 drawers (10k runs)\napproach \u00a0: wins (ratio)\nplay_naive \u00a0: 0 (0.00%)\nplay_naive_mem\u00a0: 0 (0.00%)\nplay_optimum \u00a0: 3084 (30.84%)", "safe": true }, { "filename": "100_prisoners_137.txt", "content": "'''100 Prisoners'''\n\nfrom random import randint, sample\n\n\n# allChainedPathsAreShort\u00a0:: Int -> IO (0|1)\ndef allChainedPathsAreShort(n):\n '''1 if none of the index-chasing cycles in a shuffled\n sample of [1..n] cards are longer than half the\n sample size. Otherwise, 0.\n '''\n limit = n // 2\n xs = range(1, 1 + n)\n shuffled = sample(xs, k=n)\n\n # A cycle of boxes, drawn from a shuffled\n # sample, which includes the given target.\n def cycleIncluding(target):\n boxChain = [target]\n v = shuffled[target - 1]\n while v != target:\n boxChain.append(v)\n v = shuffled[v - 1]\n return boxChain\n\n # Nothing if the target list is empty, or if the cycle which contains the\n # first target is larger than half the sample size.\n # Otherwise, just a cycle of enchained boxes containing the first target\n # in the list, tupled with the residue of any remaining targets which\n # fall outside that cycle.\n def boxCycle(targets):\n if targets:\n boxChain = cycleIncluding(targets[0])\n return Just((\n difference(targets[1:])(boxChain),\n boxChain\n )) if limit >= len(boxChain) else Nothing()\n else:\n return Nothing()\n\n # No cycles longer than half of total box count\u00a0?\n return int(n == sum(map(len, unfoldr(boxCycle)(xs))))\n\n\n# randomTrialResult\u00a0:: RandomIO (0|1) -> Int -> (0|1)\ndef randomTrialResult(coin):\n '''1 if every one of the prisoners finds their ticket\n in an arbitrary half of the sample. Otherwise 0.\n '''\n return lambda n: int(all(\n coin(x) for x in range(1, 1 + n)\n ))\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n '''Two sampling techniques constrasted with 100 drawers\n and 100 prisoners, over 100,000 trial runs.\n '''\n halfOfDrawers = randomRInt(0)(1)\n\n def optimalDrawerSampling(x):\n return allChainedPathsAreShort(x)\n\n def randomDrawerSampling(x):\n return randomTrialResult(halfOfDrawers)(x)\n\n # kSamplesWithNBoxes\u00a0:: Int -> Int -> String\n def kSamplesWithNBoxes(k):\n tests = range(1, 1 + k)\n return lambda n: '\\n\\n' + fTable(\n str(k) + ' tests of optimal vs random drawer-sampling ' +\n 'with ' + str(n) + ' boxes: \\n'\n )(fName)(lambda r: '{:.2%}'.format(r))(\n lambda f: sum(f(n) for x in tests) / k\n )([\n optimalDrawerSampling,\n randomDrawerSampling,\n ])\n\n print(kSamplesWithNBoxes(10000)(10))\n\n print(kSamplesWithNBoxes(10000)(100))\n\n print(kSamplesWithNBoxes(100000)(100))\n\n\n# ------------------------DISPLAY--------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# fname\u00a0:: (a -> b) -> String\ndef fName(f):\n '''Name bound to the given function.'''\n return f.__name__\n\n\n# ------------------------GENERIC -------------------------\n\n# Just\u00a0:: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing\u00a0:: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# difference\u00a0:: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of xs, except any also found in ys.'''\n return lambda ys: list(set(xs) - set(ys))\n\n\n# randomRInt\u00a0:: Int -> Int -> IO () -> Int\ndef randomRInt(m):\n '''The return value of randomRInt is itself\n a function. The returned function, whenever\n called, yields a a new pseudo-random integer\n in the range [m..n].\n '''\n return lambda n: lambda _: randint(m, n)\n\n\n# unfoldr(lambda x: Just((x, x - 1)) if 0\u00a0!= x else Nothing())(10)\n# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n# unfoldr\u00a0:: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns Just(a, b), a is prepended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n xr = v, v\n xs = []\n while True:\n mb = f(xr[0])\n if mb.get('Nothing'):\n return xs\n else:\n xr = mb.get('Just')\n xs.append(xr[1])\n return xs\n return lambda x: go(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "safe": true }, { "filename": "100_prisoners_138.txt", "content": "10000 tests of optimal vs random drawer-sampling with 10 boxes: \n\noptimalDrawerSampling -> 35.47%\n randomDrawerSampling -> 0.09%\n\n10000 tests of optimal vs random drawer-sampling with 100 boxes: \n\noptimalDrawerSampling -> 30.40%\n randomDrawerSampling -> 0.00%\n\n100000 tests of optimal vs random drawer-sampling with 100 boxes: \n\noptimalDrawerSampling -> 31.17%\n randomDrawerSampling -> 0.00%", "safe": true }, { "filename": "100_prisoners_139.txt", "content": "t = 100000 #number of trials\nsuccess.r = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the random method\nsuccess.o = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the optimal method\n\n#random method\nfor(i in 1:t){\n escape = rep(F,100)\n ticket = sample(1:100)\n for(j in 1:length(prisoner)){\n escape[j] = j %in% sample(ticket,50)\n }\n success.r[i] = sum(escape)\n}\n\n#optimal method\nfor(i in 1:t){\n escape = rep(F,100)\n ticket = sample(1:100)\n for(j in 1:100){\n boxes = 0\n current.box = j\n while(boxes<50 && !escape[j]){\n boxes=boxes+1\n escape[j] = ticket[current.box]==j\n current.box = ticket[current.box]\n }\n }\n success.o[i] = sum(escape)\n}\n\ncat(\"Random method resulted in a success rate of \",100*mean(success.r==100),\n \"%.\\nOptimal method resulted in a success rate of \",100*mean(success.o==100),\"%.\",sep=\"\")\n", "safe": true }, { "filename": "100_prisoners_14.txt", "content": "100 PRISONERS\n\nRESULTS:\n\n OUT OF 4000 TRIALS, THE RESULTS ARE\n AS FOLLOWS...\n\n1. RANDOM GUESSING:\n\n 0 SUCCESSES 4000 FAILURES\n\n 0% SUCCESS RATE.\n\n2. CHAINED NUMBER PICKING:\n\n 1278 SUCCESSES 2722 FAILURES\n\n 31.95% SUCCESS RATE.\n", "safe": true }, { "filename": "100_prisoners_140.txt", "content": "Random method resulted in a success rate of 0%.\nOptimal method resulted in a success rate of 31.129%.", "safe": true }, { "filename": "100_prisoners_141.txt", "content": "Const Found = -1, Searching = 0, Status = 1, Tries = 2\nConst Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2\nRandomize Timer\n\nDim Shared Prisoners(1 To 100, Status To Tries) As Integer, Drawers(1 To 100) As Integer, Results(1 To 2, 1 To 2) As Integer\nPrint \"100 prisoners\"\nPrint \"Random way to search...\"\nFor a = 1 To 2000\n Init\n Results(RandomW, Attempt) = Results(RandomW, Attempt) + 1\n RandomWay\n If verify% Then Results(RandomW, Victories) = Results(RandomW, Victories) + 1\nNext\n\nPrint: Print \"Chain way to search...\"\nFor a = 1 To 2000\n Init\n Results(ChainW, Attempt) = Results(ChainW, Attempt) + 1\n ChainWay\n If verify% Then Results(ChainW, Victories) = Results(ChainW, Victories) + 1\nNext\nPrint: Print \"Results: \"\nPrint \" Attempts \"; Results(RandomW, Attempt); \" \"; \"Victories \"; Results(RandomW, Victories); \" Ratio:\"; Results(RandomW, Victories); \"/\"; Results(RandomW, Attempt)\nPrint\nPrint \" Attempts \"; Results(ChainW, Attempt); \" \"; \"Victories \"; Results(ChainW, Victories); \" Ratio:\"; Results(ChainW, Victories); \"/\"; Results(ChainW, Attempt)\nEnd\n\nFunction verify%\n Dim In As Integer\n Print \"veryfing \"\n verify = 0\n For In = 1 To 100\n If Prisoners(In, Status) = Searching Then Exit For\n Next\n If In = 101 Then verify% = Found\nEnd Function\n\nSub ChainWay\n Dim In As Integer, ChainChoice As Integer\n Print \"Chain search\"\n For In = 1 To 100\n ChainChoice = In\n Do\n Prisoners(In, Tries) = Prisoners(In, Tries) + 1\n If Drawers(ChainChoice) = In Then Prisoners(In, Status) = Found: Exit Do\n ChainChoice = Drawers(ChainChoice)\n Loop Until Prisoners(In, Tries) = 50\n Next In\nEnd Sub\n\nSub RandomWay\n Dim In As Integer, RndChoice As Integer\n Print \"Random search\"\n For In = 1 To 100\n Do\n Prisoners(In, Tries) = Prisoners(In, Tries) + 1\n If Drawers(Int(Rnd * 100) + 1) = In Then Prisoners(In, Status) = Found: Exit Do\n Loop Until Prisoners(In, Tries) = 50\n Next\n Print \"Executed \"\nEnd Sub\n\n\nSub Init\n Dim I As Integer, I2 As Integer\n Print \"initialization\"\n For I = 1 To 100\n Prisoners(I, Status) = Searching\n Prisoners(I, Tries) = Searching\n Do\n Drawers(I) = Int(Rnd * 100) + 1\n For I2 = 1 To I\n If Drawers(I2) = Drawers(I) Then Exit For\n Next\n If I2 = I Then Exit Do\n Loop\n Next I\n Print \"Done \"\nEnd Sub", "safe": true }, { "filename": "100_prisoners_142.txt", "content": " [ this ] is 100prisoners.qky\n\n [ dup size 2 / split ] is halve ( [ --> [ [ )\n\n [ stack ] is successes ( --> s )\n\n [ [] swap times [ i join ] shuffle ] is drawers ( n --> [ )\n\n [ false unrot\n temp put \n dup shuffle\n halve drop\n witheach\n [ dip dup peek\n temp share = if\n [ dip not\n conclude ] ]\n drop\n temp release ] is naive ( [ n --> b )\n\n [ false unrot \n dup temp put\n over size 2 / times \n [ dip dup peek\n dup temp share = if\n [ rot not unrot\n conclude ] ]\n 2drop\n temp release ] is smart ( [ n --> b )\n\n [ ]'[ temp put\n drawers\n 0 successes put\n dup size times \n [ dup i temp share do\n successes tally ]\n size successes take = \n temp release ] is prisoners ( n --> b )\n \n [ say \"100 naive prisoners were pardoned \"\n 0 10000 times [ 100 prisoners naive + ] echo\n say \" times out of 10000 simulations.\" cr\n\n say \"100 smart prisoners were pardoned \"\n 0 10000 times [ 100 prisoners smart + ] echo\n say \" times out of 10000 simulations.\" cr ] is simulate ( --> )", "safe": true }, { "filename": "100_prisoners_143.txt", "content": "/O> [ $ '100prisoners.qky' loadfile ] now!\n... simulate\n... \n100 naive prisoners were pardoned 0 times out of 10000 simulations.\n100 smart prisoners were pardoned 3158 times out of 10000 simulations.\n\nStack empty.", "safe": true }, { "filename": "100_prisoners_144.txt", "content": "#lang racket\n(require srfi/1)\n\n(define current-samples (make-parameter 10000))\n(define *prisoners* 100)\n(define *max-guesses* 50)\n\n(define (evaluate-strategy instance-solved? strategy (s (current-samples)))\n (/ (for/sum ((_ s) #:when (instance-solved? strategy)) 1) s))\n\n(define (build-drawers)\n (list->vector (shuffle (range *prisoners*))))\n\n(define (100-prisoners-problem strategy)\n (every (strategy (build-drawers)) (range *prisoners*)))\n\n(define ((strategy-1 drawers) p)\n (any (\u03bb (_) (= p (vector-ref drawers (random *prisoners*)))) (range *max-guesses*)))\n\n(define ((strategy-2 drawers) p)\n (define-values (_ found?)\n (for/fold ((d p) (found? #f)) ((_ *max-guesses*)) #:break found?\n (let ((card (vector-ref drawers d))) (values card (= card p)))))\n found?)\n\n(define (print-sample-percentage caption f (s (current-samples)))\n (printf \"~a: ~a%~%\" caption (real->decimal-string (* 100 f) (- (order-of-magnitude s) 2))))\n\n(module+ main\n (print-sample-percentage \"random\" (evaluate-strategy 100-prisoners-problem strategy-1))\n (print-sample-percentage \"optimal\" (evaluate-strategy 100-prisoners-problem strategy-2)))\n", "safe": true }, { "filename": "100_prisoners_145.txt", "content": "random: 0.00%\noptimal: 31.18%", "safe": true }, { "filename": "100_prisoners_146.txt", "content": "unit sub MAIN (:$prisoners = 100,\u00a0:$simulations = 10000);\nmy @prisoners = ^$prisoners;\nmy $half = floor +@prisoners / 2;\n\nsub random ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n for @drawers.pick($half) -> $card {\n $found = 1 and last if $card == $prisoner\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsub optimal ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n my $card = @drawers[$prisoner];\n if $card == $prisoner {\n $found = 1\n } else {\n for ^($half - 1) {\n $card = @drawers[$card];\n $found = 1 and last if $card == $prisoner\n }\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsay \"Testing $simulations simulations with $prisoners prisoners.\";\nprintf \" Random play wins:\u00a0%.3f%% of simulations\\n\", random $simulations;\nprintf \"Optimal play wins:\u00a0%.3f%% of simulations\\n\", optimal $simulations;\n", "safe": true }, { "filename": "100_prisoners_147.txt", "content": "Testing 10000 simulations with 100 prisoners.\n Random play wins: 0.000% of simulations\nOptimal play wins: 30.510% of simulations", "safe": true }, { "filename": "100_prisoners_148.txt", "content": "Testing 100000 simulations with 10 prisoners.\n Random play wins: 0.099% of simulations\nOptimal play wins: 35.461% of simulations\n", "safe": true }, { "filename": "100_prisoners_149.txt", "content": "Red []\n\nK_runs: 100000\nrepeat n 100 [append rand_arr: [] n] ;; define array/series with numbers 1..100\n\n;;-------------------------------\nstrat_optimal: function [pris ][\n;;-------------------------------\n locker: pris ;; start with locker equal to prisoner number\n loop 50 [\n if Board/:locker = pris [ return true ] ;; locker with prisoner number found\n locker: Board/:locker\n ]\n false ;; number not found - fail\n]\n;;-------------------------------\nstrat_rand: function [pris ][\n;;-------------------------------\n random rand_arr ;; define set of random lockers\n repeat n 50 [ if Board/(rand_arr/:n) = pris [ return true ] ] ;; try first 50, found\u00a0? then return success\n false \n]\n\n;;------------------------------\ncheck_board: function [ strat][\n;;------------------------------\nrepeat pris 100 [ ;; for each prisoner\n either strat = 'optimal [ unless strat_optimal pris [return false ] ] \n [ unless strat_rand pris [return false ] ] \n] \n true ;; all 100 prisoners passed test\n]\n\nsaved: saved_rand: 0 ;; count all saved runs per strategy\nloop K_runs [\n Board: random copy rand_arr ;; new board for every run\n if check_board 'optimal [saved: saved + 1] ;; optimal stategy\n if check_board 'rand [saved_rand: saved_rand + 1] ;; random strategy\n]\n\nprint [\"runs\" k_runs newline \"Percent saved opt.strategy:\" saved * 100.0 / k_runs ]\nprint [\"Percent saved random strategy:\" saved_rand * 100.0 / k_runs ]\n", "safe": true }, { "filename": "100_prisoners_15.txt", "content": "/* ARM assembly Raspberry PI */\n/* program prisonniers.s */ \n\n/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include */\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n\n.equ NBDOORS, 100\n.equ NBLOOP, 1000\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"Random strategie \u00a0: @ sur 1000 \\n\"\nsMessResultOPT: .asciz \"Optimal strategie\u00a0: @ sur 1000 \\n\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\niGraine: .int 123456\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\ntbDoors: .skip 4 * NBDOORS \ntbTest: .skip 4 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n \n ldr r1,iAdrtbDoors\n mov r2,#0\n1: @ loop init doors table\n add r3,r2,#1\n str r3,[r1,r2,lsl #2]\n add r2,r2,#1\n cmp r2,#NBDOORS\n blt 1b\n \n mov r9,#0 @ loop counter\n mov r10,#0 @ counter successes random strategie\n mov r11,#0 @ counter successes optimal strategie\n2:\n ldr r0,iAdrtbDoors\n mov r1,#NBDOORS\n bl knuthShuffle\n \n ldr r0,iAdrtbDoors\n bl aleaStrategie\n cmp r0,#NBDOORS\n addeq r10,r10,#1\n \n ldr r0,iAdrtbDoors\n bl optimaStrategie\n cmp r0,#NBDOORS\n addeq r11,r11,#1\n \n add r9,r9,#1\n cmp r9,#NBLOOP\n blt 2b\n \n mov r0,r10 @ result display\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResult\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n mov r0,r11 @ result display\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResultOPT\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrsMessResultOPT: .int sMessResultOPT\niAdrtbDoors: .int tbDoors\niAdrtbTest: .int tbTest\niAdrsZoneConv: .int sZoneConv\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* r0 contains the address of table */\naleaStrategie:\n push {r1-r7,lr} @ save registers\n ldr r6,iAdrtbTest @ table doors tests address\n mov r1,r0 @ save table doors address\n mov r4,#0 @ counter number of successes\n mov r2,#0 @ prisonners indice\n1:\n bl razTable @ zero to table doors tests\n mov r5,#0 @ counter of door tests \n add r7,r2,#1\n2:\n mov r0,#NBDOORS - 1\n bl genereraleas @ random test\n add r0,r0,#1\n ldr r3,[r6,r0,lsl #2] @ doors also tested\u00a0?\n cmp r3,#0 \n bne 2b @ yes\n ldr r3,[r1,r0,lsl #2] @ load N\u00b0 door\n cmp r3,r7 @ compar N\u00b0 door N\u00b0 prisonner\n addeq r4,r4,#1 @ succes\n beq 3f\n mov r3,#1 @ top test table item \n str r3,[r6,r0,lsl #2]\n add r5,r5,#1\n cmp r5,#NBDOORS / 2 @ number tests maxi\u00a0?\n blt 2b @ no -> loop\n3:\n add r2,r2,#1 @ other prisonner\n cmp r2,#NBDOORS\n blt 1b\n \n mov r0,r4 @ return number of successes \n100:\n pop {r1-r7,lr}\n bx lr @ return \n/******************************************************************/\n/* raz test table */ \n/******************************************************************/\nrazTable:\n push {r0-r2,lr} @ save registers\n ldr r0,iAdrtbTest\n mov r1,#0 @ item indice\n mov r2,#0\n1:\n str r2,[r0,r1,lsl #2] @ store zero \u00e0 item\n add r1,r1,#1\n cmp r1,#NBDOORS\n blt 1b\n100:\n pop {r0-r2,lr}\n bx lr @ return \n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* r0 contains the address of table */\noptimaStrategie:\n push {r1-r7,lr} @ save registers\n mov r4,#0 @ counter number of successes\n mov r2,#0 @ counter prisonner\n1:\n mov r5,#0 @ counter test\n mov r1,r2 @ first test = N\u00b0 prisonner\n2:\n ldr r3,[r0,r1,lsl #2] @ load N\u00b0 door\n cmp r3,r2\n addeq r4,r4,#1 @ equal -> succes\n beq 3f\n mov r1,r3 @ new test with N\u00b0 door\n add r5,r5,#1 \n cmp r5,#NBDOORS / 2 @ test number maxi\u00a0?\n blt 2b\n3:\n add r2,r2,#1 @ other prisonner\n cmp r2,#NBDOORS\n blt 1b\n \n mov r0,r4\n100:\n pop {r1-r7,lr}\n bx lr @ return \n/******************************************************************/\n/* knuth Shuffle */ \n/******************************************************************/\n/* r0 contains the address of table */\n/* r1 contains the number of elements */\nknuthShuffle:\n push {r2-r5,lr} @ save registers\n mov r5,r0 @ save table address\n mov r2,#0 @ start index\n1:\n mov r0,r2 @ generate aleas\n bl genereraleas\n ldr r3,[r5,r2,lsl #2] @ swap number on the table\n ldr r4,[r5,r0,lsl #2]\n str r4,[r5,r2,lsl #2]\n str r3,[r5,r0,lsl #2]\n add r2,#1 @ next number\n cmp r2,r1 @ end\u00a0?\n blt 1b @ no -> loop\n100:\n pop {r2-r5,lr}\n bx lr @ return \n/***************************************************/\n/* Generation random number */\n/***************************************************/\n/* r0 contains limit */\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n/*****************************************************/\niAdriGraine: .int iGraine\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"", "safe": true }, { "filename": "100_prisoners_150.txt", "content": "\n\nruns 100000\nPercent saved opt.strategy: 31.165\nPercent saved random strategy: 0.0\n\n", "safe": true }, { "filename": "100_prisoners_151.txt", "content": "/*REXX program to simulate the problem of 100 prisoners: random, and optimal strategy.*/\nparse arg men trials seed . /*obtain optional arguments from the CL*/\nif men=='' | men==\",\" then men= 100 /*number of prisoners for this run.*/\nif trials=='' | trials==\",\" then trials= 100000 /* \" \" simulations \" \" \" */\nif datatype(seed, 'W') then call random ,,seed /*seed for the random number generator.*/\ntry= men % 2; swaps= men * 3 /*number tries for searching for a card*/\n$.1= ' a simple '; $.2= \"an optimal\" /*literals used for the SAY instruction*/\nsay center(' running' commas(trials) \"trials with\" commas(men) 'prisoners ', 70, \"\u2550\")\nsay\n do strategy=1 for 2; pardons= 0 /*perform the two types of strategies. */\n\n do trials; call gCards /*do trials for a strategy; gen cards.*/\n do p=1 for men until failure /*have each prisoner go through process*/\n if strategy==1 then failure= simple() /*Is 1st strategy? Use simple strategy*/\n else failure= picker() /* \" 2nd \" \" optimal \" */\n end /*p*/ /*FAILURE \u2261 1? Then a prisoner failed.*/\n if #==men then pardons= pardons + 1 /*was there a pardon of all prisoners? */\n end /*trials*/ /*if 1 prisoner fails, then they all do*/\n\n pc= format( pardons/trials*100, , 3); _= left('', pc<10)\n say right('Using', 9) $.strategy \"strategy yields pardons \" _||pc\"% of the time.\"\n end /*strategy*/\nexit /*stick a fork in it, we're all done. */\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\ncommas: parse arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\ngCards: #= 0; do j=1 for men; @.j= j /*define seq. of cards*/\n end /*j*/ /*same as seq. of men.*/\n do swaps; a= random(1, men) /*get 1st rand number.*/\n do until b\\==a; b= random(1, men) /* \" 2nd \" \" */\n end /*until*/ /* [\u2191] ensure A \u00ac== B */\n parse value @.a @.b with @.b @.a /*swap 2 random cards.*/\n end /*swaps*/; return\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\nsimple: !.= 0; do try; do until !.?==0; ?= random(1, men) /*get random card \u00b7\u00b7\u00b7 */\n end /*until*/ /*\u00b7\u00b7\u00b7 not used before.*/\n if @.?==p then do; #= #+1; return 0; end /*found his own card? */\n !.?= 1 /*flag as being used. */\n end /*try*/; return 1 /*didn't find his card*/\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\npicker: ?= p; do try; if @.?==p then do; #= #+1; return 0 /*Found his own card? */\n end /* [\u2191] indicate success for prisoner. */\n ?= @.? /*choose next drawer from current card.*/\n end /*try*/; return 1 /*choose half of the number of drawers.*/\n", "safe": true }, { "filename": "100_prisoners_152.txt", "content": "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 running 100,000 trials with 100 prisoners \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n Using a simple strategy yields pardons 0.000% of the time.\n Using an optimal strategy yields pardons 31.186% of the time.\n", "safe": true }, { "filename": "100_prisoners_153.txt", "content": "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 running 100,000 trials with 10 prisoners \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n Using a simple strategy yields pardons 0.086% of the time.\n Using an optimal strategy yields pardons 31.204% of the time.\n", "safe": true }, { "filename": "100_prisoners_154.txt", "content": "prisoners = [*1..100]\nN = 10_000\ngenerate_rooms = ->{ [nil]+[*1..100].shuffle }\n \nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)}\nend\nputs \"Random strategy\u00a0: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n\nres = N.times.count do\n rooms = generate_rooms[]\n prisoners.all? do |pr|\n cur_room = pr\n 50.times.any? do\n found = (rooms[cur_room] == pr)\n cur_room = rooms[cur_room]\n found\n end\n end\nend\nputs \"Optimal strategy: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n", "safe": true }, { "filename": "100_prisoners_155.txt", "content": "Random strategy\u00a0: 0.0000\u00a0%\nOptimal strategy: 30.7400\u00a0%\n", "safe": true }, { "filename": "100_prisoners_156.txt", "content": "[dependencies]\nrand = '0.7.2'\n", "safe": true }, { "filename": "100_prisoners_157.txt", "content": "extern crate rand;\n\nuse rand::prelude::*;\n\n// Do a full run of checking boxes in a random order for a single prisoner\nfn check_random_boxes(prisoner: u8, boxes: &[u8]) -> bool {\n let checks = {\n let mut b: Vec = (1u8..=100u8).collect();\n b.shuffle(&mut rand::thread_rng());\n b\n };\n checks.into_iter().take(50).any(|check| boxes[check as usize - 1] == prisoner)\n}\n\n// Do a full run of checking boxes in the optimized order for a single prisoner\nfn check_ordered_boxes(prisoner: u8, boxes: &[u8]) -> bool {\n let mut next_check = prisoner;\n (0..50).any(|_| {\n next_check = boxes[next_check as usize - 1];\n next_check == prisoner\n })\n}\n\nfn main() {\n let mut boxes: Vec = (1u8..=100u8).collect();\n\n let trials = 100000;\n\n let ordered_successes = (0..trials).filter(|_| {\n boxes.shuffle(&mut rand::thread_rng());\n (1u8..=100u8).all(|prisoner| check_ordered_boxes(prisoner, &boxes))\n }).count();\n\n let random_successes = (0..trials).filter(|_| {\n boxes.shuffle(&mut rand::thread_rng());\n (1u8..=100u8).all(|prisoner| check_random_boxes(prisoner, &boxes))\n }).count();\n\n println!(\"{} / {} ({:.02}%) successes in ordered\", ordered_successes, trials, ordered_successes as f64 * 100.0 / trials as f64);\n println!(\"{} / {} ({:.02}%) successes in random\", random_successes, trials, random_successes as f64 * 100.0 / trials as f64);\n\n}\n", "safe": true }, { "filename": "100_prisoners_158.txt", "content": "31106 / 100000 (31.11%) successes in ordered\n0 / 100000 (0.00%) successes in random", "safe": true }, { "filename": "100_prisoners_159.txt", "content": "class MAIN is\n shuffle (a: ARRAY{INT}) is\n ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a);\n end;\n\n try_random (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is\n my_tries\u00a0::= drawers.inds; shuffle(my_tries);\n loop tries.times!;\n if drawers[my_tries.elt!] = n then return true; end;\n end;\n return false;\n end;\n\n try_optimal (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is\n num\u00a0::= n;\n loop tries.times!;\n num\u00a0:= drawers[num];\n if num = n then return true; end;\n end;\n return false;\n end;\n\n stats (label: STR, rounds, successes: INT): STR is\n return #FMT(\"<^###########>: <#######> rounds. Successes: <#######> (<##.###>%%)\\n\",\n label, rounds, successes, (successes.flt / rounds.flt)*100.0).str;\n end;\n\n try (name: STR, nrounds, ndrawers, npris, ntries: INT,\n strategy: ROUT{INT,ARRAY{INT},INT}:BOOL)\n is\n drawers: ARRAY{INT}\u00a0:= #(ndrawers);\n loop drawers.set!(drawers.ind!); end;\n successes\u00a0::= 0;\n loop nrounds.times!;\n shuffle(drawers);\n success\u00a0::= true;\n loop\n n\u00a0::= npris.times!;\n if ~strategy.call(n, drawers, ntries) then\n success\u00a0:= false;\n break!;\n end;\n end;\n if success then successes\u00a0:= successes + 1; end;\n end;\n #OUT + stats(name, nrounds, successes);\n end;\n\n main is\n RND::seed\u00a0:= #TIMES.wall_time;\n #OUT +\"100 prisoners, 100 drawers, 50 tries:\\n\";\n try(\"random\", 100000, 100, 100, 50, bind(try_random(_, _, _)));\n try(\"optimal\", 100000, 100, 100, 50, bind(try_optimal(_, _, _)));\n\n #OUT +\"\\n10 prisoners, 10 drawers, 5 tries:\\n\";\n try(\"random\", 100000, 10, 10, 5, bind(try_random(_, _, _)));\n try(\"optimal\", 100000, 10, 10, 5, bind(try_optimal(_, _, _)));\n end;\nend;", "safe": true }, { "filename": "100_prisoners_16.txt", "content": "Random strategie \u00a0: 0 sur 1000\nOptimal strategie\u00a0: 303 sur 1000\n", "safe": true }, { "filename": "100_prisoners_160.txt", "content": "100 prisoners, 100 drawers, 50 tries:\nrandom \u00a0: 100000 rounds. Successes: 0 ( 0.000%)\noptimal \u00a0: 100000 rounds. Successes: 31378 (31.378%)\n\n10 prisoners, 10 drawers, 5 tries:\nrandom \u00a0: 100000 rounds. Successes: 113 ( 0.113%)\noptimal \u00a0: 100000 rounds. Successes: 35633 (35.633%)", "safe": true }, { "filename": "100_prisoners_161.txt", "content": "import scala.util.Random\nimport scala.util.control.Breaks._\n\nobject Main {\n def playOptimal(n: Int): Boolean = {\n val secretList = Random.shuffle((0 until n).toBuffer)\n\n for (i <- secretList.indices) {\n var prev = i\n breakable {\n for (_ <- 0 until secretList.size / 2) {\n if (secretList(prev) == i) {\n break()\n }\n prev = secretList(prev)\n }\n return false\n }\n }\n\n true\n }\n\n def playRandom(n: Int): Boolean = {\n val secretList = Random.shuffle((0 until n).toBuffer)\n\n for (i <- secretList.indices) {\n val trialList = Random.shuffle((0 until n).toBuffer)\n\n breakable {\n for (j <- 0 until trialList.size / 2) {\n if (trialList(j) == i) {\n break()\n }\n }\n return false\n }\n }\n\n true\n }\n\n def exec(n: Int, p: Int, play: Int => Boolean): Double = {\n var succ = 0.0\n for (_ <- 0 until n) {\n if (play(p)) {\n succ += 1\n }\n }\n (succ * 100.0) / n\n }\n\n def main(args: Array[String]): Unit = {\n val n = 100000\n val p = 100\n printf(\"# of executions:\u00a0%,d\\n\", n)\n printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, playOptimal))\n printf(\"Random play success rate: %f%%\\n\", exec(n, p, playRandom))\n }\n}\n", "safe": true }, { "filename": "100_prisoners_162.txt", "content": "# of executions: 100,000\nOptimal play success rate: 31.201000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100_prisoners_163.txt", "content": "program prisoners;\n setrandom(0);\n \n strategies\u00a0:= {\n [\"Optimal\", routine optimal_strategy],\n [\"Random\", routine random_strategy]\n };\n \n runs\u00a0:= 10000;\n\n loop for strategy = strategies(name) do\n successes\u00a0:= run_simulations(strategy, runs);\n print(rpad(name + \":\", 10), successes * 100 / runs, \"%\");\n end loop;\n \n proc run_simulations(strategy, amount);\n loop for i in [1..amount] do\n successes +:= if simulate(strategy) then 1 else 0 end;\n end loop;\n return successes; \n end proc;\n \n proc simulate(strategy);\n drawers\u00a0:= [1..100];\n shuffle(drawers);\n loop for prisoner in [1..100] do\n if not call(strategy, drawers, prisoner) then\n return false;\n end if;\n end loop;\n return true;\n end proc;\n \n proc optimal_strategy(drawers, prisoner);\n d\u00a0:= prisoner;\n loop for s in [1..50] do\n if (d\u00a0:= drawers(d)) = prisoner then\n return true;\n end if;\n end loop;\n return false;\n end proc;\n \n proc random_strategy(drawers, prisoner);\n loop for s in [1..50] do\n if drawers(1+random(#drawers-1)) = prisoner then\n return true;\n end if;\n end loop;\n return false;\n end proc;\n \n proc shuffle(rw drawers);\n loop for i in [1..#drawers] do\n j\u00a0:= i+random(#drawers-i);\n [drawers(i), drawers(j)]\u00a0:= [drawers(j), drawers(i)];\n end loop;\n end proc;\nend program;", "safe": true }, { "filename": "100_prisoners_164.txt", "content": "Optimal: 31.26\u00a0%\nRandom: 0\u00a0%", "safe": true }, { "filename": "100_prisoners_165.txt", "content": "// ==========================================================================\n// START-SuperCollider solution to Rosetta Code TASK: 100 prisoners\t\t\t\t ## BY: MusicCoder\u00a0: 2024-06-08 ##\n// ==========================================================================\n\n(\n/* ## BY: MusicCoder\u00a0: 2024-06-08 ##\nhttps://rosettacode.org/wiki/100_prisoners\nTHE TASK: Simulate the 100-prisoners game and compare two strategies\n1: random choice, 2: follow the cards.\n\n*** My preferance - make a function to play the game\n ... and feed it a function for each strategy ***\nUse 0..99 rather than 1..100 for player, card and drawer numbers\n\nWhat can a player possibly know?\n1. Player number\n2. Current turn number\n3. Previous drawer picked \u00a0: -1 means no previous as yet\n4. Previous card value \u00a0: -1 means no previous as yet\n5. Number of drawers ( PROBABLY == number of players)\n6. Number of turns\n\n--- These parameters should be good for a lot of different strategies ---\n\nStatergy function will get called with values for these six parameters\nStatergy function should return a drawerNumber\n*/\n// =============================================================================\n// *** THE REQUIRED STRATEGY FUNCTIONS ***\n// =============================================================================\n// strategyRandom: Pick a drawer number at random\nvar strategyRandom = {\n |turnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns|\n\n var drawerPicked = numDrawers.rand;\n drawerPicked;\n};\n// =============================================================================\n// strategyFollow: Start at drawerNumber = playerNumber, then follow the cardNumbers\nvar strategyFollow = {\n |turnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns|\n\n var drawerPicked = if ( (previousCard == -1), {playerNumber}, {previousCard});\n drawerPicked;\n};\n\n// =============================================================================\n/* ### playGame: Function to play the game ###\n// =============================================================================\nTwo loops: outer loop over players, inner loop over turns for each player\nThe core of the inner loop calls the supplied stratergy function\n ... passing in values for the six parameters:\nturnNumber, previousDrawer, previousCard, playerNumber, numDrawers, numTurns\nThe stratergy function responds with the number of the drawer it has picked\n ... for the current turn\n*/\nvar playGame = {\n |strategy, strategyName=\"\", numPlayers=100, numDrawers=100, numTurns=50, numSims=10000|\n var percentWins=0;\n var countWins=0;\n var drawers=Array.iota(numPlayers); // fill array with player numbers 0..99\n\n numSims.do{\n var playerWon = true; // as soon as one player fails - exit this simulation\n var playerNumber = 0; // first player\n\n drawers = drawers.scramble; // randomly reorder the cards in the drawers\n\n while(// loop until the last player or until any player fails\n {playerNumber Bool {\n for num in 1...numPrisoners {\n guard findNumber(num) else {\n return false\n }\n }\n\n return true\n }\n\n private func findNumber(_ num: Int) -> Bool {\n var tries = 0\n var nextDrawer = num - 1\n\n while tries < 50 {\n tries += 1\n\n switch strategy {\n case .random where drawers.randomElement()! == num:\n return true\n case .optimum where drawers[nextDrawer] == num:\n return true\n case .optimum:\n nextDrawer = drawers[nextDrawer] - 1\n case _:\n continue\n }\n }\n\n return false\n }\n\n enum Strategy {\n case random, optimum\n }\n}\n\nlet numGames = 100_000\nlet lock = DispatchSemaphore(value: 1)\nvar done = 0\n\nprint(\"Running \\(numGames) games for each strategy\")\n\nDispatchQueue.concurrentPerform(iterations: 2) {i in\n let strat = i == 0 ? PrisonersGame.Strategy.random : .optimum\n var numPardoned = 0\n\n for _ in 0..= 0\n}\n\n# Runs each of the STRATEGIES and prints a report on how well they\n# worked.\nproc compareStrategies {strategies} {\n global Samples\n set fmt \"Using %s %s strategy, the prisoners were freed in %5.2f%% of the cases.\"\n foreach strategy $strategies {\n set article [expr [startsWithVowel $strategy] ? {\"an\"} : {\"a\"}]\n set pct [expr [sampling ${strategy}Strategy] / $Samples.0 * 100]\n puts [format $fmt $article $strategy $pct]\n }\n}\n\ncompareStrategies $Strategies\n", "safe": true }, { "filename": "100_prisoners_17.txt", "content": "unplanned: function [][\n drawers: shuffle @1..100\n every? 1..100 'x -> some? 1..50 => [x = sample drawers]\n]\n\nplanned: function [][\n drawers: shuffle @1..100\n every? 1..100 'x [\n next: x\n some? 1..50 => [x = next: <= drawers\\[next-1]]\n ]\n]\n\ntest: function [f][\n count: enumerate 10000 => [call f []]\n print [f ~\"|mul fdiv count 10000 100|%\"]\n]\n\ntest 'unplanned\ntest 'planned\n", "safe": true }, { "filename": "100_prisoners_170.txt", "content": "Using a random strategy, the prisoners were freed in 0.00% of the cases.\nUsing an optimal strategy, the prisoners were freed in 32.35% of the cases.", "safe": true }, { "filename": "100_prisoners_171.txt", "content": "USE rosettacode;\nGO\n\nSET NOCOUNT ON;\nGO\n\nCREATE TABLE dbo.numbers (n INT PRIMARY KEY);\nGO\n\n-- NOTE If you want to play more than 10000 games, you need to extend the query generating the numbers table by adding\n-- next cross joins. Now the table contains enough values to solve the task and it takes less processing time.\n\nWITH sample100 AS (\n SELECT TOP(100) object_id\n FROM master.sys.objects\n)\nINSERT numbers\n SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS n\n FROM sample100 AS A\n CROSS JOIN sample100 AS B;\nGO\n\nCREATE TABLE dbo.drawers (drawer INT PRIMARY KEY, card INT);\nGO\n\nCREATE TABLE dbo.results (strategy VARCHAR(10), game INT, result BIT, PRIMARY KEY (game, strategy));\nGO\n\nCREATE PROCEDURE dbo.shuffleDrawers @prisonersCount INT\nAS BEGIN\n SET NOCOUNT ON;\n\n IF NOT EXISTS (SELECT * FROM drawers)\n INSERT drawers (drawer, card)\n SELECT n AS drawer, n AS card\n FROM numbers\n WHERE n <= @prisonersCount;\n\n DECLARE @randoms TABLE (n INT, random INT);\n DECLARE @n INT = 1;\n WHILE @n <= @prisonersCount BEGIN\n INSERT @randoms VALUES (@n, ROUND(RAND() * (@prisonersCount - 1), 0) + 1);\n\n SET @n = @n + 1;\n END;\n\n WITH ordered AS (\n SELECT ROW_NUMBER() OVER (ORDER BY random ASC) AS drawer,\n n AS card\n FROM @randoms\n )\n UPDATE drawers\n SET card = o.card\n FROM drawers AS s\n INNER JOIN ordered AS o\n ON o.drawer = s.drawer;\nEND\nGO\n\nCREATE PROCEDURE dbo.find @prisoner INT, @strategy VARCHAR(10)\nAS BEGIN\n -- A prisoner can open no more than 50 drawers.\n DECLARE @drawersCount INT = (SELECT COUNT(*) FROM drawers);\n DECLARE @openMax INT = @drawersCount / 2;\n\n -- Prisoners start outside the room.\n DECLARE @card INT = NULL;\n DECLARE @open INT = 1;\n WHILE @open <= @openMax BEGIN\n -- A prisoner tries to find his own number.\n IF @strategy = 'random' BEGIN\n DECLARE @random INT = ROUND(RAND() * (@drawersCount - 1), 0) + 1;\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @random);\n END\n IF @strategy = 'optimal' BEGIN\n IF @card IS NULL BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @prisoner);\n END ELSE BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @card);\n END\n END\n\n -- A prisoner finding his own number is then held apart from the others.\n IF @card = @prisoner\n RETURN 1;\n\n SET @open = @open + 1;\n END\n\n RETURN 0;\nEND\nGO\n\nCREATE PROCEDURE dbo.playGame @gamesCount INT, @strategy VARCHAR(10), @prisonersCount INT = 100\nAS BEGIN\n SET NOCOUNT ON;\n\n IF @gamesCount <> (SELECT COUNT(*) FROM results WHERE strategy = @strategy) BEGIN\n DELETE results\n WHERE strategy = @strategy;\n\n INSERT results (strategy, game, result)\n SELECT @strategy AS strategy, n AS game, 0 AS result\n FROM numbers\n WHERE n <= @gamesCount;\n END\n\n UPDATE results\n SET result = 0\n WHERE strategy = @strategy;\n\n DECLARE @game INT = 1;\n WHILE @game <= @gamesCount BEGIN\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 EXECUTE shuffleDrawers @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 DECLARE @prisoner INT = 1;\n DECLARE @found INT = 0;\n WHILE @prisoner <= @prisonersCount BEGIN\n EXECUTE @found = find @prisoner, @strategy;\n IF @found = 1\n SET @prisoner = @prisoner + 1;\n ELSE\n BREAK;\n END;\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 IF @found = 1\n UPDATE results SET result = 1 WHERE strategy = @strategy AND game = @game;\n \n SET @game = @game + 1;\n END\nEND\nGO\n\nCREATE FUNCTION dbo.computeProbability(@strategy VARCHAR(10))\nRETURNS decimal (18, 2)\nAS BEGIN\n RETURN (\n SELECT (SUM(CAST(result AS INT)) * 10000 / COUNT(*)) / 100\n FROM results\n WHERE strategy = @strategy\n );\nEND\nGO\n\n-- Simulate several thousand instances of the game:\nDECLARE @gamesCount INT = 2000;\n\n-- ...where the prisoners randomly open drawers.\nEXECUTE playGame @gamesCount, 'random';\n\n-- ...where the prisoners use the optimal strategy mentioned in the Wikipedia article.\nEXECUTE playGame @gamesCount, 'optimal';\n\n-- Show and compare the computed probabilities of success for the two strategies.\nDECLARE @log VARCHAR(max);\nSET @log = CONCAT('Games count: ', @gamesCount);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"random\" strategy: ', dbo.computeProbability('random'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"optimal\" strategy: ', dbo.computeProbability('optimal'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nGO\n\nDROP FUNCTION dbo.computeProbability;\nDROP PROCEDURE dbo.playGame;\nDROP PROCEDURE dbo.find;\nDROP PROCEDURE dbo.shuffleDrawers;\nDROP TABLE dbo.results;\nDROP TABLE dbo.drawers;\nDROP TABLE dbo.numbers;\nGO", "safe": true }, { "filename": "100_prisoners_172.txt", "content": "Games count: 2000\nProbability of success with \"random\" strategy: 0.00 \nProbability of success with \"optimal\" strategy: 31.00", "safe": true }, { "filename": "100_prisoners_173.txt", "content": "#lang transd\n\nMainModule: {\nsimRandom: (\u03bb numPris Int() nRuns Int()\n locals: nSucc 0.0\n (for n in Range(nRuns) do\n (with draws (for i in Range(numPris) project i) succ 1\n (for prisN in Range(numPris) do\n (shuffle draws)\n (if (not (is-el Range(in: draws 0 (/ numPris 2)) prisN))\n (= succ 0) break))\n (+= nSucc succ)\n ) )\n (ret (* (/ nSucc nRuns) 100))\n),\n\nsimOptimal: (\u03bb numPris Int() nRuns Int()\n locals: nSucc 0.0\n (for n in Range(nRuns) do\n (with draws (for i in Range(numPris) project i) succ 0 nextDraw 0\n (shuffle draws)\n (for prisN in Range(numPris) do (= nextDraw prisN) (= succ 0)\n (for i in Range( (/ numPris 2)) do\n (= nextDraw (get draws nextDraw))\n (if (== nextDraw prisN) (= succ 1) break))\n (if (not succ) break))\n (+= nSucc succ)\n ) )\n (ret (* (/ nSucc nRuns) 100))\n),\n\n_start: (\u03bb\n (lout prec: 4 :fixed \"Random play: \" (simRandom 100 10000) \"% of wins\")\n (lout \"Strategic play: \" (simOptimal 100 10000) \"% of wins\")\n (lout \"Check random play: \" (simRandom 10 100000) \"% of wins\")\n)\n}\n", "safe": true }, { "filename": "100_prisoners_174.txt", "content": "Random play: 0.0000% of wins\nStrategic play: 31.4500% of wins\nCheck random play: 0.1040% of wins\n", "safe": true }, { "filename": "100_prisoners_175.txt", "content": "Sub HundredPrisoners()\n\n NumberOfPrisoners = Int(InputBox(\"Number of Prisoners\", \"Prisoners\", 100))\n Tries = Int(InputBox(\"Numer of Tries\", \"Tries\", 1000))\n Selections = Int(InputBox(\"Number of Selections\", \"Selections\", NumberOfPrisoners / 2))\n\n StartTime = Timer\n\n AllFoundOptimal = 0\n AllFoundRandom = 0\n AllFoundRandomMem = 0\n\n For i = 1 To Tries\n OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections)\n RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections)\n RandomMemCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)\n \n If OptimalCount = NumberOfPrisoners Then\n AllFoundOptimal = AllFoundOptimal + 1\n End If\n If RandomCount = NumberOfPrisoners Then\n AllFoundRandom = AllFoundRandom + 1\n End If\n If RandomMemCount = NumberOfPrisoners Then\n AllFoundRandomMem = AllFoundRandomMem + 1\n End If\n Next i\n\n\n ResultString = \"Optimal: \" & AllFoundOptimal & \" of \" & Tries & \": \" & AllFoundOptimal / Tries * 100 & \"%\"\n ResultString = ResultString & Chr(13) & \"Random: \" & AllFoundRandom & \" of \" & Tries & \": \" & AllFoundRandom / Tries * 100 & \"%\"\n ResultString = ResultString & Chr(13) & \"RandomMem: \" & AllFoundRandomMem & \" of \" & Tries & \": \" & AllFoundRandomMem / Tries * 100 & \"%\"\n\n EndTime = Timer\n\n ResultString = ResultString & Chr(13) & \"Elapsed Time: \" & Round(EndTime - StartTime, 2) & \" s\"\n ResultString = ResultString & Chr(13) & \"Trials/sec: \" & Tries / Round(EndTime - StartTime, 2)\n\n MsgBox ResultString, vbOKOnly, \"Results\"\n\nEnd Sub\n\nFunction HundredPrisoners_Optimal(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n \n ReDim DrawerArray(NrPrisoners - 1)\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n For i = 1 To NrPrisoners\n NumberFromDrawer = DrawerArray(i - 1)\n For j = 1 To NrSelections - 1\n If NumberFromDrawer = i Then\n FoundOwnNumber = FoundOwnNumber + 1\n Exit For\n End If\n NumberFromDrawer = DrawerArray(NumberFromDrawer - 1)\n Next j\n Next i\n HundredPrisoners_Optimal = FoundOwnNumber\nEnd Function\n\nFunction HundredPrisoners_Random(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n ReDim DrawerArray(NrPrisoners - 1)\n \n FoundOwnNumber = 0\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n RandomDrawer = Int(NrPrisoners * Rnd)\n NumberFromDrawer = DrawerArray(RandomDrawer)\n If NumberFromDrawer = i Then\n FoundOwnNumber = FoundOwnNumber + 1\n Exit For\n End If\n Next j\n Next i\n HundredPrisoners_Random = FoundOwnNumber\nEnd Function\n\nFunction HundredPrisoners_Random_Mem(ByVal NrPrisoners, ByVal NrSelections) As Long\n Dim DrawerArray() As Long\n Dim SelectionArray() As Long\n ReDim DrawerArray(NrPrisoners - 1)\n ReDim SelectionArray(NrPrisoners - 1)\n \n HundredPrisoners_Random_Mem = 0\n FoundOwnNumberMem = 0\n \n For Counter = LBound(DrawerArray) To UBound(DrawerArray)\n DrawerArray(Counter) = Counter + 1\n Next Counter\n \n For Counter = LBound(SelectionArray) To UBound(SelectionArray)\n SelectionArray(Counter) = Counter + 1\n Next Counter\n\n FisherYates DrawerArray\n \n For i = 1 To NrPrisoners\n FisherYates SelectionArray\n For j = 1 To NrSelections\n NumberFromDrawer = DrawerArray(SelectionArray(j - 1) - 1)\n If NumberFromDrawer = i Then\n FoundOwnNumberMem = FoundOwnNumberMem + 1\n Exit For\n End If\n Next j\n Next i\n HundredPrisoners_Random_Mem = FoundOwnNumberMem\nEnd Function\n\nSub FisherYates(ByRef InputArray() As Long)\n \n Dim Temp As Long\n Dim PosRandom As Long\n Dim Counter As Long\n Dim Upper As Long\n Dim Lower As Long\n \n Lower = LBound(InputArray)\n Upper = UBound(InputArray)\n \n Randomize\n \n For Counter = Upper To (Lower + 1) Step -1\n PosRandom = CLng(Int((Counter - Lower + 1) * Rnd + Lower))\n Temp = InputArray(Counter)\n InputArray(Counter) = InputArray(PosRandom)\n InputArray(PosRandom) = Temp\n Next Counter\n \nEnd Sub\n", "safe": true }, { "filename": "100_prisoners_176.txt", "content": "Optimal: 29090 of 100000: 29.09%\nRandom: 0 of 100000: 0%\nRandomMem: 0 of 100000: 0%\nElapsed Time: 388.41 s", "safe": true }, { "filename": "100_prisoners_177.txt", "content": "Module Module1\n\n Function PlayOptimal() As Boolean\n Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n For p = 1 To 100\n Dim success = False\n\n Dim choice = p - 1\n For i = 1 To 50\n If secrets(choice) = p - 1 Then\n success = True\n Exit For\n End If\n choice = secrets(choice)\n Next\n\n If Not success Then\n Return False\n End If\n Next\n\n Return True\n End Function\n\n Function PlayRandom() As Boolean\n Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n For p = 1 To 100\n Dim choices = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList\n\n Dim success = False\n For i = 1 To 50\n If choices(i - 1) = p Then\n success = True\n Exit For\n End If\n Next\n\n If Not success Then\n Return False\n End If\n Next\n\n Return True\n End Function\n\n Function Exec(n As UInteger, play As Func(Of Boolean))\n Dim success As UInteger = 0\n For i As UInteger = 1 To n\n If play() Then\n success += 1\n End If\n Next\n Return 100.0 * success / n\n End Function\n\n Sub Main()\n Dim N = 1_000_000\n Console.WriteLine(\"# of executions: {0}\", N)\n Console.WriteLine(\"Optimal play success rate: {0:0.00000000000}%\", Exec(N, AddressOf PlayOptimal))\n Console.WriteLine(\" Random play success rate: {0:0.00000000000}%\", Exec(N, AddressOf PlayRandom))\n End Sub\n\nEnd Module\n", "safe": true }, { "filename": "100_prisoners_178.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.12990000000%\n Random play success rate: 0.00000000000%", "safe": true }, { "filename": "100_prisoners_179.txt", "content": "option explicit\nconst npris=100\nconst ntries=50\nconst ntests=1000.\ndim drawer(100),opened(100),i\nfor i=1 to npris: drawer(i)=i:next\nshuffle drawer\nwscript.echo rf(tests(false)/ntests*100,10,\" \") &\"\u00a0% success for random\"\nwscript.echo rf(tests(true) /ntests*100,10,\" \") &\"\u00a0% success for optimal strategy\"\n\nfunction rf(v,n,s) rf=right(string(n,s)& v,n):end function \n\nsub shuffle(d) 'knut's shuffle\ndim i,j,t\nrandomize timer\nfor i=1 to npris\n j=int(rnd()*i+1)\n t=d(i):d(i)=d(j):d(j)=t\nnext\nend sub\n\nfunction tests(strat)\ndim cntp,i,j\ntests=0\nfor i=1 to ntests\n shuffle drawer\n cntp=0\n if strat then\n for j=1 to npris\n\tif not trystrat(j) then exit for\n next\n else\t\t\n for j=1 to npris\n if not tryrand(j) then exit for\n next \n end if\n if j>=npris then tests=tests+1\nnext\nend function \n\t \nfunction tryrand(pris)\n dim i,r \n\terase opened\n for i=1 to ntries\n do \n r=int(rnd*npris+1)\n loop until opened(r)=false\n opened(r)=true\n if drawer(r)= pris then tryrand=true : exit function\n next\n tryrand=false\nend function \n\nfunction trystrat(pris)\n dim i,r\n r=pris\n for i=1 to ntries\n if drawer(r)= pris then trystrat=true\t:exit function\n r=drawer(r)\n next\n trystrat=false\nend function\n", "safe": true }, { "filename": "100_prisoners_18.txt", "content": "unplanned 0.0%\nplanned 31.43%", "safe": true }, { "filename": "100_prisoners_180.txt", "content": " 0\u00a0% success for random\n 32.9\u00a0% success for optimal strategy\n", "safe": true }, { "filename": "100_prisoners_181.txt", "content": "import rand\nimport rand.seed\n// Uses 0-based numbering rather than 1-based numbering throughout.\nfn do_trials(trials int, np int, strategy string) {\n mut pardoned := 0\n for _ in 0..trials {\n mut drawers := []int{len: 100, init: it}\n rand.shuffle(mut drawers) or {panic('shuffle failed')}\n mut next_trial := false\n for p in 0..np {\n mut next_prisoner := false\n if strategy == \"optimal\" {\n mut prev := p\n for _ in 0..50 {\n this := drawers[prev]\n if this == p {\n next_prisoner = true\n break\n }\n prev = this\n }\n } else {\n // Assumes a prisoner remembers previous drawers (s)he opened\n // and chooses at random from the others.\n mut opened := [100]bool{}\n for _ in 0..50 {\n mut n := 0\n for {\n n = rand.intn(100) or {0}\n if !opened[n] {\n opened[n] = true\n break\n }\n }\n if drawers[n] == p {\n next_prisoner = true\n break\n }\n }\n }\n if !next_prisoner {\n next_trial = true\n break\n }\n }\n if !next_trial {\n pardoned++\n }\n }\n rf := f64(pardoned) / f64(trials) * 100\n println(\" strategy = ${strategy:-7} pardoned = ${pardoned:-6} relative frequency = ${rf:-5.2f}%\\n\")\n}\n \nfn main() {\n rand.seed(seed.time_seed_array(2))\n trials := 100000\n for np in [10, 100] {\n println(\"Results from $trials trials with $np prisoners:\\n\")\n for strategy in [\"random\", \"optimal\"] {\n do_trials(trials, np, strategy)\n }\n }\n}\n", "safe": true }, { "filename": "100_prisoners_182.txt", "content": "Results from 100000 trials with 10 prisoners:\n\n strategy = random pardoned = 91 relative frequency = 0.09\u00a0%\n\n strategy = optimal pardoned = 31321 relative frequency = 31.32%\n\nResults from 100000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00\u00a0%\n\n strategy = optimal pardoned = 31318 relative frequency = 31.32%\n", "safe": true }, { "filename": "100_prisoners_183.txt", "content": "import \"random\" for Random\nimport \"./fmt\" for Fmt\n\nvar rand = Random.new()\n\nvar doTrials = Fn.new{ |trials, np, strategy|\n var pardoned = 0\n for (t in 0...trials) {\n var drawers = List.filled(100, 0)\n for (i in 0..99) drawers[i] = i\n rand.shuffle(drawers)\n var nextTrial = false\n for (p in 0...np) {\n var nextPrisoner = false\n if (strategy == \"optimal\") {\n var prev = p\n for (d in 0..49) {\n var curr = drawers[prev]\n if (curr == p) {\n nextPrisoner = true\n break\n }\n prev = curr\n }\n } else {\n var opened = List.filled(100, false)\n for (d in 0..49) {\n var n\n while (true) {\n n = rand.int(100)\n if (!opened[n]) {\n opened[n] = true\n break\n }\n }\n if (drawers[n] == p) {\n nextPrisoner = true\n break\n }\n }\n }\n if (!nextPrisoner) {\n nextTrial = true\n break\n }\n }\n if (!nextTrial) pardoned = pardoned + 1\n }\n var rf = pardoned/trials * 100\n Fmt.print(\" strategy = $-7s pardoned = $,6d relative frequency = $5.2f\\%\\n\", strategy, pardoned, rf)\n}\n\nvar trials = 1e5\nfor (np in [10, 100]) {\n Fmt.print(\"Results from $,d trials with $d prisoners:\\n\", trials, np)\n for (strategy in [\"random\", \"optimal\"]) doTrials.call(trials, np, strategy)\n}\n", "safe": true }, { "filename": "100_prisoners_184.txt", "content": "Results from 100,000 trials with 10 prisoners:\n\n strategy = random pardoned = 98 relative frequency = 0.10%\n\n strategy = optimal pardoned = 31,212 relative frequency = 31.21%\n\nResults from 100,000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00%\n\n strategy = optimal pardoned = 31,139 relative frequency = 31.14%\n", "safe": true }, { "filename": "100_prisoners_185.txt", "content": "int Drawer(100);\n\nproc KShuffle; \\Randomly rearrange the cards in the drawers\n\\(Woe unto thee if Stattolo shuffle is used instead of Knuth shuffle.)\nint I, J, T;\n[for I:= 100-1 downto 1 do\n [J:= Ran(I+1); \\range [0..I]\n T:= Drawer(I); Drawer(I):= Drawer(J); Drawer(J):= T;\n ];\n];\n\nfunc Stategy2; \\Return 'true' if stragegy succeeds\nint Prisoner, Card, Try;\n[for Prisoner:= 1 to 100 do\n [Card:= Drawer(Prisoner-1);\n Try:= 1;\n loop [if Card = Prisoner then quit;\n if Try >= 50 then return false;\n Card:= Drawer(Card-1);\n Try:= Try+1;\n ];\n ];\nreturn true;\n];\n\nfunc Stategy1; \\Return 'true' if stragegy succeeds\nint Prisoner, I, D(100);\n[for Prisoner:= 1 to 100 do\n loop [for I:= 0 to 100-1 do D(I):= I+1;\n KShuffle;\n for I:= 1 to 50 do\n if Drawer(D(I-1)) = Prisoner then quit;\n return false;\n ];\nreturn true;\n];\n\nproc Strategy(S);\nint S, I, Sample;\nreal Successes;\n[Successes:= 0.;\nfor Sample:= 1 to 100_000 do\n [for I:= 0 to 100-1 do Drawer(I):= I+1;\n KShuffle;\n case S of\n 1: if Stategy1 then Successes:= Successes + 1.;\n 2: if Stategy2 then Successes:= Successes + 1.\n other [];\n ];\nRlOut(0, Successes/100_000.*100.); Text(0, \"%^m^j\");\n];\n\n[Format(3, 12);\nText(0, \"Random strategy success rate: \");\nStrategy(1);\nText(0, \"Optimal strategy success rate: \");\nStrategy(2);\n]", "safe": true }, { "filename": "100_prisoners_186.txt", "content": "Random strategy success rate: 0.000000000000%\nOptimal strategy success rate: 31.085000000000%\n", "safe": true }, { "filename": "100_prisoners_187.txt", "content": "// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners\n// by Galileo, 05/2022\n\nsub play(prisoners, iterations, optimal)\n local prisoner, pardoned, found, drawer, drawers(prisoners), i, j, k, p, x\n\n for i = 1 to prisoners\u00a0: drawers(i) = i\u00a0: next\n\n for i = 1 to iterations\n for k = 1 to prisoners\u00a0: x = ran(prisoners) + 1\u00a0: p = drawers(x)\u00a0: drawers(x) = drawers(k)\u00a0: drawers(k) = p\u00a0: next\n for prisoner = 1 to prisoners\n found = false\n if optimal then drawer = prisoner else drawer = ran(prisoners) + 1 end if\n for j = 1 to prisoners / 2\n drawer = drawers(drawer)\n if drawer = prisoner found = true\u00a0: break\n if not optimal drawer = ran(prisoners) + 1\n next\n if not found break\n next\n pardoned = pardoned + found\n next\n\n return 100 * pardoned / iterations\nend sub\n \niterations = 10000\nprint \"Simulation count: \", iterations\nfor prisoners = 10 to 100 step 90\n random = play(prisoners, iterations, false)\n optimal = play(prisoners, iterations, true)\n print \"Prisoners: \", prisoners, \", random: \", random, \", optimal: \", optimal\nnext", "safe": true }, { "filename": "100_prisoners_188.txt", "content": "Simulation count: 10000\nPrisoners: 10, random: 0.01, optimal: 35.83\nPrisoners: 100, random: 0, optimal: 31.2\n---Program done, press RETURN---", "safe": true }, { "filename": "100_prisoners_189.txt", "content": "!yamlscript/v0\n\ndefn main(n=5000):\n :: https://rosettacode.org/wiki/100_prisoners\n\n random-successes optimal-successes run-count =:\n simulate-n-runs(n)\n .slice(q(random-successes optimal-successes run-count))\n\n say: \"Probability of survival with random search: $F(random-successes / run-count)\"\n\n say: \"Probability of survival with ordered search: $F(optimal-successes / run-count)\"\n\ndefn simulate-n-runs(n):\n :: Simulate n runs of the 100 prisoner problem and returns a success count\n for each search method.\n\n loop random-successes 0, optimal-successes 0, run-count 0:\n # If we've done the loop n times\n if n == run-count:\n # return results\n then::\n random-successes \u00a0:: random-successes\n optimal-successes\u00a0:: optimal-successes\n run-count \u00a0:: run-count\n\n # Otherwise, run for another batch of prisoners\n else:\n next-result =: simulate-100-prisoners()\n recur:\n (random-successes + next-result.random)\n (optimal-successes + next-result.optimal)\n run-count.++\n\ndefn simulate-100-prisoners():\n :: Simulates all prisoners searching the same drawers by both strategies,\n returns map showing whether each was successful.\n\n # Create 100 drawers with randomly ordered prisoner numbers:\n drawers =: random-drawers()\n hash-map:\n :random try-luck(drawers search-50-random-drawers)\n :optimal try-luck(drawers search-50-optimal-drawers)\n\ndefn try-luck(drawers drawer-searching-function):\n :: Returns 1 if all prisoners find their number otherwise 0.\n\n loop prisoners range(100):\n if prisoners.?:\n if prisoners.0.drawer-searching-function(drawers):\n recur: rest(prisoners)\n else: 0\n else: 1\n\ndefn search-50-optimal-drawers(prisoner-number drawers):\n :: Open 50 drawers according to the agreed strategy, returning true if\n prisoner's number was found.\n\n loop next-drawer prisoner-number, drawers-opened 0:\n when drawers-opened\u00a0!= 50:\n result =: drawers.$next-drawer\n result == prisoner-number ||:\n recur: result drawers-opened.++\n\ndefn search-50-random-drawers(prisoner-number drawers):\n :: Select 50 random drawers and return true if the prisoner's number was\n found.\n\n drawers:\n .shuffle()\n .take(50)\n .filter(eq(prisoner-number))\n .count()\n .eq(1)\n\ndefn random-drawers():\n :: Returns a list of shuffled numbers.\n\n shuffle: range(100)\n", "safe": true }, { "filename": "100_prisoners_19.txt", "content": "NumOfTrials := 20000\nrandomFailTotal := 0, strategyFailTotal := 0\nprisoners := [], drawers := [], Cards := []\nloop, 100\n\tprisoners[A_Index] := A_Index\t\t\t\t; create prisoners\n\t, drawers[A_Index] := true\t\t\t\t; create drawers\n\nloop, % NumOfTrials\n{\n\tloop, 100\n\t\tCards[A_Index] := A_Index\t\t\t; create cards for this iteration\n\tloop, 100\n\t{\n\t\tRandom, rnd, 1, Cards.count()\n\t\tdrawers[A_Index] := Cards.RemoveAt(rnd)\t\t; randomly place cards in drawers\n\t}\n\t;-------------------------------------------\n\t; randomly open drawers\n\tRandomList := []\n\tloop, 100\n\t\tRandomList[A_Index] := A_Index\n\tFail := false\n\twhile (A_Index <=100) && !Fail\n\t{\n\t\tthisPrisoner := A_Index\n\t\tres := \"\"\n\t\twhile (thisCard <> thisPrisoner) && !Fail\n\t\t{\n\t\t\tRandom, rnd, 1, % RandomList.Count()\t; choose random number\n\t\t\tNextDrawer := RandomList.RemoveAt(rnd)\t; remove drawer from random list (don't choose more than once)\n\t\t\tthisCard := drawers[NextDrawer]\t\t; get card from this drawer\n\t\t\tif (A_Index > 50)\n\t\t\t\tFail := true\n\t\t}\n\t\tif Fail\n\t\t\trandomFailTotal++\n\t}\n\t;-------------------------------------------\n\t; use optimal strategy\n\tFail := false\n\twhile (A_Index <=100) && !Fail\n\t{\n\t\tcounter := 1, thisPrisoner := A_Index\n\t\tNextDrawer := drawers[thisPrisoner]\t\t; 1st trial, drawer whose outside number is prisoner number\n\t\twhile (drawers[NextDrawer] <> thisPrisoner) && !Fail\n\t\t{\t\n\t\t\tNextDrawer := drawers[NextDrawer]\t; drawer with the same number as that of the revealed card\n\t\t\tif ++counter > 50\n\t\t\t\tFail := true\n\t\t}\n\t\tif Fail\n\t\t\tstrategyFailTotal++\n\t}\n}\nMsgBox % \"Number Of Trials = \" NumOfTrials\n\t\t. \"`nOptimal Strategy:`t\" (1 - strategyFailTotal/NumOfTrials) *100 \"\u00a0% success rate\" \n\t\t. \"`nRandom Trials:`t\" (1 - randomFailTotal/NumOfTrials) *100 \"\u00a0% success rate\"\n", "safe": true }, { "filename": "100_prisoners_190.txt", "content": "const std = @import(\"std\");\n\npub const Cupboard = struct {\n comptime {\n std.debug.assert(u7 == std.math.IntFittingRange(0, 100));\n }\n\n pub const Drawer = packed struct(u8) {\n already_visited: bool,\n card: u7,\n };\n\n drawers: [100]Drawer,\n randomizer: std.rand.Random,\n\n /// Cupboard is not shuffled after initialization,\n /// it is shuffled during `play` execution.\n pub fn init(random: std.rand.Random) Cupboard {\n var drawers: [100]Drawer = undefined;\n for (&drawers, 0..) |*drawer, i| {\n drawer.* = .{\n .already_visited = false,\n .card = @intCast(i),\n };\n }\n\n return .{\n .drawers = drawers,\n .randomizer = random,\n };\n }\n\n pub const Decision = enum {\n pardoned,\n sentenced,\n };\n\n pub const Strategy = enum {\n follow_card,\n random,\n\n pub fn decisionOfPrisoner(strategy: Strategy, cupboard: *Cupboard, prisoner_id: u7) Decision {\n switch (strategy) {\n .random => {\n return for (0..50) |_| {\n // If randomly chosen drawer was already opened,\n // throw dice again.\n const drawer = try_throw_random: while (true) {\n const random_i = cupboard.randomizer.uintLessThan(u7, 100);\n const drawer = &cupboard.drawers[random_i];\n\n if (!drawer.already_visited)\n break :try_throw_random drawer;\n };\n std.debug.assert(!drawer.already_visited);\n defer drawer.already_visited = true;\n\n if (drawer.card == prisoner_id)\n break .pardoned;\n } else .sentenced;\n },\n .follow_card => {\n var drawer_i = prisoner_id;\n return for (0..50) |_| {\n const drawer = &cupboard.drawers[drawer_i];\n std.debug.assert(!drawer.already_visited);\n defer drawer.already_visited = true;\n\n if (drawer.card == prisoner_id)\n break .pardoned\n else\n drawer_i = drawer.card;\n } else .sentenced;\n },\n }\n }\n };\n\n pub fn play(cupboard: *Cupboard, strategy: Strategy) Decision {\n cupboard.randomizer.shuffleWithIndex(Drawer, &cupboard.drawers, u7);\n\n // Decisions for all 100 prisoners.\n var all_decisions: [100]Decision = undefined;\n for (&all_decisions, 0..) |*current_decision, prisoner_id| {\n // Make decision for current prisoner\n current_decision.* = strategy.decisionOfPrisoner(cupboard, @intCast(prisoner_id));\n\n // Close all drawers after one step.\n for (&cupboard.drawers) |*drawer|\n drawer.already_visited = false;\n }\n\n // If there is at least one sentenced person, everyone are sentenced.\n return for (all_decisions) |decision| {\n if (decision == .sentenced)\n break .sentenced;\n } else .pardoned;\n }\n\n pub fn runSimulation(cupboard: *Cupboard, strategy: Cupboard.Strategy, total: u32) void {\n var success: u32 = 0;\n for (0..total) |_| {\n const result = cupboard.play(strategy);\n if (result == .pardoned) success += 1;\n }\n\n const ratio = @as(f32, @floatFromInt(success)) / @as(f32, @floatFromInt(total));\n\n const stdout = std.io.getStdOut();\n const stdout_w = stdout.writer();\n\n stdout_w.print(\n \\\\\n \\\\Strategy: {s}\n \\\\Total runs: {d}\n \\\\Successful runs: {d}\n \\\\Failed runs: {d}\n \\\\Success rate: {d:.4}%.\n \\\\\n , .{\n @tagName(strategy),\n total,\n success,\n total - success,\n ratio * 100.0,\n }) catch {}; // Do nothing on error\n }\n};\n", "safe": true }, { "filename": "100_prisoners_191.txt", "content": "const std = @import(\"std\");\n\npub fn main() std.os.GetRandomError!void {\n var prnd = std.rand.DefaultPrng.init(seed: {\n var init_seed: u64 = undefined;\n try std.os.getrandom(std.mem.asBytes(&init_seed));\n break :seed init_seed;\n });\n const random = prnd.random();\n\n var cupboard = Cupboard.init(random);\n\n cupboard.runSimulation(.follow_card, 10_000);\n cupboard.runSimulation(.random, 10_000);\n}\n", "safe": true }, { "filename": "100_prisoners_192.txt", "content": "\n\nStrategy: follow_card\nTotal runs: 10000\nSuccessful runs: 3049\nFailed runs: 6951\nSuccess rate: 30.4900%.\n\nStrategy: random\nTotal runs: 10000\nSuccessful runs: 0\nFailed runs: 10000\nSuccess rate: 0.0000%.\n\n", "safe": true }, { "filename": "100_prisoners_193.txt", "content": "const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000;\nfcn oneHundredJDI{\t// just do it strategy\n cupboard,picks\u00a0:= [0..SLOTS-1].walk().shuffle(), cupboard.copy();\n // if this prisoner can't find their number in TRIES, all fail\n foreach p in (PRISONERS){ if(picks.shuffle().find(p)>=TRIES) return(False); }\n True\t\t// all found their number\n}\nfcn oneHundredO{\t// Optimal strategy\n cupboard\u00a0:= [0..SLOTS-1].walk().shuffle();\n foreach p in (PRISONERS){\n d:=p;\n do(TRIES){ if((d=cupboard[d]) == p) continue(2) } // found my number\n return(False); // this prisoner failed to find their number, all fail\n }\n True\t\t// all found their number\n}", "safe": true }, { "filename": "100_prisoners_194.txt", "content": "s:=N.pump(Ref(0).incN,oneHundredJDI).value.toFloat()/N*100;\nprintln(\"Just do it strategy (%,d simulatations):\u00a0%.2f%%\".fmt(N,s));\n\ns:=N.pump(Ref(0).incN,oneHundredO).value.toFloat()/N*100;\nprintln(\"Optimal strategy (%,d simulatations):\u00a0%.2f%%\".fmt(N,s));", "safe": true }, { "filename": "100_prisoners_195.txt", "content": "Just do it strategy (10,000 simulatations): 0.00%\nOptimal strategy (10,000 simulatations): 31.16%\n", "safe": true }, { "filename": "100_prisoners_196.txt", "content": "const SLOTS=100, PRISONERS=10, TRIES=50, N=100_000;", "safe": true }, { "filename": "100_prisoners_197.txt", "content": "Just do it strategy (100,000 simulatations): 0.09%\nOptimal strategy (100,000 simulatations): 31.13%\n", "safe": true }, { "filename": "100_prisoners_2.txt", "content": " Simulation count: 100000\n Random play wins: 0.0% of simulations\nOptimal play wins: 31.1% of simulations\n", "safe": true }, { "filename": "100_prisoners_20.txt", "content": "Number Of Trials = 20000\nOptimal Strategy:\t33.275000\u00a0% success rate\nRandom Trials \u00a0:\t0.000000\u00a0% success rate", "safe": true }, { "filename": "100_prisoners_21.txt", "content": "O = 50\nN = 2*O\niterations = 10000\n\nREM From the numbers 0 to N-1 inclusive, pick O of them.\nfunction shuffle(N, O)\n dim array(N)\n for i = 0 to N-1\n array[i] = i\n next i\n for i = 0 to O-1\n swapindex = i + rand*(N-i)\n swapvalue = array[swapindex]\n array[swapindex] = array[i]\n array[i] = swapvalue\n next i\n return array\nend function\n\nREM given N drawers with O to open, prisoner P chooses randomly: does he choose well?\nfunction chooserandom(drawers, N, O, p)\n choices = shuffle(N, O)\n for i = 0 to O-1\n if drawers[choices[i]] = p then return true\n next i\n return false\nend function\n\nREM N prisoners randomly choose O drawers to open: do they all choose well?\nfunction allchooserandom(N, O)\n drawers = shuffle(N, N)\n for p = 0 to N-1\n goodchoice = chooserandom(drawers, N, O, p)\n if not goodchoice then return false\n next p\n return true\nend function\n\nREM given N drawers with O to open, prisoner P chooses smartly: does he choose well?\nfunction choosesmart(drawers, N, O, p)\n numopened = 0\n i = p\n while numopened < O\n numopened += 1\n if drawers[i] = p then return true\n i = drawers[i]\n end while\n return false\nend function\n\nREM N prisoners smartly choose O drawers to open: do they all choose well?\nfunction allchoosesmart(N, O)\n drawers = shuffle(N, N)\n for p = 0 to N-1\n goodchoice = choosesmart(drawers, N, O, p)\n if not goodchoice then return false\n next p\n return true\nend function\n\ncls\nprint N; \" prisoners choosing \";O;\" drawers, \";iterations;\" iterations:\"\n\ntotal = 0\nfor iteration = 1 to iterations\n if allchooserandom(N, O) then total += 1\nnext iteration\n\nprint \"Random choices: \"; total;\" out of \";iterations\nprint \"Observed ratio: \"; total/iterations; \", expected ratio: \"; (O/N)^N\n\ntotal = 0\nfor iteration = 1 to iterations\n if allchoosesmart(N, O) then total += 1\nnext iteration\n\nprint \"Smart choices: \"; total;\" out of \";iterations\nprint \"Observed ratio: \"; total/iterations; \", expected ratio with N=2*O: greater than about 0.30685\": REM for N=100, O=50 particularly, about 0.3118", "safe": true }, { "filename": "100_prisoners_22.txt", "content": "100 prisoners choosing 50 drawers, 10000 iterations:\nRandom choices: 0 out of 10000\nObserved ratio: 0.0, expected ratio: 0.0\nSmart choices: 3052 out of 10000\nObserved ratio: 0.3052, expected ratio with N=2*O: greater than about 0.30685\n", "safe": true }, { "filename": "100_prisoners_23.txt", "content": "FUNCTION trials(prisoners, iterations, optimal)\n DIM drawers(100)\n FOR i = 1 TO prisoners\n LET drawers(i) = i\n NEXT i\n FOR i = 1 TO iterations\n FOR k = 1 TO prisoners\n LET x = RND+1\n LET p = drawers(x)\n LET drawers(x) = drawers(k)\n LET drawers(k) = p\n NEXT k\n FOR prisoner = 1 TO prisoners\n LET found = false\n IF optimal<>0 THEN LET drawer = prisoner ELSE LET drawer = RND+1\n FOR j = 1 TO prisoners/2\n LET drawer = drawers(drawer)\n IF drawer = prisoner THEN\n LET found = true\n EXIT FOR\n END IF\n IF (NOT optimal<>0) THEN LET drawer = RND+1\n NEXT j\n IF (NOT found<>0) THEN EXIT FOR\n NEXT prisoner\n LET pardoned = pardoned+found\n NEXT i\n LET trials = (100*pardoned/iterations)\nEND FUNCTION\n\nLET false = 0\nLET true = 1\nLET iterations = 10000\nPRINT \"Simulation count: \"; iterations\nFOR prisoners = 10 TO 100 STEP 90\n LET randon = trials(prisoners,iterations,false)\n LET optimal = trials(prisoners,iterations,true)\n PRINT \"Prisoners: \"; prisoners; \", random: \"; randon; \", optimal: \"; optimal\nNEXT prisoners\nEND\n", "safe": true }, { "filename": "100_prisoners_24.txt", "content": "get \"libhdr\"\n\nmanifest $( \n seed = 12345 // for pseudorandom number generator\n size = 100 // amount of drawers and prisoners\n tries = 50 // amount of tries each prisoner may make\n simul = 2000 // amount of simulations to run\n$)\n\nlet randto(n) = valof\n$( static $( state = seed $)\n let mask = 1\n mask\u00a0:= (mask<<1)|1 repeatuntil mask > n\n state\u00a0:= random(state) repeatuntil ((state >> 8) & mask) < n \n resultis (state >> 8) & mask\n$)\n\n// initialize drawers\nlet placeCards(d, n) be\n$( for i=0 to n-1 do d!i\u00a0:= i;\n for i=0 to n-2 do\n $( let j = i+randto(n-i)\n let k = d!i\n d!i\u00a0:= d!j\n d!j\u00a0:= k\n $)\n$)\n\n// random strategy (prisoner 'p' tries to find his own number)\nlet randoms(d, p, t) = valof\n$( for n = 1 to t do\n if d!randto(size) = p then resultis true\n resultis false \n$)\n\n// optimal strategy\nlet optimal(d, p, t) = valof\n$( let last = p\n for n = 1 to t do\n test d!last = p \n then resultis true\n else last\u00a0:= d!last\n resultis false\n$)\n\n// run a simulation given a strategy\nlet simulate(d, strat, n, t) = valof\n$( placeCards(d, n)\n for p = 0 to n-1 do\n if not strat(d, p, t) then resultis false\n resultis true\n$)\n\n// run many simulations and count the successes\nlet runSimulations(d, strat, n, amt, t) = valof\n$( let succ = 0\n for i = 1 to amt do\n if simulate(d, strat, n, t) do\n succ\u00a0:= succ + 1\n resultis succ\n$)\n\nlet run(d, name, strat, n, amt, t) be\n$( let s = runSimulations(d, strat, n, amt, t);\n writef(\"%S: %I5 of %I5, %N percent.*N\", name, s, amt, s*10/(amt/10))\n$)\n\nlet start() be\n$( let d = vec size-1\n run(d, \" Random\", randoms, size, simul, tries)\n run(d, \"Optimal\", optimal, size, simul, tries)\n$)", "safe": true }, { "filename": "100_prisoners_25.txt", "content": " Random: 0 of 2000, 0 percent.\nOptimal: 698 of 2000, 34 percent.", "safe": true }, { "filename": "100_prisoners_26.txt", "content": "#include\n#include\n#include\n#include\n\n#define LIBERTY false\n#define DEATH true\n\ntypedef struct{\n\tint cardNum;\n\tbool hasBeenOpened;\n}drawer;\n\ndrawer *drawerSet;\n\nvoid initialize(int prisoners){\n\tint i,j,card;\n\tbool unique;\n\n\tdrawerSet = ((drawer*)malloc(prisoners * sizeof(drawer))) -1;\n\n\tcard = rand()%prisoners + 1;\n\tdrawerSet[1] = (drawer){.cardNum = card, .hasBeenOpened = false};\n\n\tfor(i=1 + 1;i \",argv[0]);\n\n\tprisoners = atoi(argv[1]);\n\tchances = atoi(argv[2]);\n\ttrials = strtoull(argv[3],&end,10);\n\n\tsrand(time(NULL));\n\n\tprintf(\"Running random trials...\");\n\tfor(i=0;i Guid.NewGuid()).ToList();\n\n for (int p = 0; p < 100; p++) {\n bool success = false;\n\n var choice = p;\n for (int i = 0; i < 50; i++) {\n if (secrets[choice] == p) {\n success = true;\n break;\n }\n choice = secrets[choice];\n }\n\n if (!success) {\n return false;\n }\n }\n\n return true;\n }\n\n static bool PlayRandom() {\n var secrets = Enumerable.Range(0, 100).OrderBy(a => Guid.NewGuid()).ToList();\n\n for (int p = 0; p < 100; p++) {\n var choices = Enumerable.Range(0, 100).OrderBy(a => Guid.NewGuid()).ToList();\n\n bool success = false;\n for (int i = 0; i < 50; i++) {\n if (choices[i] == p) {\n success = true;\n break;\n }\n }\n\n if (!success) {\n return false;\n }\n }\n\n return true;\n }\n\n static double Exec(uint n, Func play) {\n uint success = 0;\n for (uint i = 0; i < n; i++) {\n if (play()) {\n success++;\n }\n }\n return 100.0 * success / n;\n }\n\n static void Main() {\n const uint N = 1_000_000;\n Console.WriteLine(\"# of executions: {0}\", N);\n Console.WriteLine(\"Optimal play success rate: {0:0.00000000000}%\", Exec(N, PlayOptimal));\n Console.WriteLine(\" Random play success rate: {0:0.00000000000}%\", Exec(N, PlayRandom));\n }\n }\n}\n", "safe": true }, { "filename": "100_prisoners_29.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.21310000000%\n Random play success rate: 0.00000000000%", "safe": true }, { "filename": "100_prisoners_3.txt", "content": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program prisonniex64.s */ \n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBDOORS, 100\n.equ NBLOOP, 1000\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .asciz \"Random strategie \u00a0: @ sur 1000 \\n\"\nsMessResultOPT: .asciz \"Optimal strategie\u00a0: @ sur 1000 \\n\"\nszCarriageReturn: .asciz \"\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\nsZoneConv: .skip 24\ntbDoors: .skip 8 * NBDOORS \ntbTest: .skip 8 * NBDOORS\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: // entry of program \n \n ldr x1,qAdrtbDoors\n mov x2,#0\n1: // loop init doors table\n add x3,x2,#1\n str x3,[x1,x2,lsl #3]\n add x2,x2,#1\n cmp x2,#NBDOORS\n blt 1b\n \n mov x9,#0 // loop counter\n mov x10,#0 // counter successes random strategie\n mov x11,#0 // counter successes optimal strategie\n2:\n ldr x0,qAdrtbDoors\n mov x1,#NBDOORS\n bl knuthShuffle\n \n ldr x0,qAdrtbDoors\n bl aleaStrategie\n cmp x0,#NBDOORS\n cinc x10,x10,eq\n \n ldr x0,qAdrtbDoors\n bl optimaStrategie\n cmp x0,#NBDOORS\n cinc x11,x11,eq\n \n add x9,x9,#1\n cmp x9,#NBLOOP\n blt 2b\n \n mov x0,x10 // result display\n ldr x1,qAdrsZoneConv\n bl conversion10 // call decimal conversion\n ldr x0,qAdrsMessResult\n ldr x1,qAdrsZoneConv // insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n mov x0,x11 // result display\n ldr x1,qAdrsZoneConv\n bl conversion10 // call decimal conversion\n ldr x0,qAdrsMessResultOPT\n ldr x1,qAdrsZoneConv // insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n \n100: // standard end of the program \n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n \nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsMessResult: .quad sMessResult\nqAdrsMessResultOPT: .quad sMessResultOPT\nqAdrtbDoors: .quad tbDoors\nqAdrtbTest: .quad tbTest\nqAdrsZoneConv: .quad sZoneConv\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* x0 contains the address of table */\naleaStrategie:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n stp x6,x7,[sp,-16]! // save registres\n stp x8,x9,[sp,-16]! // save registres\n ldr x6,qAdrtbTest // table doors tests address\n mov x8,x0 // save table doors address\n mov x4,#0 // counter number of successes\n mov x2,#0 // prisonners indice\n1:\n bl razTable // zero to table doors tests\n mov x5,#0 // counter of door tests \n add x7,x2,#1\n2:\n mov x0,#1\n mov x1,#NBDOORS\n bl extRandom // random test\n ldr x3,[x6,x0,lsl #3] // doors also tested\u00a0?\n cmp x3,#0 \n bne 2b // yes\n ldr x3,[x8,x0,lsl #3] // load N\u00b0 door\n cmp x3,x7 // compar N\u00b0 door N\u00b0 prisonner\n cinc x4,x4,eq\n beq 3f\n mov x3,#1 // top test table item \n str x3,[x6,x0,lsl #3]\n add x5,x5,#1\n cmp x5,#NBDOORS / 2 // number tests maxi\u00a0?\n blt 2b // no -> loop\n3:\n add x2,x2,#1 // other prisonner\n cmp x2,#NBDOORS\n blt 1b\n \n mov x0,x4 // return number of successes \n100:\n ldp x8,x9,[sp],16 // restaur des 2 registres\n ldp x6,x7,[sp],16 // restaur des 2 registres\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* raz test table */ \n/******************************************************************/\nrazTable:\n stp x0,lr,[sp,-16]! // save registres\n stp x1,x2,[sp,-16]! // save registres\n ldr x0,qAdrtbTest\n mov x1,#0 // item indice\n mov x2,#0\n1:\n str x2,[x0,x1,lsl #3] // store zero \u00e0 item\n add x1,x1,#1\n cmp x1,#NBDOORS\n blt 1b\n100:\n ldp x1,x2,[sp],16 // restaur des 2 registres\n ldp x0,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* random door test strategy */ \n/******************************************************************/\n/* x0 contains the address of table */\noptimaStrategie:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n mov x4,#0 // counter number of successes\n mov x2,#0 // counter prisonner\n1:\n mov x5,#0 // counter test\n mov x1,x2 // first test = N\u00b0 prisonner\n2:\n ldr x3,[x0,x1,lsl #3] // load N\u00b0 door\n cmp x3,x2\n cinc x4,x4,eq // equal -> succes\n beq 3f\n mov x1,x3 // new test with N\u00b0 door\n add x5,x5,#1 \n cmp x5,#NBDOORS / 2 // test number maxi\u00a0?\n blt 2b\n3:\n add x2,x2,#1 // other prisonner\n cmp x2,#NBDOORS\n blt 1b\n \n mov x0,x4\n100:\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n/******************************************************************/\n/* knuth Shuffle */ \n/******************************************************************/\n/* x0 contains the address of table */\n/* x1 contains the number of elements */\nknuthShuffle:\n stp x1,lr,[sp,-16]! // save registres\n stp x2,x3,[sp,-16]! // save registres\n stp x4,x5,[sp,-16]! // save registres\n stp x6,x7,[sp,-16]! // save registers\n mov x5,x0 // save table address\n mov x6,x1 // save number of elements\n mov x2,0 // start index\n1:\n mov x0,0\n mov x1,x2 // generate aleas\n bl extRandom\n ldr x3,[x5,x2,lsl #3] // swap number on the table\n ldr x4,[x5,x0,lsl #3]\n str x4,[x5,x2,lsl #3]\n str x3,[x5,x0,lsl #3]\n add x2,x2,#1 // next number\n cmp x2,x6 // end\u00a0?\n blt 1b // no -> loop\n100:\n ldp x6,x7,[sp],16 // restaur des 2 registres\n ldp x4,x5,[sp],16 // restaur des 2 registres\n ldp x2,x3,[sp],16 // restaur des 2 registres\n ldp x1,lr,[sp],16 // restaur des 2 registres\n ret\n\n/******************************************************************/\n/* random number */ \n/******************************************************************/\n/* x0 contains inferior value */\n/* x1 contains maxi value */\n/* x0 return random number */\nextRandom:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x8,[sp,-16]! // save registers\n stp x3,x4,[sp,-16]! // save registers\n stp x19,x20,[sp,-16]! // save registers\n sub sp,sp,16 // reserve 16 octets on stack\n mov x19,x0\n add x20,x1,1\n mov x0,sp // store result on stack\n mov x1,8 // length 8 bytes\n mov x2,0\n mov x8,278 // call system Linux 64 bits Urandom\n svc 0\n mov x0,sp // load r\u00e9sult on stack\n ldr x0,[x0]\n sub x2,x20,x19 // calculation of the range of values \n udiv x1,x0,x2 // calculation range modulo\n msub x0,x1,x2,x0\n add x0,x0,x19 // and add inferior value\n100:\n add sp,sp,16 // alignement stack \n ldp x19,x20,[sp],16 // restaur 2 registers\n ldp x3,x4,[sp],16 // restaur 2 registers\n ldp x2,x8,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"", "safe": true }, { "filename": "100_prisoners_30.txt", "content": "#include // for rand\n#include // for random_shuffle\n#include // for output\n\nusing namespace std;\n\nclass cupboard {\npublic:\n cupboard() {\n for (int i = 0; i < 100; i++)\n drawers[i] = i;\n random_shuffle(drawers, drawers + 100);\n }\n\n bool playRandom();\n bool playOptimal();\n\nprivate:\n int drawers[100];\n};\n\nbool cupboard::playRandom() {\n bool openedDrawers[100] = { 0 };\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { // loops through prisoners numbered 0 through 99\n bool prisonerSuccess = false;\n for (int i = 0; i < 100 / 2; i++) { // loops through 50 draws for each prisoner\n int drawerNum = rand() % 100;\n if (!openedDrawers[drawerNum]) {\n openedDrawers[drawerNum] = true;\n break;\n }\n if (drawers[drawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n }\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\nbool cupboard::playOptimal() {\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) {\n bool prisonerSuccess = false;\n int checkDrawerNum = prisonerNum;\n for (int i = 0; i < 100 / 2; i++) {\n if (drawers[checkDrawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n } else\n checkDrawerNum = drawers[checkDrawerNum];\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\ndouble simulate(char strategy) {\n int numberOfSuccesses = 0;\n for (int i = 0; i < 10000; i++) {\n cupboard d;\n if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) // will run playRandom or playOptimal but not both because of short-circuit evaluation\n numberOfSuccesses++;\n }\n\n return numberOfSuccesses * 100.0 / 10000;\n}\n\nint main() {\n cout << \"Random strategy: \" << simulate('R') << \"\u00a0%\" << endl;\n cout << \"Optimal strategy: \" << simulate('O') << \"\u00a0%\" << endl;\n system(\"PAUSE\"); // for Windows\n return 0;\n}\n", "safe": true }, { "filename": "100_prisoners_31.txt", "content": "Random strategy: 0\u00a0%\nOptimal strategy: 31.54\u00a0%", "safe": true }, { "filename": "100_prisoners_32.txt", "content": "(ns clojure-sandbox.prisoners)\n\n(defn random-drawers []\n \"Returns a list of shuffled numbers\"\n (-> 100\n range\n shuffle))\n\n(defn search-50-random-drawers [prisoner-number drawers]\n \"Select 50 random drawers and return true if the prisoner's number was found\"\n (->> drawers\n shuffle ;; Put drawer contents in random order\n (take 50) ;; Select first 50, equivalent to selecting 50 random drawers\n (filter (fn [x] (= x prisoner-number))) ;; Filter to include only those that match prisoner number\n count\n (= 1))) ;; Returns true if the number of matching numbers is 1\n\n(defn search-50-optimal-drawers [prisoner-number drawers]\n \"Open 50 drawers according to the agreed strategy, returning true if prisoner's number was found\"\n (loop [next-drawer prisoner-number ;; The drawer index to start on is the prisoner's number\n drawers-opened 0] ;; To keep track of how many have been opened as 50 is the maximum\n (if (= drawers-opened 50)\n false ;; If 50 drawers have been opened, the prisoner's number has not been found\n (let [result (nth drawers next-drawer)] ;; Open the drawer given by next number\n (if (= result prisoner-number) ;; If prisoner number has been found\n true ;; No need to keep opening drawers - return true\n (recur result (inc drawers-opened))))))) ;; Restart the loop using the resulting number as the drawer number\n\n(defn try-luck [drawers drawer-searching-function]\n \"Returns 1 if all prisoners find their number otherwise 0\"\n (loop [prisoners (range 100)] ;; Start with 100 prisoners\n (if (empty? prisoners) ;; If they've all gone and found their number\n 1 ;; Return true- they'll all live\n (let [res (-> prisoners\n first\n (drawer-searching-function drawers))] ;; Otherwise, have the first prisoner open drawers according to the specified method\n (if (false? res) ;; If this prisoner didn't find their number\n 0 ;; no prisoners will be freed so we can return false and stop\n (recur (rest prisoners))))))) ;; Otherwise they've found the number, so we remove them from the queue and repeat with the others\n\n(defn simulate-100-prisoners []\n \"Simulates all prisoners searching the same drawers by both strategies, returns map showing whether each was successful\"\n (let [drawers (random-drawers)] ;; Create 100 drawers with randomly ordered prisoner numbers\n {:random (try-luck drawers search-50-random-drawers) ;; True if all prisoners found their number using random strategy\n :optimal (try-luck drawers search-50-optimal-drawers)})) ;; True if all prisoners found their number using optimal strategy\n\n(defn simulate-n-runs [n]\n \"Simulate n runs of the 100 prisoner problem and returns a success count for each search method\"\n (loop [random-successes 0\n optimal-successes 0\n run-count 0]\n (if (= n run-count) ;; If we've done the loop n times\n {:random-successes random-successes ;; return results\n :optimal-successes optimal-successes\n :run-count run-count}\n (let [next-result (simulate-100-prisoners)] ;; Otherwise, run for another batch of prisoners\n (recur (+ random-successes (:random next-result)) ;; Add result of run to the total successs count\n (+ optimal-successes (:optimal next-result))\n (inc run-count)))))) ;; increment run count and run again\n\n(defn -main [& args]\n \"For 5000 runs, print out the success frequency for both search methods\"\n (let [{:keys [random-successes optimal-successes run-count]} (simulate-n-runs 5000)]\n (println (str \"Probability of survival with random search: \" (float (/ random-successes run-count))))\n (println (str \"Probability of survival with ordered search: \" (float (/ optimal-successes run-count))))))\n", "safe": true }, { "filename": "100_prisoners_33.txt", "content": "Probability of survival with random search: 0.0\nProbability of survival with ordered search: 0.3062\n", "safe": true }, { "filename": "100_prisoners_34.txt", "content": "% This program needs to be merged with PCLU's \"misc\" library\n% to use the random number generator.\n%\n% pclu -merge $CLUHOME/lib/misc.lib -compile prisoners.clu\n\n% Seed the random number generator with the current time\ninit_rng = proc ()\n d: date\u00a0:= now()\n seed: int\u00a0:= ((d.hour*60) + d.minute)*60 + d.second\n random$seed(seed)\nend init_rng\n\n% Place cards in drawers randomly\nmake_drawers = proc (n: int) returns (sequence[int])\n d: array[int]\u00a0:= array[int]$predict(1,n)\n \n \u00a0% place each card in its own drawer\n for i: int in int$from_to(1,n) do\n array[int]$addh(d,i)\n end\n \n \u00a0% shuffle the cards\n for i: int in int$from_to_by(n,2,-1) do\n j: int\u00a0:= random$next(i)+1\n t: int\u00a0:= d[i]\n d[i]\u00a0:= d[j]\n d[j]\u00a0:= t\n end\n return(sequence[int]$a2s(d))\nend make_drawers\n\n% Random strategy\nrand_strat = proc (p, tries: int, d: sequence[int]) returns (bool)\n n: int\u00a0:= sequence[int]$size(d)\n for i: int in int$from_to(1,tries) do\n if p = d[random$next(n)+1] then return(true) end\n end\n return(false)\nend rand_strat\n\n% Optimal strategy\nopt_strat = proc (p, tries: int, d: sequence[int]) returns (bool)\n last: int\u00a0:= p\n for i: int in int$from_to(1,tries) do\n if d[last]=p then return(true) end\n last\u00a0:= d[last]\n end\n return(false)\nend opt_strat\n\n% Run one simulation given a strategy\nsimulate = proc (n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n returns (bool)\n d: sequence[int]\u00a0:= make_drawers(n)\n for p: int in int$from_to(1,n) do\n \u00a0% If one prisoner fails, they all hang\n if ~strat(p,tries,d) then return(false) end\n end\n return(true)\nend simulate\n\n% Run many simulations and count the successes\nrun_simulations = proc (amount, n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n returns (int)\n ok: int\u00a0:= 0\n for i: int in int$from_to(1,amount) do\n if simulate(n,tries,strat) then\n ok\u00a0:= ok + 1\n end\n end\n return(ok)\nend run_simulations\n\n% Run simulations and show the results\nshow = proc (title: string,\n amount, n, tries: int,\n strat: proctype (int,int,sequence[int]) returns (bool))\n po: stream\u00a0:= stream$primary_output()\n stream$puts(po, title || \": \")\n \n ok: int\u00a0:= run_simulations(amount, n, tries, strat)\n perc: real\u00a0:= real$i2r(ok)*100.0/real$i2r(amount)\n \n stream$putright(po, int$unparse(ok), 7)\n stream$puts(po, \" out of \")\n stream$putright(po, int$unparse(amount), 7)\n stream$putl(po, \", \" || f_form(perc, 3, 2) || \"%\")\nend show \n\nstart_up = proc ()\n prisoners = 100\n tries = 50\n simulations = 50000\n \n init_rng()\n\n show(\" Random\", simulations, prisoners, tries, rand_strat)\n show(\"Optimal\", simulations, prisoners, tries, opt_strat)\nend start_up", "safe": true }, { "filename": "100_prisoners_35.txt", "content": " Random: 0 out of 50000, 0.00%\nOptimal: 15541 out of 50000, 31.08%", "safe": true }, { "filename": "100_prisoners_36.txt", "content": "10 rem 100 prisoners\n20 rem set arrays\n30 rem dr = drawers containing card values\n40 rem ig = a list of numbers 1 through 100, shuffled to become the \n41 rem guess sequence for each inmate - method 1\n50 dim dr(100),ig(100)\n55 rem initialize drawers with own card in each drawer\n60 for i=1 to 100:dr(i)=i:next \n\n1000 print chr$(147);\"how many trials for each method\";:input tt\n1010 for m=1 to 2:su(m)=0:fa(m)=0\n1015 for tn=1 to tt\n1020 on m gosub 2000,3000\n1025 rem ip = number of inmates who passed\n1030 if ip=100 then su(m)=su(m)+1\n1040 if ip<100 then fa(m)=fa(m)+1\n1045 next tn\n1055 next m\n\n1060 print chr$(147);\"Results:\":print\n1070 print \"Out of\";tt;\"trials, the results are\"\n1071 print \"as follows...\":print\n1072 print \"1. Random Guessing:\"\n1073 print \" \";su(1);\"successes\"\n1074 print \" \";fa(1);\"failures\"\n1075 print \" \";su(1)/tn;\"{left-crsr}% success rate.\":print\n1077 print \"2. Chained Number Picking:\"\n1078 print \" \";su(2);\"successes\"\n1079 print \" \";fa(2);\"failures\"\n1080 print \" \";(su(2)/tn)*100;\"{left-crsr}% success rate.\":print\n1100 print:print \"Again?\"\n1110 get k$:if k$=\"\" then 1110\n1120 if k$=\"y\" then 1000\n1500 end\n\n2000 rem random guessing method\n2005 for x=1 to 100:ig(x)=x:next:ip=0:gosub 4000\n2007 for i=1 to 100\n2010 for x=1 to 100:t=ig(x):np=int(rnd(1)*100)+1:ig(x)=ig(np):ig(np)=t:next\n2015 for g=1 to 50\n2020 if dr(ig(g))=i then ip=ip+1:next i:return\n2025 next g\n2030 return\n\n3000 rem chained method\n3005 ip=0:gosub 4000\n3007 rem iterate through each inmate\n3010 fori=1to100\n3015 ng=i:forg=1to50\n3020 cd=dr(ng)\n3025 ifcd=ithenip=ip+1:nexti:return\n3030 ifcd<>ithenng=cd\n3035 nextg:return\n\n4000 rem shuffle the drawer cards randomly\n4010 x=rnd(-ti)\n4020 for i=1 to 100\n4030 r=int(rnd(1)*100)+1:t=dr(i):dr(i)=dr(r):dr(r)=t:next\n4040 return\n", "safe": true }, { "filename": "100_prisoners_37.txt", "content": "Results:\n\nOut of 4000 trials the percentage of\nsuccess is as follows...\n\n1. Random Guessing:\n 0 successes\n 4000 failures\n 0% success rate.\n\n2. Chained Number Picking:\n 1274 successes\n 2726 failures\n 31.85% success rate.\n", "safe": true }, { "filename": "100_prisoners_38.txt", "content": "(defparameter *samples* 10000)\n(defparameter *prisoners* 100)\n(defparameter *max-guesses* 50)\n\n(defun range (n)\n \"Returns a list from 0 to N.\"\n (loop\n for i below n\n collect i))\n\n(defun nshuffle (list)\n \"Returns a shuffled LIST.\"\n (loop\n for i from (length list) downto 2\n do (rotatef (nth (random i) list)\n (nth (1- i) list)))\n list)\n\n(defun build-drawers ()\n \"Returns a list of shuffled drawers.\"\n (nshuffle (range *prisoners*)))\n\n(defun strategy-1 (drawers p)\n \"Returns T if P is found in DRAWERS under *MAX-GUESSES* using a random strategy.\"\n (loop\n for i below *max-guesses*\n thereis (= p (nth (random *prisoners*) drawers))))\n\n(defun strategy-2 (drawers p)\n \"Returns T if P is found in DRAWERS under *MAX-GUESSES* using an optimal strategy.\"\n (loop\n for i below *max-guesses*\n for j = p then (nth j drawers)\n thereis (= p (nth j drawers))))\n\n(defun 100-prisoners-problem (strategy &aux (drawers (build-drawers)))\n \"Returns T if all prisoners find their number using the given STRATEGY.\"\n (every (lambda (e) (eql T e))\n (mapcar (lambda (p) (funcall strategy drawers p)) (range *prisoners*))))\n\n(defun sampling (strategy)\n (loop\n repeat *samples*\n for result = (100-prisoners-problem strategy) \n count result))\n\n(defun compare-strategies ()\n (format t \"Using a random strategy in ~4,2F\u00a0% of the cases the prisoners are free.~%\" (* (/ (sampling #'strategy-1) *samples*) 100))\n (format t \"Using an optimal strategy in ~4,2F\u00a0% of the cases the prisoners are free.~%\" (* (/ (sampling #'strategy-2) *samples*) 100)))\n", "safe": true }, { "filename": "100_prisoners_39.txt", "content": "CL-USER> (compare-strategies)\nUsing a random strategy in 0.00\u00a0% of the cases the prisoners are free.\nUsing an optimal strategy in 31.34\u00a0% of the cases the prisoners are free.", "safe": true }, { "filename": "100_prisoners_4.txt", "content": "Random strategie \u00a0: 0 sur 1000\nOptimal strategie\u00a0: 305 sur 1000\n", "safe": true }, { "filename": "100_prisoners_40.txt", "content": "include \"cowgol.coh\";\ninclude \"argv.coh\";\n\n# Parameters\nconst Drawers \u00a0:= 100; # Amount of drawers (and prisoners)\nconst Attempts \u00a0:= 50; # Amount of attempts a prisoner may make\nconst Simulations\u00a0:= 2000; # Amount of simulations to run\n\ntypedef NSim is int(0, Simulations);\n\n# Random number generator\nrecord RNG is\n x: uint8;\n a: uint8;\n b: uint8;\n c: uint8;\n state @at(0): int32;\nend record;\n\nsub RandomByte(r: [RNG]): (byte: uint8) is \n r.x\u00a0:= r.x + 1;\n r.a\u00a0:= r.a ^ r.c ^ r.x;\n r.b\u00a0:= r.b + r.a;\n r.c\u00a0:= r.c + (r.b >> 1) ^ r.a;\n byte\u00a0:= r.c;\nend sub;\n\nsub RandomUpTo(r: [RNG], limit: uint8): (rslt: uint8) is\n var x: uint8\u00a0:= 1;\n while x < limit loop\n x\u00a0:= x << 1;\n end loop;\n x\u00a0:= x - 1;\n \n loop\n rslt\u00a0:= RandomByte(r) & x;\n if rslt < limit then\n break;\n end if;\n end loop;\nend sub;\n\n# Drawers (though marked 0..99 instead of 1..100)\nvar drawers: uint8[Drawers];\ntypedef Drawer is @indexof drawers;\ntypedef Prisoner is Drawer;\n\n# Place cards randomly in drawers\nsub InitDrawers(r: [RNG]) is\n var x: Drawer\u00a0:= 0;\n while x < Drawers loop\n drawers[x]\u00a0:= x;\n x\u00a0:= x + 1;\n end loop;\n \n x\u00a0:= 0;\n while x < Drawers - 1 loop\n var y\u00a0:= x + RandomUpTo(r, Drawers-x);\n var t\u00a0:= drawers[x];\n drawers[x]\u00a0:= drawers[y];\n drawers[y]\u00a0:= t;\n x\u00a0:= x + 1;\n end loop;\nend sub;\n\n# A prisoner can apply a strategy and either succeed or not\ninterface Strategy(p: Prisoner, r: [RNG]): (success: uint8);\n\n# The stupid strategy: open drawers randomly.\nsub Stupid implements Strategy is\n # Let's assume the prisoner is smart enough not to reopen an open drawer\n var opened: Drawer[Drawers];\n MemZero(&opened[0], @bytesof opened);\n \n # Open random drawers\n success\u00a0:= 0;\n var triesLeft: uint8\u00a0:= Attempts;\n while triesLeft\u00a0!= 0 loop\n var d\u00a0:= RandomUpTo(r, Drawers); # grab a random drawer\n if opened[d]\u00a0!= 0 then\n continue; # Ignore it if a drawer was already open\n else\n triesLeft\u00a0:= triesLeft - 1;\n opened[d]\u00a0:= 1;\n if drawers[d] == p then # found it!\n success\u00a0:= 1;\n return;\n end if;\n end if;\n end loop;\nend sub;\n \n# The optimal strategy: open the drawer for each number\nsub Optimal implements Strategy is\n var current\u00a0:= p;\n var triesLeft: uint8\u00a0:= Attempts;\n success\u00a0:= 0;\n while triesLeft\u00a0!= 0 loop\n current\u00a0:= drawers[current];\n if current == p then\n success\u00a0:= 1;\n return;\n end if;\n triesLeft\u00a0:= triesLeft - 1;\n end loop;\nend sub;\n\n# Run a simulation\nsub Simulate(s: Strategy, r: [RNG]): (success: uint8) is\n InitDrawers(r); # place cards randomly in drawer\n var p: Prisoner\u00a0:= 0;\n success\u00a0:= 1; # if they all succeed the simulation succeeds\n while p < Drawers loop # but for each prisoner... \n if s(p, r) == 0 then # if he fails, the simulation fails\n success\u00a0:= 0;\n return;\n end if;\n p\u00a0:= p + 1;\n end loop;\nend sub;\n\n# Run an amount of simulations and report the amount of successes\nsub Run(n: NSim, s: Strategy, r: [RNG]): (successes: NSim) is\n successes\u00a0:= 0;\n while n > 0 loop\n successes\u00a0:= successes + Simulate(s, r) as NSim;\n n\u00a0:= n - 1;\n end loop;\nend sub;\n\n# Initialize RNG with number given on command line (defaults to 0)\nvar rng: RNG; rng.state\u00a0:= 0;\nArgvInit();\nvar arg\u00a0:= ArgvNext();\nif arg\u00a0!= 0 as [uint8] then\n (rng.state, arg)\u00a0:= AToI(arg);\nend if;\n\nsub RunAndPrint(name: [uint8], strat: Strategy) is\n print(name);\n print(\" strategy: \");\n var succ\u00a0:= Run(Simulations, strat, &rng) as uint32;\n print_i32(succ);\n print(\" out of \");\n print_i32(Simulations);\n print(\" - \");\n print_i32(succ * 100 / Simulations);\n print(\"%\\n\");\nend sub;\n\nRunAndPrint(\"Stupid\", Stupid);\nRunAndPrint(\"Optimal\", Optimal);", "safe": true }, { "filename": "100_prisoners_41.txt", "content": "Stupid strategy: 0 out of 2000 - 0%\nOptimal strategy: 634 out of 2000 - 31%", "safe": true }, { "filename": "100_prisoners_42.txt", "content": "prisoners = (1..100).to_a\nN = 100_000\ngenerate_rooms = ->{ (1..100).to_a.shuffle }\n\nres = N.times.count do\n rooms = generate_rooms.call\n prisoners.all? { |pr| rooms[1, 100].sample(50).includes?(pr) }\nend\nputs \"Random strategy\u00a0: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n\nres = N.times.count do\n rooms = generate_rooms.call\n prisoners.all? do |pr|\n cur_room = pr\n 50.times.any? do\n cur_room = rooms[cur_room - 1]\n found = (cur_room == pr)\n found\n end\n end\nend\nputs \"Optimal strategy: %11.4f\u00a0%%\" % (res.fdiv(N) * 100)\n", "safe": true }, { "filename": "100_prisoners_43.txt", "content": "Random strategy\u00a0: 0.0000\u00a0%\nOptimal strategy: 31.3190\u00a0%", "safe": true }, { "filename": "100_prisoners_44.txt", "content": "import std.array;\nimport std.random;\nimport std.range;\nimport std.stdio;\nimport std.traits;\n\nbool playOptimal() {\n auto secrets = iota(100).array.randomShuffle();\n\n prisoner:\n foreach (p; 0..100) {\n auto choice = p;\n foreach (_; 0..50) {\n if (secrets[choice] == p) continue prisoner;\n choice = secrets[choice];\n }\n return false;\n }\n\n return true;\n}\n\nbool playRandom() {\n auto secrets = iota(100).array.randomShuffle();\n\n prisoner:\n foreach (p; 0..100) {\n auto choices = iota(100).array.randomShuffle();\n foreach (i; 0..50) {\n if (choices[i] == p) continue prisoner;\n }\n return false;\n }\n\n return true;\n}\n\ndouble exec(const size_t n, bool function() play) {\n size_t success = 0;\n for (int i = n; i > 0; i--) {\n if (play()) {\n success++;\n }\n }\n return 100.0 * success / n;\n}\n\nvoid main() {\n enum N = 1_000_000;\n writeln(\"# of executions: \", N);\n writefln(\"Optimal play success rate: %11.8f%%\", exec(N, &playOptimal));\n writefln(\" Random play success rate: %11.8f%%\", exec(N, &playRandom));\n}\n", "safe": true }, { "filename": "100_prisoners_45.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.16100000%\n Random play success rate: 0.00000000%", "safe": true }, { "filename": "100_prisoners_46.txt", "content": "import 'dart:math';\n\nint playRandom(int n) {\n var rnd = Random();\n int pardoned = 0;\n List inDrawer = List.generate(100, (i) => i);\n List sampler = List.generate(100, (i) => i);\n for (int round = 0; round < n; round++) {\n inDrawer.shuffle();\n bool found = false;\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n found = false;\n sampler.shuffle(rnd);\n for (int i = 0; i < 50; i++) {\n int reveal = sampler[i];\n int card = inDrawer[reveal];\n if (card == prisoner) {\n found = true;\n break;\n }\n }\n if (!found) {\n break;\n }\n }\n if (found) {\n pardoned++;\n }\n }\n return (pardoned / n * 100).round();\n}\n\nint playOptimal(int n) {\n var rnd = Random();\n int pardoned = 0;\n bool found = false;\n List inDrawer = List.generate(100, (i) => i);\n for (int round = 0; round < n; round++) {\n inDrawer.shuffle(rnd);\n for (int prisoner = 0; prisoner < 100; prisoner++) {\n int reveal = prisoner;\n found = false;\n for (int go = 0; go < 50; go++) {\n int card = inDrawer[reveal];\n if (card == prisoner) {\n found = true;\n break;\n }\n reveal = card;\n }\n if (!found) {\n break;\n }\n }\n if (found) {\n pardoned++;\n }\n }\n return (pardoned / n * 100).round();\n}\n\nvoid main() {\n int n = 100000;\n print(\" Simulation count: $n\");\n print(\" Random play wins: ${playRandom(n).toStringAsFixed(2)}% of simulations\");\n print(\"Optimal play wins: ${playOptimal(n).toStringAsFixed(2)}% of simulations\");\n}\n", "safe": true }, { "filename": "100_prisoners_47.txt", "content": " Simulation count: 100000\n Random play wins: 0.00% of simulations\nOptimal play wins: 31.00% of simulations\n\n", "safe": true }, { "filename": "100_prisoners_48.txt", "content": "for i = 1 to 100\n drawer[] &= i\n sampler[] &= i\n.\nsubr shuffle_drawer\n for i = len drawer[] downto 2\n r = random i\n swap drawer[r] drawer[i]\n .\n.\nsubr play_random\n shuffle_drawer\n for prisoner = 1 to 100\n found = 0\n for i = 1 to 50\n r = random (100 - i)\n card = drawer[sampler[r]]\n swap sampler[r] sampler[100 - i - 1]\n if card = prisoner\n found = 1\n break 1\n .\n .\n if found = 0\n break 1\n .\n .\n.\nsubr play_optimal\n shuffle_drawer\n for prisoner = 1 to 100\n reveal = prisoner\n found = 0\n for i = 1 to 50\n card = drawer[reveal]\n if card = prisoner\n found = 1\n break 1\n .\n reveal = card\n .\n if found = 0\n break 1\n .\n .\n.\nn = 10000\nwin = 0\nfor _ = 1 to n\n play_random\n win += found\n.\nprint \"random: \" & 100.0 * win / n & \"%\"\n#\nwin = 0\nfor _ = 1 to n\n play_optimal\n win += found\n.\nprint \"optimal: \" & 100.0 * win / n & \"%\"\n", "safe": true }, { "filename": "100_prisoners_49.txt", "content": "random: 0.000%\noptimal: 30.800%\n", "safe": true }, { "filename": "100_prisoners_5.txt", "content": "HOW TO FILL drawers:\n PUT {} IN drawers\n FOR i IN {1..100}: PUT i IN drawers[i]\n FOR i IN {1..100}:\n PUT choice {i..100} IN j\n PUT drawers[i], drawers[j] IN drawers[j], drawers[i]\n\nHOW TO REPORT prisoner random.strat drawers:\n PUT {1..100} IN available\n FOR turn IN {1..50}:\n PUT choice available IN drawer\n IF drawers[drawer] = prisoner: SUCCEED\n REMOVE drawer FROM available\n FAIL\n\nHOW TO REPORT prisoner optimal.strat drawers:\n PUT prisoner IN drawer\n FOR turn IN {1..50}:\n IF drawers[drawer] = prisoner: SUCCEED\n PUT drawers[drawer] IN drawer\n FAIL\n\nHOW TO REPORT simulate strategy:\n FILL drawers\n FOR prisoner IN {1..100}:\n SELECT:\n strategy = \"Random\":\n IF NOT prisoner random.strat drawers: FAIL\n strategy = \"Optimal\":\n IF NOT prisoner optimal.strat drawers: FAIL\n SUCCEED\n\nHOW TO RETURN n.sim chance.of.success strategy:\n PUT 0 IN success\n FOR n IN {1..n.sim}:\n IF simulate strategy: PUT success+1 IN success\n RETURN success * 100 / n.sim\n\nFOR strategy IN {\"Random\"; \"Optimal\"}:\n WRITE strategy, \": \", 10000 chance.of.success strategy, '%'/", "safe": true }, { "filename": "100_prisoners_50.txt", "content": "module OneHundredPrisoners {\n @Inject Console console;\n\n void run() {\n console.print($\"# of executions: {attempts}\");\n console.print($\"Optimal play success rate: {simulate(tryOpt)}%\");\n console.print($\" Random play success rate: {simulate(tryRnd)}%\");\n }\n\n Int attempts = 10000;\n\n Dec simulate(function Boolean(Int[]) allFoundNumber) {\n Int[] drawers = new Int[100](i->i);\n Int pardoned = 0;\n for (Int i\u00a0: 1..attempts) {\n if (allFoundNumber(drawers.shuffled())) {\n ++pardoned;\n }\n }\n return (pardoned * 1000000 / attempts).toDec() / 10000;\n }\n\n Boolean tryRnd(Int[] drawers) {\n Inmates: for (Int inmate\u00a0: 0..<100) {\n Int[] choices = drawers.shuffled();\n for (Int attempt\u00a0: 0..<50) {\n if (drawers[choices[attempt]] == inmate) {\n continue Inmates;\n }\n }\n return False;\n }\n return True;\n }\n\n Boolean tryOpt(Int[] drawers) {\n Inmates: for (Int inmate\u00a0: 0..<100) {\n Int choice = inmate;\n for (Int attempt\u00a0: 0..<50) {\n if (drawers[choice] == inmate) {\n continue Inmates;\n }\n choice = drawers[choice];\n }\n return False;\n }\n return True;\n }\n}", "safe": true }, { "filename": "100_prisoners_51.txt", "content": "# of executions: 10000\nOptimal play success rate: 30.1%\n Random play success rate: 0%\n", "safe": true }, { "filename": "100_prisoners_52.txt", "content": "defmodule HundredPrisoners do\n def optimal_room(_, _, _, []), do: []\n def optimal_room(prisoner, current_room, rooms, [_ | tail]) do\n found = Enum.at(rooms, current_room - 1) == prisoner\n next_room = Enum.at(rooms, current_room - 1)\n [found] ++ optimal_room(prisoner, next_room, rooms, tail)\n end\n\n def optimal_search(prisoner, rooms) do\n Enum.any?(optimal_room(prisoner, prisoner, rooms, Enum.to_list(1..50)))\n end\nend\n\nprisoners = 1..100\nn = 1..10_000\ngenerate_rooms = fn -> Enum.shuffle(1..100) end\n\nrandom_strategy = Enum.count(n, \n fn _ -> \n rooms = generate_rooms.()\n Enum.all?(prisoners, fn pr -> pr in (rooms |> Enum.take_random(50)) end)\nend)\n\nIO.puts \"Random strategy: #{random_strategy} / #{n |> Range.size}\"\n\noptimal_strategy = Enum.count(n,\n fn _ ->\n rooms = generate_rooms.()\n Enum.all?(prisoners, \n fn pr -> HundredPrisoners.optimal_search(pr, rooms) end)\nend)\n\nIO.puts \"Optimal strategy: #{optimal_strategy} / #{n |> Range.size}\"\n", "safe": true }, { "filename": "100_prisoners_53.txt", "content": "Random strategy: 0 / 10000\nOptimal strategy: 3110 / 10000\n", "safe": true }, { "filename": "100_prisoners_54.txt", "content": "let rnd = System.Random()\nlet shuffled min max =\n [|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))\n\nlet drawers () = shuffled 1 100\n\n// strategy randomizing drawer opening\nlet badChoices (drawers' : int array) =\n Seq.init 100 (fun _ -> shuffled 1 100 |> Array.take 50) // selections for each prisoner\n |> Seq.map (fun indexes -> indexes |> Array.map(fun index -> drawers'.[index-1])) // transform to cards\n |> Seq.mapi (fun i cards -> cards |> Array.contains i) // check if any card matches prisoner number\n |> Seq.contains false // true means not all prisoners got their cards\nlet outcomeOfRandom runs =\n let pardons = Seq.init runs (fun _ -> badChoices (drawers ()))\n |> Seq.sumBy (fun badChoice -> if badChoice |> not then 1.0 else 0.0)\n pardons/ float runs\n \n// strategy optimizing drawer opening\nlet smartChoice max prisoner (drawers' : int array) =\n prisoner\n |> Seq.unfold (fun selection ->\n let card = drawers'.[selection-1]\n Some (card, card))\n |> Seq.take max\n |> Seq.contains prisoner\nlet smartChoices (drawers' : int array) =\n seq { 1..100 }\n |> Seq.map (fun prisoner -> smartChoice 50 prisoner drawers')\n |> Seq.filter (fun result -> result |> not) // remove all but false results\n |> Seq.isEmpty // empty means all prisoners got their cards\nlet outcomeOfOptimize runs =\n let pardons = Seq.init runs (fun _ -> smartChoices (drawers()))\n |> Seq.sumBy (fun smartChoice' -> if smartChoice' then 1.0 else 0.0)\n pardons/ float runs\n \nprintfn $\"Using Random Strategy: {(outcomeOfRandom 20000):p2}\"\nprintfn $\"Using Optimum Strategy: {(outcomeOfOptimize 20000):p2}\"\n", "safe": true }, { "filename": "100_prisoners_55.txt", "content": "Using Random Strategy: 0.00%\nUsing Optimum Strategy: 31.06%\n", "safe": true }, { "filename": "100_prisoners_56.txt", "content": "USING: arrays formatting fry io kernel math random sequences ;\n\n: setup ( -- seq seq ) 100 dup >array randomize ;\n\n: rand ( -- ? )\n setup [ 50 sample member? not ] curry find nip >boolean not ;\n\n: trail ( m seq -- n )\n 50 pick '[ [ nth ] keep over _ = ] replicate [ t = ] any?\n 2nip ;\n\n: optimal ( -- ? ) setup [ trail ] curry [ and ] map-reduce ;\n\n: simulate ( m quot -- x )\n dupd replicate [ t = ] count swap /f 100 * ; inline\n\n\"Simulation count: 10,000\" print\n10,000 [ rand ] simulate \"Random play success: \"\n10,000 [ optimal ] simulate \"Optimal play success: \"\n[ write \"%.2f%%\\n\" printf ] 2bi@\n", "safe": true }, { "filename": "100_prisoners_57.txt", "content": "Simulation count: 10,000\nRandom play success: 0.00%\nOptimal play success: 31.11%\n", "safe": true }, { "filename": "100_prisoners_58.txt", "content": "01.10 T %5.02,\" RANDOM\";S CU=0\n01.20 F Z=1,2000;D 5;S CU=CU+SU\n01.30 T CU/20,!,\"OPTIMAL\";S CU=0\n01.40 F Z=1,2000;D 6;S CU=CU+SU\n01.50 T CU/20,!\n01.60 Q\n\n02.01 C-- PUT CARDS IN RANDOM DRAWERS\n02.10 F X=1,100;S D(X)=X\n02.20 F X=1,99;D 2.3;S B=D(X);S D(X)=D(A);S D(A)=B\n02.30 D 2.4;S A=X+FITR(A*(101-X))\n02.40 S A=FABS(FRAN()*10);S A=A-FITR(A)\n\n03.01 C-- PRISONER X TRIES UP TO 50 RANDOM DRAWERS\n03.10 S TR=50;S SU=0\n03.20 D 2.4;I (X-D(A))3.3,3.4,3.3\n03.30 S TR=TR-1;I (TR),3.5,3.2\n03.40 S SU=1;R\n03.50 S SU=0\n\n04.01 C-- PRISONER X TRIES OPTIMAL METHOD\n04.10 S TR=50;S SU=0;S A=X\n04.20 I (X-D(A))4.3,4.4,4.3\n04.30 S TR=TR-1;S A=D(A);I (TR),4.5,4.2\n04.40 S SU=1;R\n04.50 S SU=0\n\n05.01 C-- PRISONERS TRY RANDOM METHOD UNTIL ONE FAILS\n05.10 D 2;S X=1\n05.20 I (X-101)5.3,5.4\n05.30 D 3;S X=X+1;I (SU),5.4,5.2\n05.40 R\n\n06.01 C-- PRISONERS TRY OPTIMAL METHOD UNTIL ONE FAILS\n06.10 D 2;S X=1\n06.20 I (X-101)6.3,6.4\n06.30 D 4;S X=X+1;I (SU),6.4,6.2\n06.40 R", "safe": true }, { "filename": "100_prisoners_59.txt", "content": " RANDOM= 0.00\nOPTIMAL= 30.10", "safe": true }, { "filename": "100_prisoners_6.txt", "content": "Optimal: 32.01\u00a0%\nRandom: 0\u00a0%", "safe": true }, { "filename": "100_prisoners_60.txt", "content": "INCLUDE ran4.seq\n\n100 CONSTANT #drawers\n#drawers CONSTANT #players\n100000 CONSTANT #tries\n\nCREATE drawers #drawers CELLS ALLOT \\ index 0..#drawers-1\n\n: drawer[] ( n -- addr ) \\ return address of drawer n\n CELLS drawers +\n;\n\n: random_drawer ( -- n ) \\ n=0..#drawers-1 random drawer \n RAN4 ( d ) XOR ( n ) #drawers MOD\n;\n\n: random_drawer[] ( -- addr ) \\ return address of random drawer\n random_drawer drawer[]\n;\n\n: swap_indirect ( addr1 addr2 -- ) \\ swaps the values at the two addresses\n 2DUP @ SWAP @ ( addr1 addr2 n2 n1 )\n ROT ! SWAP ! \\ store n1 at addr2 and n2 at addr1\n;\n\n: init_drawers ( -- ) \\ shuffle cards into drawers\n #drawers 0 DO\n I I drawer[] ! \\ store cards in order\n LOOP\n #drawers 0 DO\n I drawer[] random_drawer[] ( addr-drawer-i addr-drawer-rnd )\n swap_indirect\n LOOP\n;\n\n: random_turn ( player - f )\n #drawers 2 / 0 DO\n\t\trandom_drawer \n\t\tdrawer[] @ \n\t\tOVER = IF\n\t\t\tDROP TRUE UNLOOP EXIT\t\\ found his number\n\t\tTHEN\n\tLOOP \n\tDROP FALSE\n;\n\n0 VALUE player\n\n: cycle_turn ( player - f )\n\tDUP TO player\t\t\t( next-drawer )\n #drawers 2 / 0 DO\n\t\tdrawer[] @\n\t\tDUP player = IF \n\t\t\tDROP TRUE UNLOOP EXIT\t\\ found his number\n\t\tTHEN\n\tLOOP \n\tDROP FALSE\n;\n\n: turn ( strategy player - f )\n SWAP 0= IF \\ random play \n random_turn\n ELSE\n cycle_turn\n THEN\n;\n\n: play ( strategy -- f ) \\ return true if prisioners survived\n init_drawers\n #players 0 DO\n DUP I turn\n 0= IF\n DROP FALSE UNLOOP EXIT \t\\ this player did not survive, UNLOOP, return false\n THEN\n LOOP \n DROP TRUE \\ all survived, return true\n;\n\n: trie\t\t\t\t\t( strategy - nr-saved )\n\t0\t\t\t\t( strategy nr-saved )\n\t#tries 0 DO\n\t\tOVER play IF 1+ THEN\n\tLOOP\n\tNIP\n;\n\n0 trie . CR\t\\ random strategy\n1 trie . CR\t\\ follow the card number strategy\n", "safe": true }, { "filename": "100_prisoners_61.txt", "content": "0 \n30009 \n", "safe": true }, { "filename": "100_prisoners_62.txt", "content": "SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)\n ! Takes an input array and shuffles the elements by swapping them\n ! in pairs in turn 10 times\n IMPLICIT NONE\n\n INTEGER, DIMENSION(100), INTENT(INOUT) :: INT_ARRAY\n INTEGER, PARAMETER :: N_PASSES = 10\n ! Local Variables\n\n INTEGER :: TEMP_1, TEMP_2 ! Temporaries for swapping elements\n INTEGER :: I, J, PASS ! Indices variables\n REAL :: R ! Randomly generator value\n\n CALL RANDOM_SEED() ! Seed the random number generator\n\n DO PASS=1, N_PASSES\n DO I=1, SIZE(INT_ARRAY)\n\n ! Get a random index to swap with\n CALL RANDOM_NUMBER(R)\n J = CEILING(R*SIZE(INT_ARRAY))\n\n ! In case generated index value\n ! exceeds array size\n DO WHILE (J > SIZE(INT_ARRAY))\n J = CEILING(R*SIZE(INT_ARRAY))\n END DO\n\n ! Swap the two elements\n TEMP_1 = INT_ARRAY(I)\n TEMP_2 = INT_ARRAY(J)\n INT_ARRAY(I) = TEMP_2\n INT_ARRAY(J) = TEMP_1\n ENDDO\n ENDDO\nEND SUBROUTINE SHUFFLE_ARRAY\n\nSUBROUTINE RUN_RANDOM(N_ROUNDS)\n ! Run the 100 prisoner puzzle simulation N_ROUNDS times\n ! in the scenario where each prisoner selects a drawer at random\n IMPLICIT NONE\n\n INTEGER, INTENT(IN) :: N_ROUNDS ! Number of simulations to run in total\n\n INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables\n INTEGER :: N_SUCCESSES ! Number of successful trials\n REAL(8) :: TOTAL ! Total number of trials as real\n LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number\n\n INTEGER, DIMENSION(100) :: CARDS, CHOICES ! Arrays representing card allocations\n ! to draws and drawer choice order\n\n ! Both cards and choices are randomly assigned.\n ! This being the drawer (allocation represented by index),\n ! and what drawer to pick for Nth/50 choice\n ! (take first 50 elements of 100 element array)\n CARDS = (/(I, I=1, 100, 1)/)\n CHOICES = (/(I, I=1, 100, 1)/)\n\n N_SUCCESSES = 0\n TOTAL = REAL(N_ROUNDS)\n\n ! Run the simulation for N_ROUNDS rounds\n ! when a prisoner fails to find their number\n ! after 50 trials, set that simulation to fail\n ! and start the next round\n ROUNDS_LOOP: DO ROUND=1, N_ROUNDS\n CALL SHUFFLE_ARRAY(CARDS)\n PRISONERS_LOOP: DO PRISONER=1, 100\n NUM_FOUND = .FALSE.\n CALL SHUFFLE_ARRAY(CHOICES)\n CHOICE_LOOP: DO CHOICE=1, 50\n IF(CARDS(CHOICE) == PRISONER) THEN\n NUM_FOUND = .TRUE.\n EXIT CHOICE_LOOP\n ENDIF\n ENDDO CHOICE_LOOP\n IF(.NOT. NUM_FOUND) THEN\n EXIT PRISONERS_LOOP\n ENDIF\n ENDDO PRISONERS_LOOP\n IF(NUM_FOUND) THEN\n N_SUCCESSES = N_SUCCESSES + 1\n ENDIF\n ENDDO ROUNDS_LOOP\n\n WRITE(*, '(A, F0.3, A)') \"Random drawer selection method success rate: \", &\n 100*N_SUCCESSES/TOTAL, \"%\"\n\nEND SUBROUTINE RUN_RANDOM\n\nSUBROUTINE RUN_OPTIMAL(N_ROUNDS)\n ! Run the 100 prisoner puzzle simulation N_ROUNDS times in the scenario\n ! where each prisoner selects firstly the drawer with their number and then\n ! subsequently the drawer matching the number of the card present \n ! within that current drawer\n IMPLICIT NONE\n\n INTEGER, INTENT(IN) :: N_ROUNDS\n\n INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables\n INTEGER :: CURRENT_DRAW ! ID of the current draw\n INTEGER :: N_SUCCESSES ! Number of successful trials\n REAL(8) :: TOTAL ! Total number of trials as real\n LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number \n INTEGER, DIMENSION(100) :: CARDS ! Array representing card allocations\n\n ! Cards are randomly assigned to a drawer \n ! (allocation represented by index),\n CARDS = (/(I, I=1, 100, 1)/)\n\n N_SUCCESSES = 0\n TOTAL = REAL(N_ROUNDS)\n\n ! Run the simulation for N_ROUNDS rounds\n ! when a prisoner fails to find their number\n ! after 50 trials, set that simulation to fail\n ! and start the next round\n ROUNDS_LOOP: DO ROUND=1, N_ROUNDS\n CARDS = (/(I, I=1, 100, 1)/)\n CALL SHUFFLE_ARRAY(CARDS)\n PRISONERS_LOOP: DO PRISONER=1, 100\n CURRENT_DRAW = PRISONER\n NUM_FOUND = .FALSE.\n CHOICE_LOOP: DO CHOICE=1, 50\n IF(CARDS(CURRENT_DRAW) == PRISONER) THEN\n NUM_FOUND = .TRUE.\n EXIT CHOICE_LOOP\n ELSE\n CURRENT_DRAW = CARDS(CURRENT_DRAW)\n ENDIF\n ENDDO CHOICE_LOOP\n IF(.NOT. NUM_FOUND) THEN\n EXIT PRISONERS_LOOP\n ENDIF\n ENDDO PRISONERS_LOOP\n IF(NUM_FOUND) THEN\n N_SUCCESSES = N_SUCCESSES + 1\n ENDIF\n ENDDO ROUNDS_LOOP\n WRITE(*, '(A, F0.3, A)') \"Optimal drawer selection method success rate: \", &\n 100*N_SUCCESSES/TOTAL, \"%\"\n\nEND SUBROUTINE RUN_OPTIMAL\n\nPROGRAM HUNDRED_PRISONERS\n ! Run the two scenarios for the 100 prisoners puzzle of random choice\n ! and optimal choice (choice based on drawer contents)\n IMPLICIT NONE\n INTEGER, PARAMETER :: N_ROUNDS = 50000\n WRITE(*,'(A, I0, A)') \"Running simulation for \", N_ROUNDS, \" trials...\"\n CALL RUN_RANDOM(N_ROUNDS)\n CALL RUN_OPTIMAL(N_ROUNDS)\nEND PROGRAM HUNDRED_PRISONERS\n", "safe": true }, { "filename": "100_prisoners_63.txt", "content": "Running simulation for 50000 trials...\nRandom drawer selection method success rate: .000%\nOptimal drawer selection method success rate: 31.360%\n", "safe": true }, { "filename": "100_prisoners_64.txt", "content": "#include once \"knuthshuf.bas\" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC\n\nfunction gus( i as long, strat as boolean ) as long\n if strat then return i\n return 1+int(rnd*100)\nend function\n\nsub trials( byref c_success as long, byref c_fail as long, byval strat as boolean )\n dim as long i, j, k, guess, drawer(1 to 100)\n for i = 1 to 100\n drawer(i) = i\n next i\n for j = 1 to 1000000 'one million trials of prisoners\n knuth_up( drawer() ) 'shuffles the cards in the drawers\n for i = 1 to 100 'prisoner number\n guess = gus(i, strat)\n for k = 1 to 50 'each prisoner gets 50 tries\n if drawer(guess) = i then goto next_prisoner\n guess = gus(drawer(guess), strat)\n next k\n c_fail += 1\n goto next_trial\n next_prisoner:\n next i\n c_success += 1\n next_trial:\n next j\nend sub\n\nrandomize timer\ndim as long c_fail=0, c_success=0\n\ntrials( c_success, c_fail, false )\n\nprint using \"For prisoners guessing randomly we had ####### successes and ####### failures.\";c_success;c_fail\n\nc_success = 0\nc_fail = 0\n\ntrials( c_success, c_fail, true )\n\nprint using \"For prisoners using the strategy we had ####### successes and ####### failures.\";c_success;c_fail\n", "safe": true }, { "filename": "100_prisoners_65.txt", "content": "include \"Tlbx GameplayKit.incl\"\n\n_prisoners = 100\n_instances = 10000\n\nlocal fn DrawersArray as CFArrayRef\n long index\n CFMutableArrayRef temp = fn MutableArrayWithCapacity(100)\n for index = 0 to 99\n MutableArrayAddObject( temp, @(index) )\n next\nend fn = fn ArrayShuffledArray( temp )\n\n\nlocal fn RandomResult( drawers as CFArrayRef ) as BOOL\n long prisoner, i, drawer, total = 0\n MutableIndexSetRef set\n \n for prisoner = 0 to _prisoners - 1\n set = fn MutableIndexSetInit\n for i = 1 to _prisoners/2\n drawer = rnd(_prisoners)-1\n while ( fn IndexSetContainsIndex( set, intVal( drawers[drawer] ) ) )\n drawer = rnd(_prisoners)-1\n wend\n MutableIndexSetAddIndex( set, intVal( drawers[drawer] ) )\n if ( fn IndexSetContainsIndex( set, prisoner ) )\n total++\n break\n end if\n next\n next\nend fn = ( total == _prisoners )\n\n\nlocal fn OptimalResult( drawers as CFArrayRef ) as BOOL\n long prisoner, drawer, i, card, total = 0\n \n for prisoner = 0 to _prisoners - 1\n drawer = prisoner\n for i = 1 to _prisoners/2\n card = intVal( drawers[drawer] )\n if ( card == prisoner )\n total++\n break\n end if\n drawer = card\n next\n next\nend fn = ( total == _prisoners )\n\n\nvoid local fn DoIt\n static double sTime = 0.0\n \n block TimerRef timer = timerbegin , 0.001, YES\n sTime += 0.001\n cls\n printf @\"Compute time:\u00a0%.3f\\n\",sTime\n timerend\n \n dispatchglobal\n long instance, randomTotal = 0, optimalTotal = 0\n CFArrayRef drawers\n \n for instance = 1 to _instances\n drawers = fn DrawersArray\n if ( fn RandomResult( drawers ) ) then randomTotal++\n if ( fn OptimalResult( drawers ) ) then optimalTotal++\n next\n \n dispatchmain\n TimerInvalidate( timer )\n \n cls\n print @\"Prisoners: \"_prisoners\n print @\"Instances: \"_instances\n printf @\"Random - fail: %ld, success: %ld (%.2f%%)\",_instances-randomTotal,randomTotal,(double)randomTotal/(double)_instances*100.0\n printf @\"Optimal - fail: %ld, success: %ld (%.2f%%)\\n\",_instances-optimalTotal,optimalTotal,(double)optimalTotal/(double)_instances*100.0\n \n printf @\"Compute time:\u00a0%.3f\\n\",sTime\n dispatchend\n \n dispatchend\nend fn\n\nrandom\n\nwindow 1, @\"100 Prisoners\"\n\nfn DoIt\n\nHandleEvents", "safe": true }, { "filename": "100_prisoners_66.txt", "content": "Prisoners: 100\nInstances: 10000\nRandom - fail: 10000, success: 0 (0.00%)\nOptimal - fail: 6896, success: 3104 (31.04%)\n\nCompute time: 7.856\n", "safe": true }, { "filename": "100_prisoners_67.txt", "content": "' Gambas module file\n\nPublic DrawerArray As Long[]\nPublic NumberFromDrawer As Long\nPublic FoundOwnNumber As Long\n\nPublic Sub Main()\n \n Dim NumberOfPrisoners As Long\n Dim Selections As Long\n Dim Tries As Long\n \n Print \"Number of prisoners (default, 100)?\"\n Try Input NumberOfPrisoners\n If Error Then NumberOfPrisoners = 100\n \n Print \"Number of selections (default, half of prisoners)?\" \n Try Input Selections\n If Error Then Selections = NumberOfPrisoners / 2\n \n Print \"Number of tries (default, 1000)?\"\n Try Input Tries\n If Error Then Tries = 1000\n \n Dim AllFoundOptimal As Long = 0\n Dim AllFoundRandom As Long = 0\n Dim AllFoundRandomMem As Long = 0\n \n Dim i As Long\n Dim OptimalCount As Long\n Dim RandomCount As Long\n Dim RandomMenCount As Long\n \n Dim fStart As Float = Timer\n \n For i = 1 To Tries\n OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections)\n RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections)\n RandomMenCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)\n \n If OptimalCount = NumberOfPrisoners Then AllFoundOptimal += 1\n If RandomCount = NumberOfPrisoners Then AllFoundRandom += 1\n If RandomMenCount = NumberOfPrisoners Then AllFoundRandomMem += 1\n Next\n \n Dim fTime As Float = Timer - fStart\n fTime = Round(ftime, -1)\n \n Print\n Print \"Result with \" & NumberOfPrisoners & \" prisoners, \" & Selections & \" selections and \" & Tries & \" tries. \"\n Print\n Print \"Optimal: \" & AllFoundOptimal & \" of \" & Tries & \": \" & Str(AllFoundOptimal / Tries * 100) & \"\u00a0%\"\n Print \"Random: \" & AllFoundRandom & \" of \" & Tries & \": \" & Str(AllFoundRandom / Tries * 100) & \"\u00a0%\"\n Print \"RandomMem: \" & AllFoundRandomMem & \" of \" & Tries & \": \" & Str(AllFoundRandomMem / Tries * 100) & \"\u00a0%\"\n Print\n Print \"Elapsed Time: \" & fTime & \" sec\"\n Print\n Print \"Trials/sec: \" & Round(Tries / fTime, -1)\n \nEnd\n\nFunction HundredPrisoners_Optimal(NrPrisoners As Long, NrSelections As Long) As Long\n \n DrawerArray = New Long[NrPrisoners]\n Dim Counter As Long\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n If j = 1 Then NumberFromDrawer = DrawerArray[i - 1]\n \n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n\nFunction HundredPrisoners_Random(NrPrisoners As Long, NrSelections As Long) As Long\n \n Dim RandomDrawer As Long\n Dim Counter As Long\n \n DrawerArray = New Long[NrPrisoners]\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n Randomize\n \n For i = 1 To NrPrisoners\n For j = 1 To NrSelections\n RandomDrawer = CLong(Rand(NrPrisoners - 1))\n NumberFromDrawer = DrawerArray[RandomDrawer]\n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n\nFunction HundredPrisoners_Random_Mem(NrPrisoners As Long, NrSelections As Long) As Long\n \n Dim SelectionArray As New Long[NrPrisoners]\n Dim Counter As Long\n \n DrawerArray = New Long[NrPrisoners]\n \n For Counter = 0 To DrawerArray.Max\n DrawerArray[Counter] = Counter + 1\n \n Next\n \n For Counter = 0 To SelectionArray.Max\n SelectionArray[Counter] = Counter + 1\n \n Next\n \n DrawerArray.Shuffle()\n \n Dim i As Long\n Dim j As Long\n FoundOwnNumber = 0\n \n For i = 1 To NrPrisoners\n SelectionArray.Shuffle()\n For j = 1 To NrSelections\n NumberFromDrawer = DrawerArray[SelectionArray[j - 1] - 1]\n If NumberFromDrawer = i Then\n FoundOwnNumber += 1\n Break\n Endif\n NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]\n Next\n Next\n Return FoundOwnNumber\n \nEnd\n", "safe": true }, { "filename": "100_prisoners_68.txt", "content": "Number of prisoners (default, 100)?\n100\nNumber of selections (default, half of prisoners)?\n50\nNumber of tries (default, 1000)?\n\n\nResult with 100 prisoners, 50 selections and 1000 tries. \n\nOptimal: 311 of 1000: 31,1\u00a0%\nRandom: 0 of 1000: 0\u00a0%\nRandomMem: 0 of 1000: 0\u00a0%\n\nElapsed Time: 8.7 sec\n\nTrials/sec: 114.9", "safe": true }, { "filename": "100_prisoners_69.txt", "content": "extends MainLoop\n\n\nenum Strategy {Random, Optimal}\n\nconst prisoner_count := 100\n\n\nfunc get_random_drawers() -> Array[int]:\n\tvar drawers: Array[int] = []\n\tdrawers.resize(prisoner_count)\n\tfor i in range(0, prisoner_count):\n\t\tdrawers[i] = i + 1\n\tdrawers.shuffle()\n\treturn drawers\n\n\nvar random_strategy = func(drawers: Array[int], prisoner: int) -> bool:\n\t# Randomly selecting 50 drawers is equivalent to shuffling and picking the first 50\n\tvar drawerCopy: Array[int] = drawers.duplicate()\n\tdrawerCopy.shuffle()\n\tfor i in range(50):\n\t\tif drawers[drawerCopy[i]-1] == prisoner:\n\t\t\treturn true\n\treturn false\n\n\nvar optimal_strategy = func(drawers: Array[int], prisoner: int) -> bool:\n\tvar choice: int = prisoner\n\tfor _i in range(50):\n\t\tvar drawer_value: int = drawers[choice-1]\n\t\tif drawer_value == prisoner:\n\t\t\treturn true\n\t\tchoice = drawer_value\n\treturn false\n\n\nfunc play_all(drawers: Array[int], strategy: Callable) -> bool:\n\tfor prisoner in range(1, prisoner_count+1):\n\t\tif not strategy.call(drawers, prisoner):\n\t\t\treturn false\n\treturn true\n\n\nfunc _process(_delta: float) -> bool:\n\t# Constant seed for reproducibility, call randomize() in real use\n\tseed(1234)\n\n\tconst SAMPLE_SIZE: int = 10_000\n\n\tvar random_successes: int = 0\n\tfor i in range(SAMPLE_SIZE):\n\t\tif play_all(get_random_drawers(), random_strategy):\n\t\t\trandom_successes += 1\n\n\tvar optimal_successes: int = 0\n\tfor i in range(SAMPLE_SIZE):\n\t\tif play_all(get_random_drawers(), optimal_strategy):\n\t\t\toptimal_successes += 1\n\n\tprint(\"Random play: %%%f\" % (100.0 * random_successes/SAMPLE_SIZE))\n\tprint(\"Optimal play: %%%f\" % (100.0 * optimal_successes/SAMPLE_SIZE))\n\n\treturn true # Exit\n", "safe": true }, { "filename": "100_prisoners_7.txt", "content": "package Prisoners is\n\n type Win_Percentage is digits 2 range 0.0 .. 100.0;\n type Drawers is array (1 .. 100) of Positive;\n\n function Play_Game\n (Repetitions : in Positive;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Win_Percentage;\n -- Play the game with a specified number of repetitions, the chosen strategy\n -- is passed to this function\n\n function Optimal_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean;\n\n function Random_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean;\n\nend Prisoners;\n", "safe": true }, { "filename": "100_prisoners_70.txt", "content": "Random play: %0.000000\nOptimal play: %31.700000\n", "safe": true }, { "filename": "100_prisoners_71.txt", "content": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// Uses 0-based numbering rather than 1-based numbering throughout.\nfunc doTrials(trials, np int, strategy string) {\n pardoned := 0\ntrial:\n for t := 0; t < trials; t++ {\n var drawers [100]int\n for i := 0; i < 100; i++ {\n drawers[i] = i\n }\n rand.Shuffle(100, func(i, j int) {\n drawers[i], drawers[j] = drawers[j], drawers[i]\n })\n prisoner:\n for p := 0; p < np; p++ {\n if strategy == \"optimal\" {\n prev := p\n for d := 0; d < 50; d++ {\n this := drawers[prev]\n if this == p {\n continue prisoner\n }\n prev = this\n }\n } else {\n // Assumes a prisoner remembers previous drawers (s)he opened\n // and chooses at random from the others.\n var opened [100]bool\n for d := 0; d < 50; d++ {\n var n int\n for {\n n = rand.Intn(100)\n if !opened[n] {\n opened[n] = true\n break\n }\n }\n if drawers[n] == p {\n continue prisoner\n }\n }\n }\n continue trial\n }\n pardoned++\n }\n rf := float64(pardoned) / float64(trials) * 100\n fmt.Printf(\" strategy =\u00a0%-7s pardoned =\u00a0%-6d relative frequency = %5.2f%%\\n\\n\", strategy, pardoned, rf)\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n const trials = 100000\n for _, np := range []int{10, 100} {\n fmt.Printf(\"Results from %d trials with %d prisoners:\\n\\n\", trials, np)\n for _, strategy := range [2]string{\"random\", \"optimal\"} {\n doTrials(trials, np, strategy)\n }\n }\n}\n", "safe": true }, { "filename": "100_prisoners_72.txt", "content": "Results from 100000 trials with 10 prisoners:\n\n strategy = random pardoned = 99 relative frequency = 0.10%\n\n strategy = optimal pardoned = 31205 relative frequency = 31.20%\n\nResults from 100000 trials with 100 prisoners:\n\n strategy = random pardoned = 0 relative frequency = 0.00%\n\n strategy = optimal pardoned = 31154 relative frequency = 31.15%\n", "safe": true }, { "filename": "100_prisoners_73.txt", "content": "import java.util.function.Function\nimport java.util.stream.Collectors\nimport java.util.stream.IntStream\n\nclass Prisoners {\n private static boolean playOptimal(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(secretList)\n\n prisoner:\n for (int i = 0; i < secretList.size(); ++i) {\n int prev = i\n for (int j = 0; j < secretList.size() / 2; ++j) {\n if (secretList.get(prev) == i) {\n continue prisoner\n }\n prev = secretList.get(prev)\n }\n return false\n }\n return true\n }\n\n private static boolean playRandom(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(secretList)\n\n prisoner:\n for (Integer i\u00a0: secretList) {\n List trialList = IntStream.range(0, n).boxed().collect(Collectors.toList())\n Collections.shuffle(trialList)\n\n for (int j = 0; j < trialList.size() / 2; ++j) {\n if (Objects.equals(trialList.get(j), i)) {\n continue prisoner\n }\n }\n\n return false\n }\n return true\n }\n\n private static double exec(int n, int p, Function play) {\n int succ = 0\n for (int i = 0; i < n; ++i) {\n if (play.apply(p)) {\n succ++\n }\n }\n return (succ * 100.0) / n\n }\n\n static void main(String[] args) {\n final int n = 100_000\n final int p = 100\n System.out.printf(\"# of executions: %d\\n\", n)\n System.out.printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, Prisoners.&playOptimal))\n System.out.printf(\"Random play success rate: %f%%\\n\", exec(n, p, Prisoners.&playRandom))\n }\n}\n", "safe": true }, { "filename": "100_prisoners_74.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.215000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100_prisoners_75.txt", "content": "import System.Random\nimport Control.Monad.State\n\nnumRuns = 10000\nnumPrisoners = 100\nnumDrawerTries = 50\ntype Drawers = [Int]\ntype Prisoner = Int\ntype Prisoners = [Int]\n\nmain = do\n gen <- getStdGen\n putStrLn $ \"Chance of winning when choosing randomly: \" ++ (show $ evalState runRandomly gen)\n putStrLn $ \"Chance of winning when choosing optimally: \" ++ (show $ evalState runOptimally gen)\n\n\nrunRandomly :: State StdGen Double\nrunRandomly =\n let runResults = replicateM numRuns $ do\n drawers <- state $ shuffle [1..numPrisoners]\n allM (\\prisoner -> openDrawersRandomly drawers prisoner numDrawerTries) [1..numPrisoners]\n in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults\n\nopenDrawersRandomly :: Drawers -> Prisoner -> Int -> State StdGen Bool\nopenDrawersRandomly drawers prisoner triesLeft = go triesLeft []\n where go 0 _ = return False\n go triesLeft seenDrawers = do\n try <- state $ randomR (1, numPrisoners)\n case try of\n x | x == prisoner -> return True\n | x `elem` seenDrawers -> go triesLeft seenDrawers\n | otherwise -> go (triesLeft - 1) (x:seenDrawers)\n\nrunOptimally :: State StdGen Double\nrunOptimally =\n let runResults = replicateM numRuns $ do\n drawers <- state $ shuffle [1..numPrisoners]\n return $ all (\\prisoner -> openDrawersOptimally drawers prisoner numDrawerTries) [1..numPrisoners]\n in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults\n\nopenDrawersOptimally :: Drawers -> Prisoner -> Int -> Bool\nopenDrawersOptimally drawers prisoner triesLeft = go triesLeft prisoner\n where go 0 _ = False\n go triesLeft drawerToTry =\n let thisDrawer = drawers !! (drawerToTry - 1)\n in if thisDrawer == prisoner then True else go (triesLeft - 1) thisDrawer\n\n\n-- Haskel stdlib is lacking big time, so here some necessary 'library' functions\n\n-- make a list of 'len' random values in range 'range' from 'gen'\nrandomLR :: Integral a => Random b => a -> (b, b) -> StdGen -> ([b], StdGen)\nrandomLR 0 range gen = ([], gen)\nrandomLR len range gen =\n let (x, newGen) = randomR range gen\n (xs, lastGen) = randomLR (len - 1) range newGen\n in (x : xs, lastGen)\n\n\n-- shuffle a list by a generator\nshuffle :: [a] -> StdGen -> ([a], StdGen)\nshuffle list gen = (shuffleByNumbers numbers list, finalGen)\n where\n n = length list\n (numbers, finalGen) = randomLR n (0, n-1) gen\n shuffleByNumbers :: [Int] -> [a] -> [a]\n shuffleByNumbers [] _ = []\n shuffleByNumbers _ [] = []\n shuffleByNumbers (i:is) xs = let (start, x:rest) = splitAt (i `mod` length xs) xs\n in x : shuffleByNumbers is (start ++ rest)\n\n-- short-circuit monadic all\nallM :: Monad m => (a -> m Bool) -> [a] -> m Bool\nallM func [] = return True\nallM func (x:xs) = func x >>= \\res -> if res then allM func xs else return False\n", "safe": true }, { "filename": "100_prisoners_76.txt", "content": "Chance of winning when choosing randomly: 0.0\nChance of winning when choosing optimally: 0.3188", "safe": true }, { "filename": "100_prisoners_77.txt", "content": "NB. game is solvable by optimal strategy when the length (#) of the\nNB. longest (>./) cycle (C.) is at most 50.\nopt=: 50 >: [: >./ [: > [: #&.> C.\n\nNB. for each prisoner randomly open 50 boxes ((50?100){y) and see if \nNB. the right card is there (p&e.). if not return 0.\nrand=: monad define\nfor_p. i.100 do. if. -.p e.(50?100){y do. 0 return. end.\nend. 1\n)\n\nNB. use both strategies on the same shuffles y times.\nsimulate=: monad define\n'o r'=. y %~ 100 * +/ ((rand,opt)@?~)\"0 y # 100\n('strategy';'win rate'),('random';(\":o),'%'),:'optimal';(\":r),'%'\n)\n", "safe": true }, { "filename": "100_prisoners_78.txt", "content": " simulate 10000000\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502strategy\u2502win rate\u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502random \u25020% \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502optimal \u250231.1816%\u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n", "safe": true }, { "filename": "100_prisoners_79.txt", "content": "(math/seedrandom (os/cryptorand 8))\n\n(defn drawers\n \"create list and shuffle it\"\n [prisoners]\n (var x (seq [i :range [0 prisoners]] i))\n (loop [i :down [(- prisoners 1) 0]]\n (var j (math/floor (* (math/random) (+ i 1))))\n (var k (get x i))\n (put x i (get x j))\n (put x j k))\n x)\n\n(defn optimal-play\n \"optimal decision path\"\n [prisoners drawers]\n (var result 0)\n (loop [i :range [0 prisoners]]\n (var choice i)\n (loop [j :range [0 50] :until (= (get drawers choice) i)]\n (set choice (get drawers choice)))\n (cond\n (= (get drawers choice) i) (++ result)\n (break)))\n result)\n\n(defn random-play\n \"random decision path\"\n [prisoners d]\n (var result 0)\n (var options (drawers prisoners))\n (loop [i :range [0 prisoners]]\n (var choice 0)\n (loop [j :range [0 (/ prisoners 2)] :until (= (get d j) (get options i))]\n (set choice j))\n (cond\n (= (get d choice) (get options i)) (++ result)\n (break)))\n result)\n\n(defn main [& args]\n (def prisoners 100)\n (var optimal-success 0)\n (var random-success 0)\n (var sims 10000)\n (for i 0 sims\n (var d (drawers prisoners))\n (if (= (optimal-play prisoners d) prisoners)\n (++ optimal-success))\n (if (= (random-play prisoners d) prisoners)\n (++ random-success)))\n (printf \"Simulation count: %d\" sims)\n (printf \"Optimal play wins:\u00a0%.1f%%\" (* (/ optimal-success sims) 100))\n (printf \"Random play wins: \u00a0%.1f%%\" (* (/ random-success sims) 100)))", "safe": true }, { "filename": "100_prisoners_8.txt", "content": "pragma Ada_2012;\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO; use Ada.Text_IO;\n\npackage body Prisoners is\n\n subtype Drawer_Range is Positive range 1 .. 100;\n package Random_Drawer is new Ada.Numerics.Discrete_Random (Drawer_Range);\n use Random_Drawer;\n \n -- Helper procedures to initialise and shuffle the drawers\n \n procedure Swap (A, B : Positive; Cupboard : in out Drawers) is\n Temp : Positive;\n begin\n Temp := Cupboard (B);\n Cupboard (B) := Cupboard (A);\n Cupboard (A) := Temp;\n end Swap;\n\n procedure Shuffle (Cupboard : in out Drawers) is\n G : Generator;\n begin\n Reset (G);\n for I in Cupboard'Range loop\n Swap (I, Random (G), Cupboard);\n end loop;\n end Shuffle;\n\n procedure Initialise_Drawers (Cupboard : in out Drawers) is\n begin\n for I in Cupboard'Range loop\n Cupboard (I) := I;\n end loop;\n Shuffle (Cupboard);\n end Initialise_Drawers;\n \n -- The two strategies for playing the game\n\n function Optimal_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean\n is\n Current_Card : Positive;\n begin\n Current_Card := Cupboard (Prisoner_Number);\n if Current_Card = Prisoner_Number then\n return True;\n else\n for I in Integer range 1 .. Max_Attempts loop\n Current_Card := Cupboard (Current_Card);\n if Current_Card = Prisoner_Number then\n return True;\n end if;\n end loop;\n end if;\n return False;\n end Optimal_Strategy;\n\n function Random_Strategy\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Prisoner_Number : Integer) return Boolean\n is\n Current_Card : Positive;\n G : Generator;\n begin\n Reset (G);\n Current_Card := Cupboard (Prisoner_Number);\n if Current_Card = Prisoner_Number then\n return True;\n else\n for I in Integer range 1 .. Max_Attempts loop\n Current_Card := Cupboard (Random (G));\n if Current_Card = Prisoner_Number then\n return True;\n end if;\n end loop;\n end if;\n return False;\n end Random_Strategy;\n\n function Prisoners_Attempts\n (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Boolean\n is\n begin\n for Prisoner_Number in Integer range 1 .. Max_Prisoners loop\n if not Strategy\n (Cupboard, Max_Prisoners, Max_Attempts, Prisoner_Number)\n then\n return False;\n end if;\n end loop;\n return True;\n end Prisoners_Attempts;\n \n -- The function to play the game itself\n\n function Play_Game\n (Repetitions : in Positive;\n Strategy : not null access function\n (Cupboard : in Drawers; Max_Prisoners : Integer;\n Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)\n return Win_Percentage\n is\n Cupboard : Drawers;\n Win, Game_Count : Natural := 0;\n Number_Of_Prisoners : constant Integer := 100;\n Max_Attempts : constant Integer := 50;\n begin\n loop\n Initialise_Drawers (Cupboard);\n if Prisoners_Attempts\n (Cupboard => Cupboard, Max_Prisoners => Number_Of_Prisoners,\n Max_Attempts => Max_Attempts, Strategy => Strategy)\n then\n Win := Win + 1;\n end if;\n Game_Count := Game_Count + 1;\n exit when Game_Count = Repetitions;\n end loop;\n return Win_Percentage ((Float (Win) / Float (Repetitions)) * 100.0);\n end Play_Game;\n\nend Prisoners;\n", "safe": true }, { "filename": "100_prisoners_80.txt", "content": "Simulation count: 10000\nOptimal play wins: 33.1%\nRandom play wins: 0.0%\n", "safe": true }, { "filename": "100_prisoners_81.txt", "content": "import java.util.Collections;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n private static boolean playOptimal(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (int i = 0; i < secretList.size(); ++i) {\n int prev = i;\n for (int j = 0; j < secretList.size() / 2; ++j) {\n if (secretList.get(prev) == i) {\n continue prisoner;\n }\n prev = secretList.get(prev);\n }\n return false;\n }\n return true;\n }\n\n private static boolean playRandom(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (Integer i : secretList) {\n List trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(trialList);\n\n for (int j = 0; j < trialList.size() / 2; ++j) {\n if (Objects.equals(trialList.get(j), i)) {\n continue prisoner;\n }\n }\n\n return false;\n }\n return true;\n }\n\n private static double exec(int n, int p, Function play) {\n int succ = 0;\n for (int i = 0; i < n; ++i) {\n if (play.apply(p)) {\n succ++;\n }\n }\n return (succ * 100.0) / n;\n }\n\n public static void main(String[] args) {\n final int n = 100_000;\n final int p = 100;\n System.out.printf(\"# of executions: %d\\n\", n);\n System.out.printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, Main::playOptimal));\n System.out.printf(\"Random play success rate: %f%%\\n\", exec(n, p, Main::playRandom));\n }\n}\n", "safe": true }, { "filename": "100_prisoners_82.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.343000%\nRandom play success rate: 0.000000%", "safe": true }, { "filename": "100_prisoners_83.txt", "content": "const _ = require('lodash');\n\nconst numPlays = 100000;\n\nconst setupSecrets = () => {\n\t// setup the drawers with random cards\n\tlet secrets = [];\n\n\tfor (let i = 0; i < 100; i++) {\n\t\tsecrets.push(i);\n\t}\n\n\treturn _.shuffle(secrets);\n}\n\nconst playOptimal = () => {\n\t\n\tlet secrets = setupSecrets();\n\t\n\n\t// Iterate once per prisoner\n\tloop1:\n\tfor (let p = 0; p < 100; p++) {\n\t\t\n\t\t// whether the prisoner succeedss\n\t\tlet success = false;\n\t\t\n\t\t// the drawer number the prisoner chose\n\t\tlet choice = p;\n\t\t\n\t\t\n\t\t// The prisoner can choose up to 50 cards\n\t\tloop2:\n\t\tfor (let i = 0; i < 50; i++) {\n\t\t\t\n\t\t\t// if the card in the drawer that the prisoner chose is his card\n\t\t\tif (secrets[choice] === p){\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak loop2;\n\t\t\t}\n\n\t\t\t// the next drawer the prisoner chooses will be the number of the card he has.\n\t\t\tchoice = secrets[choice];\n\t\t\n\t\t}\t// each prisoner gets 50 chances\n\n\t\t\n\t\tif (!success) return false;\n\n\t} // iterate for each prisoner \n\n\treturn true;\n}\n\nconst playRandom = () => {\n\n\tlet secrets = setupSecrets();\n\n\t// iterate for each prisoner \n\tfor (let p = 0; p < 100; p++) {\n\n\t\tlet choices = setupSecrets();\n\t\t\n\t\tlet success = false;\n\t\t\n\t\tfor (let i = 0; i < 50; i++) {\n\n\t\t\tif (choices[i] === p) {\n\t\t\t\tsuccess = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!success) return false;\n\t}\n\n\treturn true;\n}\n\nconst execOptimal = () => {\n\n\tlet success = 0;\n\t\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playOptimal()) success++;\n\t\t\t\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconst execRandom = () => {\n\n\tlet success = 0;\n\n\tfor (let i = 0; i < numPlays; i++) {\n\n\t\tif (playRandom()) success++;\n\n\t}\n\n\treturn 100.0 * success / 100000;\n}\n\nconsole.log(\"# of executions: \" + numPlays);\nconsole.log(\"Optimal Play Success Rate: \" + execOptimal());\nconsole.log(\"Random Play Success Rate: \" + execRandom());\n", "safe": true }, { "filename": "100_prisoners_84.txt", "content": "\"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}\n", "safe": true }, { "filename": "100_prisoners_85.txt", "content": "Games count: 2000\nProbability of success with \"random\" strategy: 0\nProbability of success with \"optimal\" strategy: 33.2", "safe": true }, { "filename": "100_prisoners_86.txt", "content": "export LC_ALL=C\n< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq\n", "safe": true }, { "filename": "100_prisoners_87.txt", "content": "def count(s): reduce s as $x (0; .+1);\n\n# Output: a PRN in range(0;$n) where $n is .\ndef prn:\n if . == 1 then 0\n else . as $n\n | (($n-1)|tostring|length) as $w\n | [limit($w; inputs)] | join(\"\") | tonumber\n | if . < $n then . else ($n | prn) end\n end;\n\ndef knuthShuffle:\n length as $n\n | if $n <= 1 then .\n else {i: $n, a: .}\n | until(.i == 0;\n .i += -1\n | (.i + 1 | prn) as $j\n | .a[.i] as $t\n | .a[.i] = .a[$j]\n | .a[$j] = $t)\n | .a \n end;", "safe": true }, { "filename": "100_prisoners_88.txt", "content": "# Output: if all the prisoners succeed, emit true, otherwise false\ndef optimalStrategy($drawers; np):\n # Does prisoner $p succeed?\n def succeeds($p):\n first( foreach range(0; np/2) as $d ({prev: $p};\n .curr = ($drawers[.prev])\n | if .curr == $p\n then .success = true\n else .prev = .curr\n end;\n select(.success))) // false;\n \n all( range(0; np); succeeds(.) );\n \n# Output: if all the prisoners succeed, emit true, otherwise false\ndef randomStrategy($drawers; np):\n (np/2) as $maxd\n # Does prisoner $p succeed?\n | def succeeds($p):\n {success: false }\n | first(.d = 0\n | .opened = []\n | until( (.d >= $maxd) or .success;\n (np|prn) as $n\n | if .opened[$n] then .\n else .opened[$n] = true\n | .d += 1\n | .success = $drawers[$n] == $p\n end )\n | select(.success) ) // false;\n\n all( range(0; np); succeeds(.) );\n\n\ndef run(strategy; trials; np):\n count(range(0; trials)\n | ([range(0;np)] | knuthShuffle) as $drawers\n | select (if strategy == \"optimal\"\n then optimalStrategy($drawers; np)\n else randomStrategy($drawers; np)\n end ) );\n\ndef task($trials):\n def percent: \"\\(10000 * . | round / 100)%\";\n def summary(strategy):\n \"With \\(strategy) strategy: pardoned = \\(.), relative frequency = \\(./$trials | percent)\";\n\n (10, 100) as $np\n | \"Results from \\($trials) trials with \\($np) prisoners:\",\n (run(\"random\"; $trials; $np) | summary(\"random\")),\n (run(\"optimal\"; $trials; $np) | summary(\"optimal\")),\n \"\"\n;\n\ntask(100000)", "safe": true }, { "filename": "100_prisoners_89.txt", "content": "Results from 100000 trials with 10 prisoners:\nWith random strategy: pardoned = 92, relative frequency = 0.09%\nWith optimal strategy: pardoned = 31212, relative frequency = 31.21%\n\nResults from 100000 trials with 100 prisoners:\nWith random strategy: pardoned = 0, relative frequency = 0%\nWith optimal strategy: pardoned = 31026, relative frequency = 31.03%\n", "safe": true }, { "filename": "100_prisoners_9.txt", "content": "with Prisoners; use Prisoners;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Main is\n Wins : Win_Percentage;\n package Win_Percentage_IO is new Float_IO (Win_Percentage);\nbegin\n Wins := Play_Game (100_000, Optimal_Strategy'Access);\n Put (\"Optimal Strategy = \");\n Win_Percentage_IO.Put (Wins, 2, 2, 0);\n Put (\"%\");\n New_Line;\n Wins := Play_Game (100_000, Random_Strategy'Access);\n Put (\"Random Strategy = \");\n Win_Percentage_IO.Put (Wins, 2, 2, 0);\n Put (\"%\");\nend Main;\n", "safe": true }, { "filename": "100_prisoners_90.txt", "content": "using Random, Formatting\n\nfunction randomplay(n, numprisoners=100)\n pardoned, indrawer, found = 0, collect(1:numprisoners), false\n for i in 1:n\n shuffle!(indrawer)\n for prisoner in 1:numprisoners\n found = false\n for reveal in randperm(numprisoners)[1:div(numprisoners, 2)]\n indrawer[reveal] == prisoner && (found = true) && break\n end\n !found && break\n end\n found && (pardoned += 1)\n end\n return 100.0 * pardoned / n\nend\n\nfunction optimalplay(n, numprisoners=100)\n pardoned, indrawer, found = 0, collect(1:numprisoners), false\n for i in 1:n\n shuffle!(indrawer)\n for prisoner in 1:numprisoners\n reveal = prisoner\n found = false\n for j in 1:div(numprisoners, 2)\n card = indrawer[reveal]\n card == prisoner && (found = true) && break\n reveal = card\n end\n !found && break\n end\n found && (pardoned += 1)\n end\n return 100.0 * pardoned / n\n end\n\nconst N = 100_000\nprintln(\"Simulation count: $N\")\nprintln(\"Random play wins: \", format(randomplay(N), precision=8), \"% of simulations.\")\nprintln(\"Optimal play wins: \", format(optimalplay(N), precision=8), \"% of simulations.\")\n", "safe": true }, { "filename": "100_prisoners_91.txt", "content": "Simulation count: 100000\nRandom play wins: 0.00000000% of simulations.\nOptimal play wins: 31.18100000% of simulations.\n", "safe": true }, { "filename": "100_prisoners_92.txt", "content": "import std/num/random\n\nvalue struct drawer\n num: int\n open: bool = False\n\ninline extern unsafe-assign : forall ( v : vector, i : ssize_t, x : a ) -> total ()\n c \"kk_vector_unsafe_assign\"\n\nfun createDrawers()\n val drawers = vector(100, Drawer(0,open=True))\n for(0, 99) fn(i)\n var found := False\n while {!found}\n val r = random-int() % 100\n if drawers[r].open then\n drawers.unsafe-assign(r.ssize_t, Drawer(i))\n found := True\n else\n ()\n drawers\n\nfun closeAll(d:vector)\n for(0,99) fn(i)\n d.unsafe-assign(i.ssize_t, d[i](open=False))\n\neffect fail\n final ctl failed(): a \n\nfun open-random(drawers: vector)\n val r = random-int() % 100\n val opened = drawers[r]\n if opened.open then\n open-random(drawers)\n else\n drawers.unsafe-assign(r.ssize_t, opened(open=True))\n opened.num\n\nfun random-approach(drawers: vector)\n for(0, 99) fn(i)\n var found := False\n for(0, 49) fn(j)\n val opened = open-random(drawers)\n if opened == i then\n found := True\n else\n ()\n if !found then\n failed()\n else\n drawers.closeAll()\n\nfun optimal-approach(drawers: vector)\n for(0, 99) fn(i)\n var found := False\n var drawer := i;\n for(0, 49) fn(j)\n val opened = drawers[drawer]\n if opened.open then\n failed()\n if opened.num == i then\n found := True\n else\n drawers.unsafe-assign(drawer.ssize_t, opened(open=True))\n drawer := opened.num\n if !found then\n failed()\n else\n drawers.closeAll()\n ()\n\nfun run-trials(f, num-trials)\n var num_success := 0\n for(0,num-trials - 1) fn(i)\n val drawers = createDrawers()\n with handler\n return(x) -> \n num_success := num_success + 1\n final ctl failed() -> \n ()\n f(drawers)\n num_success\n\nfun main()\n val num_trials = 1000\n val num_success_random = run-trials(random-approach, num_trials)\n val num_success_optimal = run-trials(optimal-approach, num_trials)\n println(\"Number of trials: \" ++ num_trials.show)\n println(\"Random approach: wins \" ++ num_success_random.show ++ \" (\" ++ (num_success_random.float64 * 100.0 / num_trials.float64).show(2) ++ \"%)\")\n println(\"Optimal approach: wins \" ++ num_success_optimal.show ++ \" (\" ++ (num_success_optimal.float64 * 100.0 / num_trials.float64).show(2) ++ \"%)\")\n", "safe": true }, { "filename": "100_prisoners_93.txt", "content": "Number of trials: 1000\nRandom approach: wins 0 (0.00%)\nOptimal approach: wins 319 (31.90%)\n", "safe": true }, { "filename": "100_prisoners_94.txt", "content": "val playOptimal: () -> Boolean = {\n val secrets = (0..99).toMutableList()\n var ret = true\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n var prev = i\n draw@ for(j in 0 until 50){\n if (secrets[prev] == i) continue@prisoner\n prev = secrets[prev]\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nval playRandom: ()->Boolean = {\n var ret = true\n val secrets = (0..99).toMutableList()\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n val opened = mutableListOf()\n val genNum : () ->Int = {\n var r = (0..99).random()\n while (opened.contains(r)) {\n r = (0..99).random()\n }\n r\n }\n for(j in 0 until 50){\n val draw = genNum()\n if ( secrets[draw] == i) continue@prisoner\n opened.add(draw)\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nfun exec(n:Int, play:()->Boolean):Double{\n var succ = 0\n for (i in IntRange(0, n-1)){\n succ += if(play()) 1 else 0\n }\n return (succ*100.0)/n\n}\n\nfun main() {\n val N = 100_000\n println(\"# of executions: $N\")\n println(\"Optimal play success rate: ${exec(N, playOptimal)}%\")\n println(\"Random play success rate: ${exec(N, playRandom)}%\")\n}\n", "safe": true }, { "filename": "100_prisoners_95.txt", "content": "# of executions: 100000\nOptimal play success rate: 31.451%\nRandom play success rate: 0.0%\n", "safe": true }, { "filename": "100_prisoners_96.txt", "content": "function shuffle(tbl)\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\n return tbl\nend\n\nfunction playOptimal()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local success = false\n\n local choice = p\n for i=1,50 do\n if secrets[choice] == p then\n success = true\n break\n end\n choice = secrets[choice]\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction playRandom()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local choices = {}\n for i=1,100 do\n choices[i] = i\n end\n shuffle(choices)\n\n local success = false\n for i=1,50 do\n if choices[i] == p then\n success = true\n break\n end\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction exec(n,play)\n local success = 0\n for i=1,n do\n if play() then\n success = success + 1\n end\n end\n return 100.0 * success / n\nend\n\nfunction main()\n local N = 1000000\n print(\"# of executions: \"..N)\n print(string.format(\"Optimal play success rate: %f\", exec(N, playOptimal)))\n print(string.format(\"Random play success rate: %f\", exec(N, playRandom)))\nend\n\nmain()\n", "safe": true }, { "filename": "100_prisoners_97.txt", "content": "# of executions: 1000000\nOptimal play success rate: 31.237500\nRandom play success rate: 0.000000", "safe": true }, { "filename": "100_prisoners_98.txt", "content": "p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));\n# p=1/2", "safe": true }, { "filename": "100_prisoners_99.txt", "content": "p^100;\nevalf(%);\n\n# 1/1267650600228229401496703205376\n# 7.888609052e-31", "safe": true }, { "filename": "15 puzzle game_1.txt", "content": "T Puzzle\n position = 0\n [Int = String] items\n\n F main_frame()\n V& d = .items\n print(\u2018+-----+-----+-----+-----+\u2019)\n print(\u2018|#.|#.|#.|#.|\u2019.format(d[1], d[2], d[3], d[4]))\n print(\u2018+-----+-----+-----+-----+\u2019)\n print(\u2018|#.|#.|#.|#.|\u2019.format(d[5], d[6], d[7], d[8]))\n print(\u2018+-----+-----+-----+-----+\u2019)\n print(\u2018|#.|#.|#.|#.|\u2019.format(d[9], d[10], d[11], d[12]))\n print(\u2018+-----+-----+-----+-----+\u2019)\n print(\u2018|#.|#.|#.|#.|\u2019.format(d[13], d[14], d[15], d[16]))\n print(\u2018+-----+-----+-----+-----+\u2019)\n\n F format(=ch)\n ch = ch.trim(\u2018 \u2019)\n I ch.len == 1\n R \u2018 \u2019ch\u2018 \u2019\n E I ch.len == 2\n R \u2018 \u2019ch\u2018 \u2019\n E\n assert(ch.empty)\n R \u2018 \u2019\n\n F change(=to)\n V fro = .position\n L(a, b) .items\n I b == .format(String(to))\n to = a\n L.break\n swap(&.items[fro], &.items[to])\n .position = to\n\n F build_board(difficulty)\n L(i) 1..16\n .items[i] = .format(String(i))\n V tmp = 0\n L(a, b) .items\n I b == \u2018 16 \u2019\n .items[a] = \u2018 \u2019\n tmp = a\n L.break\n .position = tmp\n Int diff\n I difficulty == 0\n diff = 10\n E I difficulty == 1\n diff = 50\n E\n diff = 100\n L 0 .< diff\n V lst = .valid_moves()\n [Int] lst1\n L(j) lst\n lst1.append(Int(j.trim(\u2018 \u2019)))\n .change(lst1[random:(lst1.len)])\n\n F valid_moves()\n V pos = .position\n I pos C [6, 7, 10, 11]\n R [.items[pos - 4], .items[pos - 1], .items[pos + 1], .items[pos + 4]]\n E I pos C [5, 9]\n R [.items[pos - 4], .items[pos + 4], .items[pos + 1]]\n E I pos C [8, 12]\n R [.items[pos - 4], .items[pos + 4], .items[pos - 1]]\n E I pos C [2, 3]\n R [.items[pos - 1], .items[pos + 1], .items[pos + 4]]\n E I pos C [14, 15]\n R [.items[pos - 1], .items[pos + 1], .items[pos - 4]]\n E I pos == 1\n R [.items[pos + 1], .items[pos + 4]]\n E I pos == 4\n R [.items[pos - 1], .items[pos + 4]]\n E I pos == 13\n R [.items[pos + 1], .items[pos - 4]]\n E\n assert(pos == 16)\n R [.items[pos - 1], .items[pos - 4]]\n\n F game_over()\n V flag = 0B\n L(a, b) .items\n I b\u00a0!= \u2018 \u2019\n I a == Int(b.trim(\u2018 \u2019))\n flag = 1B\n E\n flag = 0B\n R flag\n\nV g = Puzzle()\ng.build_board(Int(input(\"Enter the difficulty\u00a0: 0 1 2\\n2 => highest 0 => lowest\\n\")))\ng.main_frame()\nprint(\u2018Enter 0 to exit\u2019)\nL\n print(\"Hello user:\\nTo change the position just enter the no. near it\")\n V lst = g.valid_moves()\n [Int] lst1\n L(i) lst\n lst1.append(Int(i.trim(\u2018 \u2019)))\n print(i.trim(\u2018 \u2019)\" \\t\", end' \u2018\u2019)\n print()\n V x = Int(input())\n I x == 0\n L.break\n E I x !C lst1\n print(\u2018Wrong move\u2019)\n E\n g.change(x)\n g.main_frame()\n I g.game_over()\n print(\u2018You WON\u2019)\n L.break", "safe": true }, { "filename": "15 puzzle game_10.txt", "content": "#include \n\n#define FILATABLA 5\n#define COLUMNATABLA 10\n#define Imprimelamatriz Gosub 'Pone la matriz'\n#define Imprimelascasillas Gosub 'Pone las casillas'\n#define Imprimeel\u00edndiceen(_X_,_Y_) Set '_X_,_Y_', Gosub 'Pone el \u00edndice'\n\nMain\n Set break\n\n Void (casilla, \u00edndice, n\u00fameros)\n Link gosub( Crea una casilla, Crea el \u00edndice, Crea la matriz de n\u00fameros )\n \n Cls\n x=4, y=4, Tok sep '\"\"', Gosub 'Imprime escenario'\n \n /* INICIA EL JUEGO */\n SW = 1, GANADOR = 0\n c=0, cero x=4, cero y=4\n \n Loop\n Let ( c:=Getch )\n Switch ( c )\n Case 'KRIGHT' { #( y < 4 ) do{ ++y }, Exit }\n Case 'KDOWN' { #( x < 4 ) do{ ++x }, Exit }\n Case 'KLEFT' { #( y > 1 ) do{ --y }, Exit }\n Case 'KUP' { #( x > 1 ) do{ --x }, Exit }\n Case 'KRETURN' { If ( Gosub 'Chequear si movimiento es v\u00e1lido' )\n Gosub 'Mover las casillas'\n End If\n Exit\n }\n Case 'KESCAPE' { SW=0 }\n End switch\n \n Gosub 'Imprime escenario'\n Break if ( Gosub 'Verificar puzzle resuelto' --- Backup to 'GANADOR' )\n Back if 'SW' is not zero\n\n /* FIN DEL JUEGO */\n If ( GANADOR )\n Locate (18,15), Printnl(\"LO RESOLVISTE!\")\n End If\n Locate (19,1), Prnl\nEnd\n\nSubrutines\n\n/* CHEQUEO DE MOVIMIENTO */\n\nDefine ( Verificar puzzle resuelto )\n ret = 0\n Clr all marks\n Tn\u00fameros=n\u00fameros\n Redim (Tn\u00fameros,0), N = 0, Let ( N\u00a0:= Length(Tn\u00fameros) Minus (1))\n i=1\n Iterator ( ++i, Less equal ( i, N ) And( Not(ret) ), \\\n Let ( ret\u00a0:= Bit xor(i, [i] Get 'Tn\u00fameros') ) )\n Clr all marks\n Clear 'Tn\u00fameros'\n\nReturn 'Not (ret); And( Equals(i, Plus one(N)) ) '\n\nDefine ( Chequear si movimiento es v\u00e1lido )\nReturn 'Only one ( Equals (x, cero x), Equals(y, cero y ) )'\n\nDefine ( Mover las casillas )\n If ( Equals (y, cero y) )\n If ( Less (x, cero x) ) // mueve hacia abajo\n Loop for ( i = cero x, #( i >= x ) , --i )\n If ( Greater ( i, 1 ) )\n [{i} Minus(1), y] Get 'n\u00fameros', [i,y] Put 'n\u00fameros'\n Else\n [{i} Plus(1), y] Get 'n\u00fameros', [i,y] Put 'n\u00fameros'\n End If\n Next\n Else // por defecto: mueve hacia arriba\n Loop for ( i = cero x, #( i <= x ) , ++i )\n If ( Less ( i, 4 ) )\n [{i} Plus(1), y] Get 'n\u00fameros', [i,y] Put 'n\u00fameros'\n Else\n [i,y] Get 'n\u00fameros', [{i} Minus(1),y] Put 'n\u00fameros'\n End If\n Next\n End If\n [x,y] Set '0', Put 'n\u00fameros'\n Set 'x', Move to 'cero x'\n Else // por defecto: est\u00e1 en la misma fila \n If ( Less ( y, cero y ) ) // mueve hacia la derecha\n Loop for ( i = cero y, #( i >= y ) , --i )\n If ( Greater ( i, 1) )\n [x, {i} Minus(1)] Get 'n\u00fameros', [x,i] Put 'n\u00fameros'\n Else\n [x, y] Get 'n\u00fameros', [x, {i} Plus(1)] Put 'n\u00fameros'\n End If\n Next\n Else // por defecto: mueve hacia la izquierda\n Loop for ( i = cero y, #( i <= y ) , ++i )\n If ( Less ( i, 4 ) )\n [x, {i} Plus(1)] Get 'n\u00fameros', [x,i] Put 'n\u00fameros'\n Else\n [x,i] Get 'n\u00fameros', [x,{i} Minus(1)] Put 'n\u00fameros'\n End If\n Next\n End If\n [x,y] Set '0', Put 'n\u00fameros'\n Set 'y', Move to 'cero y'\n End If\n Clr all marks\nReturn\n\n/* DESPLIEGUE DE CUADRITOS Y NUMEROS */\n\nDefine ( Imprime escenario )\n Imprime las casillas\n Imprime el \u00edndice en 'x,y'\n Imprime la matriz\nReturn\n\nDefine ( Pone la matriz )\n i=4, col = COLUMNA TABLA, celda=\"\"\n Clr all marks\n py=1\n Loop\n j=4, fil = FILA TABLA, px=1\n Loop\n Locate 'Plus one(fil), Plus two (col)' \n Printnl( Get if ([px,py] Get 'n\u00fameros' ---Backup to (celda)---, celda, \" \") )\n fil += 3 \n --j, ++px\n Back if (j) is not zero\n col += 6, --i, ++py\n Back if (i) is not zero\nReturn\n\nDefine ( Pone las casillas )\n i=4, col = COLUMNA TABLA\n Clr all marks\n Loop\n j=4, fil = FILA TABLA\n Loop\n Set 'fil, col', Gosub 'Pone un cuadrito'\n fil += 3, --j\n Back if (j) is not zero\n col += 6, --i\n Back if (i) is not zero\nReturn\n\nDefine (Pone un cuadrito, fil, col)\n Locate 'fil, col', Print table 'casilla'\nReturn\n\nDefine ( Pone el \u00edndice, fil, col )\n /* 5+(fil-1)*3 fila\n 10+(col-1)*6 col */\n Clr all marks\n Locate 'Minus one(fil) Mul by (3) Plus (FILA TABLA), Minus one(col) Mulby(6) Plus(COLUMNA TABLA)' \n Print table '\u00edndice'\nReturn\n\n/* CONFIGURACION DEL JUEGO */\n\nDefine ( Crea la matriz de n\u00fameros )\n Sequence ( 0, 1, 16, n\u00fameros )\n Gosub 'Barajar el array'\n Redim ( n\u00fameros, 4,4 )\nReturn\n\n/* algoritmo de Fisher-Yates */\nDefine ( Barajar el array )\n N = 0, Let ( N\u00a0:= Length(n\u00fameros) )\n R = 0, aux = 0\n Loop\n Let (R\u00a0:= Ceil(Rand(N)))\n Let (aux\u00a0:= [R] Get 'n\u00fameros' )\n [N] Get 'n\u00fameros', [R] Put 'n\u00fameros'\n Set 'aux', [N] Put 'n\u00fameros'\n --N\n Back if 'N' is positive\n If ( [16] Get 'n\u00fameros' ---Backup to 'aux'---, Not (Is zero?) )\n [aScan(1,0,n\u00fameros)] Set 'aux', Put 'n\u00fameros'\n [16] Set '0', Put 'n\u00fameros'\n End If\nReturn\n\nDefine ( Crea una casilla )\n Set 'Utf8(Chr(218)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(191))', Apnd row 'casilla'\n Set 'Utf8(Chr(179)),\" \",\" \",\" \",\" \",Utf8(Chr(179))', Apnd row 'casilla'\n Set 'Utf8(Chr(192)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(196)),Utf8(Chr(217))', Apnd row 'casilla'\nReturn\n\nDefine ( Crea el \u00edndice )\n Set 'Utf8(Chr(220)),Utf8(Chr(220)),Utf8(Chr(220)),Utf8(Chr(220)),Utf8(Chr(220)),Utf8(Chr(220))', Apnd row '\u00edndice'\n Set 'Utf8(Chr(219)),\" \",\" \",\" \",\" \",Utf8(Chr(219))', Apnd row '\u00edndice'\n Set 'Utf8(Chr(223)),Utf8(Chr(223)),Utf8(Chr(223)),Utf8(Chr(223)),Utf8(Chr(223)),Utf8(Chr(223))', Apnd row '\u00edndice'\nReturn", "safe": true }, { "filename": "15 puzzle game_100.txt", "content": "> puz15(scramble.length=4)\n+----+----+----+----+ \n| 1 | 2 | 3 | 4 |\n+----+----+----+----+\n| 5 | 6 | 7 | 8 |\n+----+----+----+----+\n| 9 | 10 | | 12 |\n+----+----+----+----+\n| 13 | 14 | 11 | 15 |\n+----+----+----+----+\nMove:w\n+----+----+----+----+ \n| 1 | 2 | 3 | 4 |\n+----+----+----+----+\n| 5 | 6 | 7 | 8 |\n+----+----+----+----+\n| 9 | 10 | 11 | 12 |\n+----+----+----+----+\n| 13 | 14 | | 15 |\n+----+----+----+----+\nMove:a\n+----+----+----+----+ \n| 1 | 2 | 3 | 4 |\n+----+----+----+----+\n| 5 | 6 | 7 | 8 |\n+----+----+----+----+\n| 9 | 10 | 11 | 12 |\n+----+----+----+----+\n| 13 | 14 | 15 | |\n+----+----+----+----+\n\n[1] \"You win!\"\n\n It took you 2 moves. \n", "safe": true }, { "filename": "15 puzzle game_101.txt", "content": "#lang racket/base\n(require 2htdp/universe 2htdp/image racket/list racket/match)\n\n(define ((fifteen->pict (finished? #f)) fifteen)\n (for/fold ((i (empty-scene 0 0))) ((r 4))\n (define row\n (for/fold ((i (empty-scene 0 0))) ((c 4))\n (define v (list-ref fifteen (+ (* r 4) c)))\n (define cell\n (if v\n (overlay/align\n \"center\" \"center\"\n (rectangle 50 50 'outline (if finished? \"white\" \"blue\"))\n (text (number->string v) 30 \"black\"))\n (rectangle 50 50 'solid (if finished? \"white\" \"powderblue\"))))\n (beside i cell)))\n (above i row)))\n\n(define (move-space fifteen direction)\n (define idx (for/first ((i (in-naturals)) (x fifteen) #:unless x) i))\n (define-values (row col) (quotient/remainder idx 4))\n (define dest (+ idx (match direction\n ['l #:when (> col 0) -1]\n ['r #:when (< col 3) 1]\n ['u #:when (> row 0) -4]\n ['d #:when (< row 3) 4]\n [else 0])))\n (list-set (list-set fifteen idx (list-ref fifteen dest)) dest #f))\n\n(define (key-move-space fifteen a-key)\n (cond [(key=? a-key \"left\") (move-space fifteen 'l)]\n [(key=? a-key \"right\") (move-space fifteen 'r)]\n [(key=? a-key \"up\") (move-space fifteen 'u)]\n [(key=? a-key \"down\") (move-space fifteen 'd)]\n [else fifteen]))\n\n(define (shuffle-15 fifteen shuffles)\n (for/fold ((rv fifteen)) ((_ shuffles))\n (move-space rv (list-ref '(u d l r) (random 4)))))\n\n(define fifteen0 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #f))\n\n(define (solved-world? w) (equal? w fifteen0))\n\n(big-bang (shuffle-15 fifteen0 200)\n (name \"Fifteen\")\n (to-draw (fifteen->pict))\n (stop-when solved-world? (fifteen->pict #t))\n (on-key key-move-space))\n", "safe": true }, { "filename": "15 puzzle game_102.txt", "content": "use Term::termios;\n\nconstant $saved = Term::termios.new(fd => 1).getattr;\nconstant $termios = Term::termios.new(fd => 1).getattr;\n# raw mode interferes with carriage returns, so\n# set flags needed to emulate it manually\n$termios.unset_iflags();\n$termios.unset_lflags(< ECHO ICANON IEXTEN ISIG>);\n$termios.setattr(:DRAIN);\n\n# reset terminal to original setting on exit\nEND { $saved.setattr(:NOW) }\n\nconstant n = 4; # board size\nconstant cell = 6; # cell width\n\nconstant $top = join '\u2500' x cell, '\u250c', '\u252c' xx n-1, '\u2510';\nconstant $mid = join '\u2500' x cell, '\u251c', '\u253c' xx n-1, '\u2524';\nconstant $bot = join '\u2500' x cell, '\u2514', '\u2534' xx n-1, '\u2518';\n\nmy %dir = (\n \"\\e[A\" => 'up',\n \"\\e[B\" => 'down',\n \"\\e[C\" => 'right',\n \"\\e[D\" => 'left',\n);\n\nmy @solved = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' '];\nmy @board;\nnew();\n\nsub new () {\n loop {\n @board = shuffle();\n last if parity-ok(@board);\n }\n}\n\nsub parity-ok (@b) {\n my $row = @b.first(/' '/,:k);\n my $col = @b[$row].first(/' '/,:k);\n so ([3,3] <<->> [$row,$col]).sum\u00a0%% 2;\n}\n\nsub shuffle () {\n my @c = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' '];\n for (^16).pick(*) -> $y, $x {\n my ($yd, $ym, $xd, $xm) = ($y div n, $y mod n, $x div n, $x mod n);\n @(@c[$ym;$yd],@c[$xm;$xd]) = @(@c[$xm;$xd],@c[$ym;$yd]);\n }\n @c;\n}\n\nsub row (@row) { '\u2502' ~ (join '\u2502', @row\u00bb.¢er) ~ '\u2502' }\n\nsub center ($s){\n my $c = cell - $s.chars;\n my $pad = ' ' x ceiling($c/2);\n sprintf \"%{cell}s\", \"$s$pad\";\n}\n\nsub draw-board {\n run('clear');\n print qq:to/END/;\n\n\n\tPress direction arrows to move.\n\n\tPress q to quit. Press n for a new puzzle.\n\n\t$top\n\t{ join \"\\n\\t$mid\\n\\t\", map { .&row }, @board }\n\t$bot\n\n\t{ (so @board ~~ @solved)\u00a0?? 'Solved!!'\u00a0!! '' }\nEND\n}\n\nsub slide (@c is copy) {\n my $t = (grep { /' '/ },\u00a0:k, @c)[0];\n return @c unless $t and $t > 0;\n @c[$t,$t-1] = @c[$t-1,$t];\n @c;\n}\n\nproto sub move (|) {*};\n\nmulti move('up') {\n map { @board[*;$_] = reverse slide reverse @board[*;$_] }, ^n;\n}\n\nmulti move('down') {\n map { @board[*;$_] = slide @board[*;$_] }, ^n;\n}\n\nmulti move('left') {\n map { @board[$_] = reverse slide reverse @board[$_] }, ^n;\n}\n\nmulti move('right') {\n map { @board[$_] = slide @board[$_] }, ^n;\n}\n\nloop {\n draw-board;\n\n # Read up to 4 bytes from keyboard buffer.\n # Page navigation keys are 3-4 bytes each.\n # Specifically, arrow keys are 3.\n my $key = $*IN.read(4).decode;\n\n move %dir{$key} if so %dir{$key};\n last if $key eq 'q'; # (q)uit\n new() if $key eq 'n';\n}\n", "safe": true }, { "filename": "15 puzzle game_103.txt", "content": "\tPress direction arrows to move.\n\n\tPress q to quit. Press n for a new puzzle.\n\n\t\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\t\u2502 2 \u2502 1 \u2502 10 \u2502 14 \u2502\n\t\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\t\u2502 15 \u2502 11 \u2502 12 \u2502 \u2502\n\t\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\t\u2502 13 \u2502 3 \u2502 6 \u2502 7 \u2502\n\t\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\t\u2502 9 \u2502 4 \u2502 5 \u2502 8 \u2502\n\t\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n", "safe": true }, { "filename": "15 puzzle game_104.txt", "content": "rebol [] random/seed now g: [style t box red [\n if not find [0x108 108x0 0x-108 -108x0] face/offset - e/offset [exit]\n x: face/offset face/offset: e/offset e/offset: x] across\n] x: random repeat i 15 [append x:[] i] repeat i 15 [\n repend g ['t mold x/:i random white] if find [4 8 12] i [append g 'return]\n] append g [e: box] view layout g\n", "safe": true }, { "filename": "15 puzzle game_105.txt", "content": "Red [Needs: 'view]\nsystem/view/screens/1/pane/-1/visible?: false ;; suppress console window\n;; because this code is heavily influenced / (copied from ... )\n;; by the rebol version ( which actually works with red as well with\n;; some minimal changes ) i added some comments to make the\n;; code more readable...\n\n;;-----------------------------------------\n;; check, if puzzle is solved, OK button closes program\n;;-----------------------------------------\ncheck: does [\n;; the text on each tile must be equal to its position:\n repeat pos 15 [ unless pos = to-integer lay/pane/:pos/text [exit] ]\n view/flags [ title \"SuCCeSS\" \n text \"You solved the puzzle\u00a0! \" button \"OK\" [quit]\n ] [modal popup] \n]\n;;--------------------------------------\n;; actually only changes text / Number on tile / button\n;;---------------------------------------\nchangeTiles: func [ f ][\n ;; this is tricky, check if e(mpty) button is one in of the\n ;; four valid positions , by simply subtracting their offsets...else exit ( no change)\n unless find [ 0x52 0x-52 52x0 -52x0 ] f/offset - e/offset [return false]\n e/text: f/text ;; empty button gets Number from clicked button\n e/visible?: true ;; empty gets visible\n f/visible?: false ;; clicked button gets invisible\n e: f ;; e(mpty) refers now to clicked button\n return true ;; true - change has happened\n]\n;;-----------------------------------------\n;; function which is executed, when button is clicked\n;; argument is face - button\n;;-------------------------------------\nbClicked: func [f][ if changeTiles f [check] ]\n \n;; define the window:\n;; style is a prototype definition for a button element\nwin: [ title \"15 Puzzle\"\n\t\tbackdrop silver\n\t\tstyle btn: button 40x40 [bClicked face] font-size 15 bold \n]\n;; generate 1..15 buttons with number \nrepeat nr 15 [\n repend win [ 'btn form nr ] ;; repend reduces and then appends..\n if 0 = mod nr 4 [ append win 'return ] ;; \"carriage return\" in window after 4 buttons\n\t]\n ;; append empty / hidden button no 16 and return/quit button:\n\tappend win [ e: btn \"16\" hidden return button \"Quit\" [quit]]\n \nlay: layout win\n;; define win as layout, so each button can now be addressed as\n;; layout/pane/index ( 1..15 - redbol is 1 based )\n\nflip: 0 \n;; start random generator, otherwise we always get the same puzzle\nrandom/seed now/time/precise \n;; lets flip random tiles a few times to initialize the puzzle\n;; ( actually numbers < 100 are quite easy to solve )\n\nwhile [ flip < 40 ] [ if changeTiles lay/pane/(random 16) [ flip: flip + 1 ] ]\n\n;; show the window... \nview lay\n", "safe": true }, { "filename": "15 puzzle game_106.txt", "content": "/*REXX pgm implements the 15\u2500puzzle (AKA: Gem Puzzle, Boss Puzzle, Mystic Square, 14\u250015)*/\nparse arg N seed . /*obtain optional arguments from the CL*/\nif N=='' | N==\",\" then N=4 /*Not specified? Then use the default.*/\nif datatype(seed, 'W') then call random ,,seed /*use repeatability seed for RANDOM BIF*/\nnh= N**2; @.=; nn= nh - 1; w= length(nn) /*define/initialize some handy values. */\n$= /*$: will hold the solution for testing*/\n do i=1 for nn; $= $ i /* [\u25c4] build a solution for testing. */\n end /*i*/\ndone= $ /* [\u2193] scramble the tiles in puzzle. */\n do j=1 for nn; a= random(1, words($) ); @.j= word($, a); $= delword($, a, 1)\n end /*j*/\n /*\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 play the 15\u2500puzzle 'til done or quit.*/\n do until puzz==done & @.nh=='' /*perform moves until puzzle is solved.*/\n call getmv /*get user's move(s) and validate it.*/\n if errMsg\\=='' then do; say sep errMsg; iterate /*possible error msg? */\n end\n call showGrid 0 /*don't display puzzle, just find hole.*/\n if wordpos(x, !)==0 then do; say sep 'tile ' x \" can't be moved.\"; iterate\n end\n @.hole= x; @.tile=\n call showGrid 0 /*move specified tile \u2500\u2500\u2500\u25ba puzzle hole.*/\n end /*until*/ /*\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550*/\n\ncall showGrid 1; say; say sep 'Congratulations! The' nn\"-puzzle is solved.\"\nexit 0 /*stick a fork in it, we're all done. */\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\ngetmv: x= 0; sep= copies('\u2500', 8); pad= left('', 1 + length(sep) ) /*pad=9 blanks*/\n prompt= sep 'Please enter a tile number or numbers ' sep \" (or Quit).\"\n if queued()==0 then do; say; call showGrid 1; say; say prompt\n end\n parse pull x . 1 ox . 1 . zx; upper x /*obtain a number (or numbers) from CL.*/\n if abbrev('QUIT', x, 1) then do; say; say; say sep \"quitting.\"; exit\n end\n if words(zx)>0 then do; parse var zx xq; queue xq\n end /* [\u2191] Extra moves? Stack for later. */\n select /* [\u2193] Check for possible errors/typos*/\n when x=='' then errMsg= \"nothing entered.\"\n when \\datatype(x, 'N') then errMsg= \"tile number isn't numeric: \" ox\n when \\datatype(x, 'W') then errMsg= \"tile number isn't an integer: \" ox\n when x=0 then errMsg= \"tile number can't be zero: \" ox\n when x<0 then errMsg= \"tile number can't be negative: \" ox\n when x>nn then errMsg= \"tile number can't be greater than\" nn\n otherwise errMsg=\n end /*select*/ /* [\u2191] verify the human entered data. */\n return\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500*/\nshowGrid: parse arg show; !.=; x= x/1; #= 0; puzz=\n top= '\u2554'copies( copies(\"\u2550\", w)'\u2566', N); top= left( top, length(top) -1)\"\u2557\"\n bar= '\u2560'copies( copies(\"\u2550\", w)'\u256c', N); bar= left( bar, length(bar) -1)\"\u2563\"\n bot= '\u255a'copies( copies(\"\u2550\", w)'\u2569', N); bot= left( bot, length(bot) -1)\"\u255d\"\n if show then say pad top\n\n do r=1 for N; z= '\u2551'\n do c=1 for N; #= #+1; y= @.#; puzz= puzz y; !.r.c= y\n _= right(@.#, w)\"\u2551\"; z= z || _ /* [\u2193] find hole*/\n if @.# == '' then do; hole= #; holeRow= r; holeCol= c; end\n if @.# == x then do; tile= #; tileRow= r; tileCol= c; end\n end /*c*/ /* [\u2191] find X. */\n if show then do; say pad z; if r\\==N then say pad bar; end\n end /*r*/\n\n rm=holeRow-1; rp=holeRow+1; cm=holeCol-1; cp=holeCol+1 /*possible moves.*/\n !=!.rm.holeCol !.rp.holeCol !.holeRow.cm !.holeRow.cp /* legal moves.*/\n if show then say pad bot; return\n", "safe": true }, { "filename": "15 puzzle game_107.txt", "content": " \u2554\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2557\n \u255110\u2551 7\u2551 8\u255111\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 4\u2551 3\u255115\u2551 1\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 9\u255112\u2551 2\u255113\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u255114\u2551 5\u2551 6\u2551 \u2551\n \u255a\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u255d\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a tile number or numbers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 (or Quit).\n13 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input. \n \u2554\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2557\n \u255110\u2551 7\u2551 8\u255111\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 4\u2551 3\u255115\u2551 1\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 9\u255112\u2551 2\u2551 \u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u255114\u2551 5\u2551 6\u255113\u2551\n \u255a\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u255d\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a tile number or numbers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 (or Quit).\n1 15 3 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input. \n \u2554\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2566\u2550\u2550\u2557\n \u255110\u2551 7\u2551 8\u255111\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 4\u2551 \u2551 3\u255115\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u2551 9\u255112\u2551 2\u2551 1\u2551\n \u2560\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u256c\u2550\u2550\u2563\n \u255114\u2551 5\u2551 6\u255113\u2551\n \u255a\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u255d\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a tile number or numbers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 (or Quit).\nquit \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input. \n\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 quitting.\n", "safe": true }, { "filename": "15 puzzle game_108.txt", "content": "# Project\u00a0: CalmoSoft Fifteen Puzzle Game \n# Date \u00a0: 2018/12/01\n# Author \u00a0: Gal Zsolt (CalmoSoft), Bert Mariani\n# Email \u00a0: calmosoft@gmail.com\n\nload \"guilib.ring\"\n\napp1 = new qapp {\n\n stylefusionblack()\n empty = 16 \n nr_moves = 0\n nr_sleep = 1\n button_size = 4 \n current_button = 4\n temp = 0\n flag_init = 0\n flag_save = 0\n flag_move = 0\n button = list(52) \n size_button = list(7)\n table1 = [] \n table2 = [] \n table3 = []\n n_degree = 0\n nr_degree = [0,90,180,270 ,-90,-180,-270]\n n_degreeRight = 0\n n_degreeLeft = 0\n btn_degree = newlist(52,2)\n counter_man = 0 \n t1 = 0\n\n win1 = new qwidget() {\n move(0,0)\n resize(380,760)\n setwindowtitle(\"CalmoSoft Fifteen Puzzle Game\")\n\n for n=1 to 52\n for m=1 to 2\n btn_degree[n][m] = 0\n next\n next \n\n for n = 4 to 7\n size_button[n] = new qpushbutton(win1) \n {\n col = n%4\n setgeometry(100+col*40,60,40,40)\n settext(string(n) + \"x\" + string(n))\n setclickevent(\"newsize(\" + string(n) + \")\")\n } \n next \n\n btnMoves = new qpushbutton(win1)\n {\n setgeometry(100,260,80,40)\n settext(\"0\")\n show() \n }\n\n scramblebtn = new qpushbutton(win1)\n {\n setgeometry(100,300,160,40)\n settext(\"Scramble\")\n setclickevent(\"scramble()\") \n }\n\n resetbtn = new qpushbutton(win1) \n {\n setgeometry(100,340,160,40)\n settext(\"Reset\")\n setclickevent(\"resettiles()\")\n }\n\n savebtn = new qpushbutton(win1) \n {\n setgeometry(100,380,160,40) \n settext(\"Save Game\") \n setclickevent(\"pSave()\")\n }\n\n playbtn = new qpushbutton(win1) \n {\n setgeometry(100,420,160,40) \n settext(\"Resume Game\") \n setclickevent(\"pPlay()\")\n }\n\n sleepbtn = new qpushbutton(win1) \n {\n setgeometry(100,460,160,40) \n settext(\"Sleep Time: \") \n\n }\n\n decbtn = new qpushbutton(win1) \n {\n setgeometry(220,460,40,40) \n settext(\"<-\") \n setclickevent(\"pDecSleep()\")\n }\n\n incbtn = new qpushbutton(win1) \n {\n setgeometry(260,460,40,40) \n settext(\"->\") \n setclickevent(\"pIncSleep()\")\n }\n\n rightbtn = new qpushbutton(win1) \n {\n setgeometry(100,500,160,40) \n settext(\"In the Right Place\u00a0: \") \n }\n\n timebtn = new qpushbutton(win1) \n {\n setgeometry(100,540,160,40) \n settext(\"Elapsed Time\u00a0: \") \n }\n\n TimerMan = new qtimer(win1)\n {\n setinterval(500)\n settimeoutevent(\"pTime()\")\n stop()\n }\n newsize(4) \n show()\n }\n exec()\n}\n\nFunc newlist x, y\n if isstring(x) x=0+x ok\n if isstring(y) y=0+y ok\n alist = list(x)\n for t in alist\n t = list(y)\n next\n return alist\n\nfunc scramble\n for n= 1 to 1000 \n current_button=random(button_size*button_size-1)+1\n up = (empty = (current_button - button_size))\n down = (empty = (current_button + button_size))\n left = ((empty = (current_button - 1)) and ((current_button\u00a0% button_size)\u00a0!= 1))\n right = ((empty = (current_button + 1)) and ((current_button\u00a0% button_size)\u00a0!= 0))\n move = up or down or left or right\n if move = 1 \n button[current_button] { temp2 = text() }\n col = empty%button_size\n if col = 0 col = button_size ok\n row = ceil(empty/button_size)\n button[empty] {\n setgeometry(60+col*40,60+row*40,40,40)\n rnd = random(6)+1\n n_degree = nr_degree[rnd]\n button[empty].setbuttoncolor(\"yellow\")\n button[empty].settext(temp2)\n button[empty].setClickEvent(\"movetile(\" + string(empty) +\")\")\n btn_degree[empty] [1] = temp2\n btn_degree[empty] [2] = n_degree\n }\n button[current_button].setbuttoncolor(\"yellow\")\n btn_degree[current_button][2] = 0\n button[current_button]{settext(\"\")}\n empty = current_button\n ok\n next\n button[button_size*button_size+2]{settext(\"Here\")}\n for n=1 to button_size*button_size\n button[n].setbuttoncolor(\"yellow\")\n next\n table1 = []\n table2 = []\n table3 = [] \n for n = 1 to button_size*button_size\n add(table1, button[n].text())\n add(table2, button[n].text())\n add(table3, string(btn_degree[n][2]))\n next\n add(table1, string(empty))\n add(table2, string(empty))\n add(table3, string(empty))\n add(table1, \"OK\")\n add(table2, \"OK\")\n add(table3, \"OK\")\n flag_save = 0\n flag_move = 0\n nr_moves = 0\n btnMoves.settext(string(nr_moves))\n timebtn.settext(\"Elapsed Time\u00a0: \")\n t1 = clock()\n rightPlace()\n return\n\nfunc movetile current_button2\n if (current_button2 = button_size*button_size-1 and button[current_button2].text() = \"In\")\n pBack()\n else\n see char(7)\n up = (empty = (current_button2 - button_size))\n down = (empty = (current_button2 + button_size))\n left = ((empty = (current_button2- 1)) and ((current_button2\u00a0% button_size)\u00a0!= 1))\n right = ((empty = (current_button2 + 1)) and ((current_button2\u00a0% button_size)\u00a0!= 0))\n move = up or down or left or right\n if move = 1 \n temp2 = button[current_button2].text() \n btn_degree[empty][1] = temp2\n add(table1, temp2)\n add(table2, string(current_button2)) \n col = empty%button_size\n if col = 0 col = button_size ok\n row = ceil(empty/button_size)\n button[empty] {\n setgeometry(60+col*40,60+row*40,40,40)\n n_degree = btn_degree[current_button2][2]\n btn_degree[empty][2] = n_degree\n button[empty].setbuttoncolor(\"orange\")\n button[empty].settext(temp2) \n }\n add(table3, string(n_degree))\n button[current_button2].setbuttoncolor(\"cyan\")\n button[current_button2]{settext(\"\")}\n empty = current_button2\n nr_moves = nr_moves + 1\n btnMoves.settext(string(nr_moves))\n isGameOver()\n ok\n ok \n flag_move = 1\n pElapsedTime()\n rightPlace()\n return\n\nfunc resettiles\n n_degree = 0 \n empty = button_size*button_size\n for empty = 1 to button_size*button_size-1\n btn_degree[empty][2] = 0\n n_degree = 0\n btn_degree[empty][1] = string(empty)\n button[empty].setstylesheet(\"background-color:yellow\")\n button[empty] {settext(string(empty))}\n next\n button[button_size*button_size].setstylesheet(\"background-color:yellow\")\n button[button_size*button_size] {settext(\"\")}\n table1 = []\n table2 = []\n table3 = [] \n for n = 1 to button_size*button_size\n add(table1, button[n].text())\n add(table2, button[n].text())\n add(table3, string(btn_degree[n][2]))\n next\n add(table1, string(empty))\n add(table2, string(empty))\n add(table3, string(empty))\n add(table1, \"OK\")\n add(table2, \"OK\")\n add(table3, \"OK\")\n flag_save = 0\n flag_move = 0\n nr_moves = 0\n btnMoves.settext(string(nr_moves))\n timebtn.settext(\"Elapsed Time\u00a0: \")\n t1 = clock()\n rightPlace()\n return\n\nfunc pHere\n if button[button_size*button_size-1].text()\u00a0!= \"\" and button[button_size*button_size+2].text() = \"Here\"\n button[button_size*button_size-1] { temp = text() }\n button[button_size*button_size+2].close()\n button[button_size*button_size+2] = new ButtonWithRotatedText(win1)\n button[button_size*button_size+2] {\n setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40)\n setstylesheet(\"background-color:yellow\")\n btn_degree[button_size*button_size+2][2] = btn_degree[button_size*button_size-1][2]\n n_degree = btn_degree[button_size*button_size+2][2]\n emptysave = empty\n empty = button_size*button_size+2\n btn_degree[empty][1] = temp\n settext(temp)\n }\n n_degree = 0\n empty = button_size*button_size-1\n btn_degree[empty][1] = \"In\"\n button[button_size*button_size-1]{settext(\"In\")}\n for n = 1 to button_size*button_size\n\t button[n].setenabled(false)\n next\n button[button_size*button_size-1].setenabled(true)\n scramblebtn.setenabled(false)\n resetbtn.setenabled(false)\n savebtn.setenabled(false)\n playbtn.setenabled(false)\n empty = emptysave\n ok\n\nfunc pBack\n button[button_size*button_size+2] { temp = text() }\n n_degree = btn_degree[button_size*button_size+2][2]\n btn_degree[button_size*button_size-1][2] = btn_degree[button_size*button_size+2][2]\n emptysave = empty\n empty = button_size*button_size-1\n btn_degree[empty][1] = temp\n button[button_size*button_size-1] {settext(temp)}\n button[button_size*button_size+2].close()\n button[button_size*button_size+2] = new qpushbutton(win1)\n {\n setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40)\n settext(\"Here\")\n setclickevent(\"pHere()\") \n show() \n } \n for n = 1 to button_size*button_size\n button[n].setenabled(true)\n next\n scramblebtn.setenabled(true)\n resetbtn.setenabled(true)\n savebtn.setenabled(true)\n playbtn.setenabled(true)\n empty = emptysave\n isGameOver()\n\nfunc rotateleft\n if button[button_size*button_size+2].text()\u00a0!= \"Here\" \n button[button_size*button_size+2].close()\n button[button_size*button_size+2] = new ButtonWithRotatedText(win1)\n button[button_size*button_size+2] {\n setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40)\n setstylesheet(\"background-color:yellow\")\n n_degreeLeft = (n_degreeLeft-90)%360\n n_degree = n_degreeLeft\n btn_degree[button_size*button_size+2][2] = n_degree\n emptysave = empty\n empty = button_size*button_size+2\n btn_degree[empty][1] = temp\n button[button_size*button_size+2]{settext(temp)}\n } \n empty = emptysave\n ok\n\nfunc rotateright\n if button[button_size*button_size+2].text()\u00a0!= \"Here\" \n button[button_size*button_size+2].close()\n button[button_size*button_size+2] = new ButtonWithRotatedText(win1)\n button[button_size*button_size+2] {\n setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40)\n setstylesheet(\"background-color:yellow\")\n n_degreeRight = (n_degreeRight+90)%360\n n_degree = n_degreeRight\n btn_degree[button_size*button_size+2][2] = n_degree\n emptysave = empty\n empty = button_size*button_size+2\n btn_degree[empty][1] = temp\n button[button_size*button_size+2]{settext(temp)}\n }\n empty = emptysave\n ok\n\nfunc newsize current_button\n win1{ \n sizenew = current_button%4\n win1.resize(360+sizenew*40,640+sizenew*40)\n if flag_init\u00a0!= 0\n for nb = 1 to button_size*button_size+3\n button[nb] {close()}\n next\n btnMoves.close()\n ok\n scramblebtn.close()\n resetbtn.close()\n savebtn.close()\n playbtn.close()\n btnMoves.close()\n sleepbtn.close()\n decbtn.close()\n incbtn.close()\n rightbtn.close()\n timebtn.close()\n\n for n = 1 to current_button*current_button\n col = n%current_button\n if col = 0 col = current_button ok\n row = ceil(n/current_button)\n button[n] = new ButtonWithRotatedText(win1)\n button[n] {\n setgeometry(60+col*40,60+row*40,40,40)\n button[n].setbuttoncolor(\"yellow\") \n n_degree = 0\n if n < current_button*current_button\n button[n].settext(string(n))\n but n = current_button*current_button\n button[n].settext(\"\")\n ok \n setClickEvent(\"movetile(\" + string(n) +\")\")\n }\n next\n\n btnMoves = new qpushbutton(win1)\n {\n setgeometry(100,60+(current_button+1)*40,(current_button-3)*40,40)\n setStyleSheet(\"text-align:center\")\n settext(\"0\")\n show() \n }\n\n button[current_button*current_button+1] = new qpushbutton(win1)\n {\n setgeometry(60+(current_button-2)*40,60+(current_button+1)*40,40,40)\n settext(\"<-\")\n setclickevent(\"rotateLeft()\") \n show() \n } \n\n button[current_button*current_button+2] = new qpushbutton(win1)\n {\n setgeometry(60+(current_button-1)*40,60+(current_button+1)*40,40,40)\n settext(\"Here\")\n setclickevent(\"pHere()\") \n show() \n }\n\n button[current_button*current_button+3] = new qpushbutton(win1)\n {\n setgeometry(60+current_button*40,60+(current_button+1)*40,40,40)\n settext(\"->\")\n setclickevent(\"rotateRight()\") \n show() \n }\n\n scramblebtn = new qpushbutton(win1)\n {\n setgeometry(100,100+(current_button+1)*40,current_button*40,40)\n settext(\"Scramble\")\n setclickevent(\"scramble()\")\n show() \n }\n\n resetbtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+2)*40,current_button*40,40)\n settext(\"Reset\")\n setclickevent(\"resettiles()\")\n show() \n }\n\n savebtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+3)*40,current_button*40,40)\n settext(\"Save Game\")\n setclickevent(\"pSave()\")\n show() \n }\n\n playbtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+4)*40,current_button*40,40) \n settext(\"Resume Game\") \n setclickevent(\"pPlay()\")\n show()\n }\n\n sleepbtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+5)*40,(current_button-2)*40,40) \n settext(\"Sleep Time: \" + string(nr_sleep) + \" s\") \n show()\n }\n\n decbtn = new qpushbutton(win1) \n {\n setgeometry(100+(current_button-2)*40,100+(current_button+5)*40,40,40) \n settext(\"<-\") \n setclickevent(\"pDecSleep()\")\n show()\n }\n\n incbtn = new qpushbutton(win1) \n {\n setgeometry(100+(current_button-1)*40,100+(current_button+5)*40,40,40) \n settext(\"->\") \n setclickevent(\"pIncSleep()\")\n show()\n }\n\n rightbtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+6)*40,current_button*40,40) \n settext(\"In the Right Place\u00a0: \") \n show()\n }\n\n timebtn = new qpushbutton(win1) \n {\n setgeometry(100,100+(current_button+7)*40,current_button*40,40) \n settext(\"Elapsed Time\u00a0: \") \n show()\n }\n\n table1 = []\n table2 = []\n table3 = [] \n for n = 1 to button_size*button_size\n add(table1, button[n].text())\n add(table2, button[n].text())\n add(table3, string(0))\n next\n add(table1, string(empty))\n add(table2, string(empty))\n add(table3, string(empty))\n add(table1, \"OK\")\n add(table2, \"OK\")\n add(table3, \"OK\")\n empty = current_button*current_button\n button_size = current_button\n flag_init = 1\n flag_save = 0\n flag_move = 0\n nr_moves = 0\n timebtn.settext(\"Elapsed Time\u00a0: \")\n t1 = clock()\n scramble()\n }\n\nfunc pSave\n textedit1 = list2str(table1)\n textedit2 = list2str(table2)\n textedit3 = list2str(table3)\n chdir(currentdir())\n cName1 = \"CalmoSoftPuzzle1.txt\"\n cName2 = \"CalmoSoftPuzzle2.txt\"\n cName3 = \"CalmoSoftPuzzle3.txt\"\n write(cName1,textedit1)\n write(cName2,textedit2)\n write(cName3,textedit3)\n flag_save = 1 \n timebtn.settext(\"Elapsed Time\u00a0: \")\n t1 = clock()\n return\n\nfunc pPlay\n if flag_save = 0 or flag_move = 0\n warning() \n else\n chdir(currentdir())\n cName1 = \"CalmoSoftPuzzle1.txt\"\n textedit1 = read(cName1)\n table1 = str2list(textedit1)\n cName2 = \"CalmoSoftPuzzle2.txt\"\n textedit2 = read(cName2)\n table2 = str2list(textedit2)\n cName3 = \"CalmoSoftPuzzle3.txt\"\n textedit3 = read(cName3)\n table3 = str2list(textedit3)\n for empty = 1 to button_size*button_size\n button[empty].setbuttoncolor(\"yellow\") \n n_degree = number(table3[empty])\n btn_degree[empty][1] = table1[empty]\n button[empty] {settext(table1[empty])}\n next\n empty = number(table1[button_size*button_size + 1])\n counter_man = button_size*button_size+2\n nr_moves = 0\n t1 = clock()\n TimerMan.start()\n ok\n\nfunc pTime()\n if flag_save = 0 or flag_move = 0\n warning() \n else\n counter_man++\n pPlaySleep()\n sleep(nr_sleep*1000) \n pElapsedTime()\n if counter_man = len(table1)\n TimerMan.stop()\n ok\n ok\n\nfunc pPlaySleep\n see char(7)\n value = table1[counter_man]\n place = table2[counter_man]\n n_degree = number(table3[counter_man])\n btn_degree[empty][1] = value\n button[empty].setbuttoncolor(\"orange\")\n button[empty] {settext(value)}\n n_degree = 0\n button[number(place)].setbuttoncolor(\"cyan\")\n button[number(place)] {settext(\"\")}\n empty = number(place) \n nr_moves = nr_moves + 1\n btnMoves.settext(string(nr_moves))\n\nfunc pIncSleep\n nr_sleep = nr_sleep + 1 \n sleepbtn.settext(\"Sleep Time: \" + string(nr_sleep) + \" s\")\n\nfunc pDecSleep\n if nr_sleep > 1 \n nr_sleep = nr_sleep - 1\n sleepbtn.settext(\"Sleep Time: \" + string(nr_sleep) + \" s\")\n ok\n\nfunc sleep(x)\n nTime = x \n oTest = new qTest\n oTest.qsleep(nTime)\n return\n\nfunc isGameOver\n flagend = 1\n for n=1 to button_size*button_size-1\n if button[n].text()\u00a0!= n or btn_degree[n][2]\u00a0!= 0\n flagend = 0\n exit\n ok\n next\n if flagend = 1\n new qmessagebox(win1) {\n setwindowtitle(\"Game Over\") \n settext(\"Congratulations!\")\n show()\n } \n ok \n\nfunc rightPlace\n count = 0\n for n=1 to button_size*button_size\n if button[n].text() = n and btn_degree[n][2] = 0\n count = count + 1\n ok\n next \n rightbtn.settext(\"In the Right Place\u00a0: \" + count)\n\nfunc warning\n new qmessagebox(win1) {\n setwindowtitle(\"Warning!\") \n settext(\"First you must play and save the game.\")\n show()\n } \n\nfunc pElapsedTime\n t2 = (clock() - t1)/1000\n timebtn.settext(\"Elapsed Time\u00a0: \" + t2 + \" s\")\n\nClass ButtonWithRotatedText\n\n oButton oLabel cText=\"We are here\" n_degree = 30 nTransX = 50 nTransY = 0\n\nfunc init( oParent)\n oButton = new qPushButton(oParent)\n oLabel = new qLabel(oParent)\n oLabel.setAttribute(Qt_WA_TransparentForMouseEvents,True)\n oLabel.setAttribute(Qt_WA_DeleteOnClose, True)\n oButton.setAttribute(Qt_WA_DeleteOnClose, True)\n oButton.Show()\n return\n \nfunc close()\n oLabel.close()\n oButton.close()\n return\n\nfunc setstylesheet(x)\n oButton.setstylesheet(x)\n\nfunc setgeometry( x,y,width,height)\n oButton.setgeometry(x,y,width,height)\n oLabel.setgeometry( x,y,width,height)\n \nfunc setText( cValue)\n cText = cValue\n return\n \nfunc Text() \n return cText\n\nfunc setTranslate( x,y ) \n nTransX = x\n nTransY = y\t\t\n return\n\nfunc TranslateOffsetX()\n return nTransX \n\nfunc TranslateOffsetY()\n return nTransY \n\t\nfunc setRotation_degree( nValue)\n n_degree = nValue\n return\n \nfunc Rotation_degree()\n return n_degree\n\nfunc setClickEvent( cEvent)\n oButton.setClickEvent(cEvent)\n return\n \nfunc braceend()\n draw() \n return\n\nfunc setEnabled(value) \n oButton.setenabled(value)\n return\t\n\n func setButtonColor(color) \n colorIt = \"background-color:\" + color \n oButton.setstylesheet(colorIt) \n return\n \t\nfunc draw()\n picture = new qpicture()\n color = new qcolor() { setrgb(0,0,255,255) }\n pen = new qpen() { setcolor(color) setwidth(10) }\n \n painter = new qpainter() \n {\n begin(picture) \n setpen(pen)\n oFont = new qfont(\"Courier New\",12,75,0)\n oFont.setpointsize(20)\n setfont(oFont)\n if n_degree = 0\n if btn_degree[empty] [1]=\"In\" p1 = -8 p2=0 \n translate(p1,p2) ok ok\n if n_degree = 0\n if btn_degree[empty] [1]<10 p1 = 10 p2=10 else p1=5 p2=10 ok\n translate(p1,p2)\n but n_degree = 90\n if btn_degree[empty] [1]<10 p=-10 else p=-15 ok\n translate(10,p)\n but n_degree = 180\n if btn_degree[empty] [1]<10 p1= 30 p2=-10 else p1=35 p2=-10 ok\n translate(p1,p2)\n but n_degree = 270\n if btn_degree[empty] [1]<10 p=10 else p=15 ok\n translate(30,p)\n but n_degree = -90\n if btn_degree[empty] [1]<10 p=10 else p=15 ok\n translate(30,p)\n but n_degree = -180\n if btn_degree[empty] [1]<10 p1=30 p2=-10 else p1=35 p2=-10 ok\n translate(p1,p2)\n but n_degree = -270\n if btn_degree[empty] [1]<10 p1=10 p2=-10 else p1=10 p2=-15 ok\n translate(p1,p2)\n ok\t\t\t\t\t\t\n rotate(n_degree)\n\t drawtext(0,0,this.Text()) \n endpaint()\n }\n oLabel {\n setpicture(picture) \n show() \n }\n return", "safe": true }, { "filename": "15 puzzle game_109.txt", "content": "/*\n**\n**\tGame \t\t\t\u00a0: CalmoSoft Fifteen Puzzle Game 3D \n**\tDate \t\t\t\u00a0: 2017/09/01\n** Author \t\t\t\u00a0: CalmoSoft , Mahmoud Fayed\n**\n*/\n\n# Load Libraries\nload \"gamelib.ring\"\t\t# RingAllegro Library\nload \"opengl21lib.ring\"\t# RingOpenGL Library\n\nbutSize = 3\ntexture = list(9)\ncube = list(9)\nrnd = list(9)\nrndok = 0\n\nfor n=1 to 9\n rnd[n] = 0\nnext \n\nfor n=1 to 9\n while true\n rndok = 0\n ran = random(8) + 1\n for nr=1 to 9\n if rnd[nr] = ran\n rndok = 1\n ok\n next \n if rndok = 0\n rnd[n] = ran\n exit\n ok \n end\nnext \n\nfor n=1 to 9\n if rnd[n] = 9\n empty = n\n ok\nnext \n\n#==============================================================\n# To Support MacOS X\n\tal_run_main()\t\n\tfunc al_game_start \t# Called by al_run_main()\n\t\tmain()\t\t# Now we call our main function\n#==============================================================\n\nfunc main\n\tnew TicTacToe3D {\n\t\tstart()\n\t}\n\nclass TicTacToe3D from GameLogic\n\n\tFPS = 60\n\tTITLE = \"CalmoSoft Fifteen Puzzle Game 3D\"\n\n\toBackground = new GameBackground\n\toGameSound = new GameSound\n\toGameCube = new GameCube\n\toGameInterface = new GameInterface \n\n\tfunc loadresources\n\t\toGameSound.loadresources()\n\t\toBackGround.loadresources()\n\t\toGameCube.loadresources()\n\n\tfunc drawScene\n\t\toBackground.update()\n\t\toGameInterface.update(self)\n\n\tfunc MouseClickEvent\n\t\toGameInterface.MouseClickEvent(self)\n\nclass GameInterface \n\n\tfunc Update oGame\n\t\tprepare()\n\t\tcubes(oGame)\n\n\tfunc Prepare \n\t\tw = 1024 h = 768\n\t\tratio = w / h\n\t\tglViewport(0, 0, w, h)\n\t\tglMatrixMode(GL_PROJECTION)\n\t\tglLoadIdentity()\n\t\tgluPerspective(-120,ratio,1,120)\n\t\tglMatrixMode(GL_MODELVIEW)\n\t\tglLoadIdentity()\n\t\tglEnable(GL_TEXTURE_2D)\t\t\t\t\t\t\t\n\t\tglShadeModel(GL_SMOOTH)\t\t\n\t\tglClearColor(0.0, 0.0, 0.0, 0.5)\n\t\tglClearDepth(1.0)\t\t\t\n\t\tglEnable(GL_DEPTH_TEST)\t\n\t\tglEnable(GL_CULL_FACE)\n\t\tglDepthFunc(GL_LEQUAL)\n\t\tglHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)\n\n\tfunc Cubes oGame\n\t\toGame.oGameCube {\n\t\taGameMap = oGame.aGameMap \n cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] )\n\t\tcube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] )\n\t\tcube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] )\n\t\tcube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] )\n\t\tcube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] )\n\t\tcube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] )\n\t\tcube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] )\n\t\tcube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] )\n\t\tcube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] )\n \t\trotate()\n\t\t}\n\n\tfunc MouseClickEvent oGame\n\t\toGame {\n\t\t\taBtn = Point2Button(Mouse_X,Mouse_Y)\n move = 0\n\t\t\tnRow = aBtn[1]\n\t\t\tnCol = aBtn[2]\n tile = (nRow-1)*3 + nCol\n up = (empty = (tile - butSize))\n down = (empty = (tile + butSize))\n left = ((empty = (tile- 1)) and ((tile\u00a0% butSize)\u00a0!= 1))\n right = ((empty = (tile + 1)) and ((tile\u00a0% butSize)\u00a0!= 0))\n move = up or down or left or right\n if move = 1 \n temp = rnd[empty]\n rnd[empty] = rnd[tile] \n rnd[tile] = temp\n empty = tile\n oGame.oGameCube {\n\t\t aGameMap = oGame.aGameMap \n cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] )\n\t\t cube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] )\n\t\t cube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] )\n\t\t cube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] )\n\t\t cube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] )\n\t cube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] )\n\t\t cube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] )\n\t cube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] )\n\t\t cube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] )\n \t\t rotate()\n\t\t }\n ok\n\t\t}\n\nClass GameLogic from GraphicsAppBase\n\n\taGameMap = [\n\t\t[ :n , :n , :n ] ,\n\t\t[ :n , :n , :n ] ,\n\t\t[ :n , :n , :n ]\n\t]\n\n\taGameButtons = [\t\t\t# x1,y1,x2,y2\n \t\t[176,88,375,261],\t\t# [1,1]\n\t\t[423,88,591,261],\t\t# [1,2]\n\t\t[645,88,876,261],\t\t# [1,3]\n \t\t[176,282,375,428],\t\t# [2,1]\n\t\t[423,282,591,428],\t\t# [2,2]\n\t\t[645,282,876,428],\t\t# [2,3]\n \t\t[176,454,375,678],\t\t# [3,1]\n\t\t[423,454,591,678],\t\t# [3,2]\n\t\t[645,454,876,678]\t\t# [3,3]\n\t]\n\n\tcActivePlayer = :x\n\n\tfunc point2button x,y\n\t\tnRow = 0\n\t\tnCol = 0\n\t\tfor t = 1 to len(aGameButtons) \n\t\t\trect = aGameButtons[t]\n\t\t\tif x >= rect[1] and x <= rect[3] and\n\t\t\t y >= rect[2] and y <= rect[4] \n\t\t\t\t\tswitch t\n\t\t\t\t\t\ton 1 nRow = 1 nCol = 1\n\t\t\t\t\t\ton 2 nRow = 1 nCol = 2\n\t\t\t\t\t\ton 3 nRow = 1 \tnCol = 3\n\t\t\t\t\t\ton 4 nRow = 2 nCol = 1\n\t\t\t\t\t\ton 5 nRow = 2 nCol = 2\n\t\t\t\t\t\ton 6 nRow = 2 nCol = 3\n\t\t\t\t\t\ton 7 nRow = 3 \tnCol = 1\n\t\t\t\t\t\ton 8 nRow = 3 nCol = 2\n\t\t\t\t\t\ton 9 nRow = 3 nCol = 3\n\t\t\t\t\toff\n\t\t\t\t\texit \n\t\t\tok\n\t\tnext \n\t\treturn [nRow,nCol]\n\nclass GameCube\n\n\tbitmap bitmap2 bitmap3 \n\ttextureX textureO textureN\n\n\txrot = 0.0\n\tyrot = 0.0\n\tzrot = 0.0\n\n\tfunc loadresources\n\t\tbitmp1 = al_load_bitmap(\"image/n1.jpg\")\n\t\ttexture[1] = al_get_opengl_texture(bitmp1)\n\t\tbitmp2 = al_load_bitmap(\"image/n2.jpg\")\n\t\ttexture[2] = al_get_opengl_texture(bitmp2)\n\t\tbitmp3 = al_load_bitmap(\"image/n3.jpg\")\n\t\ttexture[3] = al_get_opengl_texture(bitmp3)\n\t\tbitmp4 = al_load_bitmap(\"image/n4.jpg\")\n\t\ttexture[4] = al_get_opengl_texture(bitmp4)\n\t\tbitmp5 = al_load_bitmap(\"image/n5.jpg\")\n\t\ttexture[5] = al_get_opengl_texture(bitmp5)\n\t\tbitmp6 = al_load_bitmap(\"image/n6.jpg\")\n\t\ttexture[6] = al_get_opengl_texture(bitmp6)\n\t\tbitmp7 = al_load_bitmap(\"image/n7.jpg\")\n\t\ttexture[7] = al_get_opengl_texture(bitmp7)\n\t\tbitmp8 = al_load_bitmap(\"image/n8.jpg\")\n\t\ttexture[8] = al_get_opengl_texture(bitmp8)\n\t\tbitmp9 = al_load_bitmap(\"image/empty.png\")\n\t\ttexture[9] = al_get_opengl_texture(bitmp9)\n\n\tfunc cube(x,y,z,nTexture)\n\t\tglLoadIdentity()\t\t\t\t\t\t\t\t\t\n\t\tglTranslatef(x,y,z)\n\t\tglRotatef(xrot,1.0,0.0,0.0)\n\t\tglRotatef(yrot,0.0,1.0,0.0)\n\t\tglRotatef(zrot,0.0,0.0,1.0)\n\t\tsetCubeTexture(nTexture)\n\t\tdrawCube()\n\n\tfunc setCubeTexture cTexture\n\t\tglBindTexture(GL_TEXTURE_2D, cTexture)\n\n\tfunc Rotate \n\t\txrot += 0.3 * 5\n\t\tyrot += 0.2 * 5\n\t\tzrot += 0.4 * 5\n\n\tfunc drawcube\n\t\tglBegin(GL_QUADS) \n\t\t\t// Front Face\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0)\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, 1.0)\n\t\t\t// Back Face\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, -1.0)\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, -1.0)\n\t\t\t// Top Face\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f(-1.0, 1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f( 1.0, 1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)\n\t\t\t// Bottom Face\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f(-1.0, -1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f( 1.0, -1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)\n\t\t \n\t\t\t// Right face\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, -1.0)\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0)\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)\n\t \n\t\t\t// Left Face\n\t\t\tglTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, -1.0)\n\t\t\tglTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)\n\t\t\tglTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, 1.0)\n\t\t\tglTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)\n\t\tglEnd()\n\n\nclass GameBackground \n\n\tnBackX = 0\n\tnBackY = 0\n\tnBackDiffx = -1\n\tnBackDiffy = -1\n\tnBackMotion = 1\n\taBackMotionList = [\n\t\t[ -1, -1 ] ,\t\t# Down - Right\n\t\t[ 0 , 1 ] ,\t\t# Up\n\t\t[ -1, -1 ] , \t\t# Down - Right\n\t\t[ 0 , 1 ] ,\t\t# Up\n\t\t[ 1 , -1 ] ,\t\t# Down - Left\n\t\t[ 0 , 1 ] ,\t\t# Up\n\t\t[ 1 , -1 ] , \t\t# Down - Left\n\t\t[ 0 , 1 ]\t\t\t# Up\n\t]\n\n\tbitmap\n\n\tfunc Update \n\t\tdraw()\n\t\tmotion()\n\n\tfunc draw\n\t\tal_draw_bitmap(bitmap,nBackX,nBackY,1)\n\n\tfunc motion\n\t\tnBackX += nBackDiffx\n\t\tnBackY += nBackDiffy\n\t\tif (nBackY = -350) or (nBackY = 0)\n\t\t\tnBackMotion++\n\t\t\tif nBackMotion > len(aBackMotionList)\n\t\t\t\tnBackMotion = 1\n\t\t\tok\n\t\t\tnBackDiffx = aBackMotionList[nBackMotion][1]\n\t\t\tnBackDiffy = aBackMotionList[nBackMotion][2]\n\t\tok\n\n\tfunc loadResources\n\t\tbitmap = al_load_bitmap(\"image/back.jpg\")\n\nclass GameSound\n\n\tsample sampleid\n\n\tfunc loadresources\n\t\tsample = al_load_sample( \"sound/music1.wav\" )\n\t\tsampleid = al_new_allegro_sample_id()\n\t\tal_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,sampleid)\n\nclass GraphicsAppBase\n\n\tdisplay event_queue ev timeout \n\ttimer \n\tredraw \t\t\t= true\n\tFPS \t\t\t= 60 \n\tSCREEN_W \t\t= 1024\n\tSCREEN_H \t\t= 700\n\tKEY_UP\t\t\t= 1\n\tKEY_DOWN \t\t= 2\n\tKEY_LEFT \t\t= 3\n\tKEY_RIGHT \t\t= 4\n\tKey \t\t\t= [false,false,false,false]\n\tMouse_X \t\t= 0\n\tMouse_Y\t\t\t= 0\n\tTITLE \t\t\t= \"Graphics Application\"\n\tPRINT_MOUSE_XY \t= False\n\n\tfunc start\n\t\tSetUp()\n\t\tloadResources()\n\t\teventsLoop()\n\t\tdestroy()\n\n\tfunc setup\n\t\tal_init()\n\t\tal_init_font_addon()\n\t\tal_init_ttf_addon()\n\t\tal_init_image_addon()\n\t\tal_install_audio()\n\t\tal_init_acodec_addon()\n\t\tal_reserve_samples(1)\n\t\tal_set_new_display_flags(ALLEGRO_OPENGL) \n\t\tdisplay = al_create_display(SCREEN_W,SCREEN_H)\n\t\tal_set_window_title(display,TITLE)\n\t\tal_clear_to_color(al_map_rgb(0,0,0))\n\t\tevent_queue = al_create_event_queue()\n\t\tal_register_event_source(event_queue, \n\t\tal_get_display_event_source(display))\n\t\tev = al_new_allegro_event()\n\t\ttimeout = al_new_allegro_timeout()\n\t\tal_init_timeout(timeout, 0.06)\n\t\ttimer = al_create_timer(1.0 / FPS)\n\t\tal_register_event_source(event_queue, \n\t\tal_get_timer_event_source(timer))\n\t\tal_start_timer(timer)\n\t\tal_install_mouse()\n\t\tal_register_event_source(event_queue, \n\t\tal_get_mouse_event_source())\n\t\tal_install_keyboard()\n\t\tal_register_event_source(event_queue, \n\t\tal_get_keyboard_event_source())\n\n\tfunc eventsLoop\n\t\twhile true\n\t\t\tal_wait_for_event_until(event_queue, ev, timeout)\n\t\t\tswitch al_get_allegro_event_type(ev)\n\t\t\ton ALLEGRO_EVENT_DISPLAY_CLOSE\n\t\t\t\tCloseEvent()\n\t\t\ton ALLEGRO_EVENT_TIMER\n\t\t\t\tredraw = true\n\t\t\ton ALLEGRO_EVENT_MOUSE_AXES\n\t\t\t\tmouse_x = al_get_allegro_event_mouse_x(ev)\n\t\t\t\tmouse_y = al_get_allegro_event_mouse_y(ev)\n\t\t\t\tif PRINT_MOUSE_XY\n\t\t\t\t\tsee \"x = \" + mouse_x + nl\n\t\t\t\t\tsee \"y = \" + mouse_y + nl\n\t\t\t\tok\n\t\t\ton ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY\n\t\t\t\tmouse_x = al_get_allegro_event_mouse_x(ev)\n\t\t\t\tmouse_y = al_get_allegro_event_mouse_y(ev)\n\t\t\ton ALLEGRO_EVENT_MOUSE_BUTTON_UP\n\t\t\t\tMouseClickEvent()\n\t\t\ton ALLEGRO_EVENT_KEY_DOWN\n\t\t\t\tswitch al_get_allegro_event_keyboard_keycode(ev)\n\t\t\t\t\ton ALLEGRO_KEY_UP\n\t\t\t\t\t\tkey[KEY_UP] = true\n\t\t\t\t\ton ALLEGRO_KEY_DOWN\n\t\t\t\t\t\tkey[KEY_DOWN] = true\n\t\t\t\t\ton ALLEGRO_KEY_LEFT\n\t\t\t\t\t\tkey[KEY_LEFT] = true\n\t\t\t\t\ton ALLEGRO_KEY_RIGHT\n\t\t\t\t\t\tkey[KEY_RIGHT] = true\n\t\t\t\toff\n\t\t\ton ALLEGRO_EVENT_KEY_UP\n\t\t\t\tswitch al_get_allegro_event_keyboard_keycode(ev)\n\t\t\t\t\ton ALLEGRO_KEY_UP\n\t\t\t\t\t\tkey[KEY_UP] = false\n\t\t\t\t\ton ALLEGRO_KEY_DOWN\n\t\t\t\t\t\tkey[KEY_DOWN] = false\n\t\t\t\t\ton ALLEGRO_KEY_LEFT\n\t\t\t\t\t\tkey[KEY_LEFT] = false\n\t\t\t\t\ton ALLEGRO_KEY_RIGHT\n\t\t\t\t\t\tkey[KEY_RIGHT] = false\n\t\t\t\t\ton ALLEGRO_KEY_ESCAPE\n\t\t\t\t\t\texit\n\t\t\t\toff\n\t\t\toff\n\t\t\tif redraw and al_is_event_queue_empty(event_queue)\n\t\t\t\tredraw = false\n\t\t\t\tdrawScene()\n\t\t\t\tal_flip_display()\n\t\t\tok\n\t\t\tcallgc()\n\t\tend\n\n\tfunc destroy\n\t\tal_destroy_timer(timer)\n\t\tal_destroy_allegro_event(ev)\n\t\tal_destroy_allegro_timeout(timeout)\n\t\tal_destroy_event_queue(event_queue)\n\t\tal_destroy_display(display)\n\t\tal_exit()\n\n\tfunc loadresources\n\n\tfunc drawScene\n\n\tfunc MouseClickEvent\n\t\texit \t\t\t# Exit from the Events Loop \n\n\tfunc CloseEvent\n\t\texit \t\t\t# Exit from the Events Loop", "safe": true }, { "filename": "15 puzzle game_11.txt", "content": "$ hopper jm/puzzle.jambo\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 14 \u2502\u2502 5 \u2502\u2502 3 \u2502\u2502 12 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 13 \u2502\u2502 9 \u2502\u2502 6 \u2502\u2502 11 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 15 \u2502\u2502 10 \u2502\u2502 8 \u2502\u2502 2 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u2584\u2584\u2584\u2584\u2584\u2584\n \u2502 4 \u2502\u2502 1 \u2502\u2502 7 \u2502\u2588 \u2588\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2580\u2580\u2580\u2580\u2580\u2580\n ..... (muchos click)\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 7 \u2502\u2502 10 \u2502\u2502 14 \u2502\u2502 12 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 15 \u2502\u2502 \u2502\u2502 4 \u2502\u2502 2 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u2584\u2584\u2584\u2584\u2584\u2584\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 1 \u2502\u2588 8 \u2588\u2502 6 \u2502\u2502 11 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2580\u2580\u2580\u2580\u2580\u2580\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 3 \u2502\u2502 13 \u2502\u2502 5 \u2502\u2502 9 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n ....( muy muchos clicks )\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 1 \u2502\u2502 2 \u2502\u2502 3 \u2502\u2502 4 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 5 \u2502\u2502 6 \u2502\u2502 7 \u2502\u2502 8 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\n \u2502 9 \u2502\u2502 10 \u2502\u2502 11 \u2502\u2502 12 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\n \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510\u2584\u2584\u2584\u2584\u2584\u2584\n \u2502 13 \u2502\u2502 14 \u2502\u2502 15 \u2502\u2588 \u2588\n \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u2580\u2580\u2580\u2580\u2580\u2580\n\n LO RESOLVISTE!\n", "safe": true }, { "filename": "15 puzzle game_110.txt", "content": "require 'io/console'\n\nclass Board\n SIZE = 4\n RANGE = 0...SIZE\n \n def initialize\n width = (SIZE*SIZE-1).to_s.size\n @frame = (\"+\" + \"-\"*(width+2)) * SIZE + \"+\"\n @form = \"|\u00a0%#{width}d \" * SIZE + \"|\"\n @step = 0\n @orign = [*0...SIZE*SIZE].rotate.each_slice(SIZE).to_a.freeze\n @board = @orign.map{|row | row.dup}\n randomize\n draw\n message\n play\n end\n \n private\n \n def randomize\n @board[0][0], @board[SIZE-1][SIZE-1] = 0, 1\n @board[SIZE-1][0], @board[0][SIZE-1] = @board[0][SIZE-1], @board[SIZE-1][0]\n x, y, dx, dy = 0, 0, 1, 0\n 50.times do\n nx,ny = [[x+dx,y+dy], [x+dy,y-dx], [x-dy,y+dx]]\n .select{|nx,ny| RANGE.include?(nx) and RANGE.include?(ny)}\n .sample\n @board[nx][ny], @board[x][y] = 0, @board[nx][ny]\n x, y, dx, dy = nx, ny, nx-x, ny-y\n end\n @x, @y = x, y \n end\n \n def draw\n puts \"\\e[H\\e[2J\"\n @board.each do |row|\n puts @frame\n puts (@form % row).sub(\" 0 \", \" \")\n end\n puts @frame\n puts \"Step: #{@step}\"\n end\n \n DIR = {up: [-1,0], down: [1,0], left: [0,-1], right: [0,1]}\n def move(direction)\n dx, dy = DIR[direction]\n nx, ny = @x + dx, @y + dy\n if RANGE.include?(nx) and RANGE.include?(ny)\n @board[nx][ny], @board[@x][@y] = 0, @board[nx][ny]\n @x, @y = nx, ny\n @step += 1\n draw\n end\n end\n \n def play\n until @board == @orign\n case key_in\n when \"\\e[A\", \"w\" then move(:up)\n when \"\\e[B\", \"s\" then move(:down)\n when \"\\e[C\", \"d\" then move(:right)\n when \"\\e[D\", \"a\" then move(:left)\n \n when \"q\",\"\\u0003\",\"\\u0004\" then exit\n when \"h\" then message\n end\n end\n \n puts \"Congratulations, you have won!\"\n end\n \n def key_in\n input = STDIN.getch\n if input == \"\\e\" \n 2.times {input << STDIN.getch}\n end\n input\n end\n \n def message\n puts <<~EOM\n Use the arrow-keys or WASD on your keyboard to push board in the given direction. \n PRESS q TO QUIT (or Ctrl-C or Ctrl-D)\n EOM\n end\nend\n\nBoard.new\n", "safe": true }, { "filename": "15 puzzle game_111.txt", "content": "+----+----+----+----+\n| 5 | 7 | 2 | 13 |\n+----+----+----+----+\n| 6 | | 8 | 12 |\n+----+----+----+----+\n| 10 | 3 | 1 | 15 |\n+----+----+----+----+\n| 9 | 4 | 14 | 11 |\n+----+----+----+----+\nStep: 0\nUse the arrow-keys or WASD on your keyboard to push board in the given direction.\nPRESS q TO QUIT (or Ctrl-C or Ctrl-D)\n", "safe": true }, { "filename": "15 puzzle game_112.txt", "content": "DIM = 100\nSOLUTION = %w[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0].freeze\n\nattr_reader :bcolor, :dark, :light, :tcolor, :space, :blank, :list\n\ndef settings\n size(400, 400)\nend\n\ndef setup\n sketch_title 'Fifteen Tile Puzzle'\n labels = SOLUTION.shuffle\n @list = []\n grid(width, height, DIM, DIM) do |y, x|\n list << Tile.new(Vec2D.new(x, y), labels[list.length])\n end\n @tcolor = color(255, 175, 0)\n @bcolor = color(235, 231, 178)\n @dark = color(206, 141, 0)\n @light = color(255, 214, 126)\n text_size(DIM / 2.7)\n text_align(CENTER)\n no_loop\nend\n\ndef draw\n list.each(&:draw)\nend\n\ndef mouse_clicked\n inside = list.find_index { |tile| tile.include?(Vec2D.new(mouse_x, mouse_y)) }\n target = list.find_index { |tile| tile.label == '0' }\n source = list[inside].pos\n dest = list[target].pos\n return unless source.dist(dest) == DIM\n\n list[target].label = list[inside].label\n list[inside].label = '0'\n redraw\nend\n\n# Our Tile Boundary Class\nclass Boundary\n attr_reader :low, :high\n\n def initialize(low, high)\n @low = low\n @high = high\n end\n\n def include?(val)\n return false unless (low.x...high.x).cover? val.x\n\n return false unless (low.y...high.y).cover? val.y\n\n true\n end\nend\n\n# Holds Tile logic and draw (Processing::Proxy give access to Sketch methods)\nclass Tile\n include Processing::Proxy\n attr_writer :label\n attr_reader :boundary, :label, :pos\n\n def initialize(pos, lbl)\n @label = lbl\n @pos = pos\n @boundary = Boundary.new(pos, pos + Vec2D.new(DIM, DIM))\n end\n\n def draw_empty\n fill(bcolor)\n rect(pos.x + 1, pos.y + 1, DIM - 1, DIM - 1)\n end\n\n def draw_tile\n rect(pos.x + 1, pos.y + 1, DIM - 1, DIM - 1)\n fill(0) # Black text shadow\n text(label, pos.x + DIM / 2 + 1, pos.y + DIM / 2 + text_ascent / 2)\n fill(255)\n text(label, pos.x + DIM / 2, pos.y + DIM / 2 + text_ascent / 2)\n stroke(dark)\n line(pos.x + DIM - 1, pos.y + 1, pos.x + DIM - 1, pos.y + DIM - 2) # Right side shadow\n line(pos.x + 2, pos.y + DIM, pos.x + DIM - 1, pos.y + DIM - 2) # Bottom side shadow\n stroke(light)\n line(pos.x + 2, pos.y - 1, pos.x + 2, pos.y + DIM - 1) # Left bright\n line(pos.x + 2, pos.y + 1, pos.x + DIM - 1, pos.y + 1) # Upper bright\n end\n\n def include?(vec)\n boundary.include?(vec)\n end\n\n def draw\n no_stroke\n return draw_empty if label == '0'\n\n fill(tcolor)\n draw_tile\n end\nend\n", "safe": true }, { "filename": "15 puzzle game_113.txt", "content": "call SetCSS\n' ---- fill 15 squares with 1 to 15\ndim sq(16)\nfor i = 1 to 15: sq(i) = i: next \n \n'----- shuffle the squares\n[newGame]\nfor i = 1 to 100\t\t' Shuffle the squares\n\tj\t= rnd(0) * 16 + 1\n\tk\t= rnd(0) * 16 + 1\n\th\t= sq(j)\n\tsq(j)\t= sq(k)\n\tsq(k)\t= h\nnext i\n \n' ---- show the squares\n[loop]\ncls\nhtml \"
\"\nfor i = 1 to 16\n\thtml \"\"\n\tif i mod 4 = 0 then html \"\"\nnext i\nhtml \"
\"\n\tif sq(i) <> 0 then\n\t\tbutton\t#pick, str$(sq(i)), [pick]\n\t\t\t#pick setkey(str$(i))\n\t\t\t#pick cssclass(\"lBtn\")\n\tend if\n\thtml \"
\"\nwait\n \n' ---- Find what square they picked\n[pick]\t\t\t\npicked\t= val(EventKey$)\nmove\t= 0 ' 0000000001111111\nif picked - 1 > 0 then ' LEFT 1234567890123456\n\t\t\t\tif mid$(\" *** *** *** ***\",picked,1) = \"*\" and sq(picked -1) = 0 then move = -1 :end if\nif picked + 1 < 17 then ' RIGHT\n\t\t\t\tif mid$(\"*** *** *** *** \",picked,1) = \"*\" and sq(picked +1) = 0 then move = 1 :end if\nif picked - 4 > 0 then ' UP \n\t\t\t\tif mid$(\" ************\",picked,1) = \"*\" and sq(picked -4) = 0 then move = -4 :end if\nif picked + 4 < 17 then ' DOWN \n\t\t\t\tif mid$(\"************ \",picked,1) = \"*\" and sq(picked +4) = 0 then move = 4 :end if\n' ---- See if they picked a valid square next to the blank square\nif move = 0 then\n\tprint \"Invalid move: \";sq(picked)\n\twait\nend if\n \n' ---- Valid squire, switch it with the blank square\nsq(picked + move) = sq(picked) ' move to the empty square\nsq(picked) = 0\nfor i = 1 to 15 ' ---- If they got them all in a row they are a winner\n\tif sq(i) <> i then goto [loop]\nnext i\n \nprint \"----- You are a winner -----\"\ninput \"Play again (Y/N)\";a$\nif a$ = \"Y\" then goto [newGame]\t\t' set up new game\nend\n \n' ---- Make the squares look nice\nSUB SetCSS\nCSSClass \".lBtn\", \"{\nbackground:wheat;border-width:5px;width:70px;\nText-Align:Center;Font-Size:24pt;Font-Weight:Bold;Font-Family:Arial;\n}\"\nEND SUB", "safe": true }, { "filename": "15 puzzle game_114.txt", "content": "extern crate rand;\nuse clearscreen::clear;\nuse std::collections::HashMap;\nuse std::fmt;\nuse std::io::{self, Write};\n\nuse rand::seq::SliceRandom;\nuse rand::Rng;\n\n#[derive(Copy, Clone, PartialEq, Debug)]\nenum Cell {\n Card(usize),\n Empty,\n}\n\n#[derive(Eq, PartialEq, Hash, Debug)]\nenum Direction {\n Up,\n Down,\n Left,\n Right,\n}\n\nenum Action {\n Move(Direction),\n Quit,\n}\n\ntype Board = [Cell; 16];\nconst EMPTY: Board = [Cell::Empty; 16];\n\nstruct P15 {\n board: Board,\n}\n\nimpl P15 {\n fn new() -> Self {\n let mut board = EMPTY;\n for (i, cell) in board.iter_mut().enumerate().skip(1) {\n *cell = Cell::Card(i);\n }\n\n let mut rng = rand::thread_rng();\n\n board.shuffle(&mut rng);\n if !Self::is_valid(board) {\n // random swap\n let i = rng.gen_range(0..16);\n let mut j = rng.gen_range(0..16);\n while j == i {\n j = rng.gen_range(0..16);\n }\n board.swap(i, j);\n }\n\n Self { board }\n }\n\n fn is_valid(mut board: Board) -> bool {\n // TODO: optimize\n let mut permutations = 0;\n\n let pos = board.iter().position(|&cell| cell == Cell::Empty).unwrap();\n\n if pos != 15 {\n board.swap(pos, 15);\n permutations += 1;\n }\n\n for i in 1..16 {\n let pos = board\n .iter()\n .position(|&cell| matches!(cell, Cell::Card(value) if value == i))\n .unwrap();\n\n if pos + 1 != i {\n board.swap(pos, i - 1);\n permutations += 1;\n }\n }\n\n permutations % 2 == 0\n }\n\n fn get_empty_position(&self) -> usize {\n self.board.iter().position(|&c| c == Cell::Empty).unwrap()\n }\n\n fn get_moves(&self) -> HashMap {\n let mut moves = HashMap::new();\n let i = self.get_empty_position();\n\n if i > 3 {\n moves.insert(Direction::Up, self.board[i - 4]);\n }\n if i % 4 != 0 {\n moves.insert(Direction::Left, self.board[i - 1]);\n }\n if i < 12 {\n moves.insert(Direction::Down, self.board[i + 4]);\n }\n if i % 4 != 3 {\n moves.insert(Direction::Right, self.board[i + 1]);\n }\n moves\n }\n\n fn play(&mut self, direction: &Direction) {\n let i = self.get_empty_position();\n // This is safe because `ask_action` only returns legal moves\n match *direction {\n Direction::Up => self.board.swap(i, i - 4),\n Direction::Left => self.board.swap(i, i - 1),\n Direction::Right => self.board.swap(i, i + 1),\n Direction::Down => self.board.swap(i, i + 4),\n };\n }\n\n fn is_complete(&self) -> bool {\n self.board.iter().enumerate().all(|(i, &cell)| match cell {\n Cell::Card(value) => value == i + 1,\n Cell::Empty => i == 15,\n })\n }\n}\n\nimpl fmt::Display for P15 {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n (writeln!(f, \"+----+----+----+----+\"))?;\n for (i, &cell) in self.board.iter().enumerate() {\n match cell {\n Cell::Card(value) => (write!(f, \"| {value:2} \"))?,\n Cell::Empty => (write!(f, \"| \"))?,\n }\n\n if i % 4 == 3 {\n (writeln!(f, \"|\"))?;\n (writeln!(f, \"+----+----+----+----+\"))?;\n }\n }\n Ok(())\n }\n}\n\nfn main() {\n let mut p15 = P15::new();\n\n for turns in 1.. {\n println!(\"{p15}\");\n match ask_action(&p15.get_moves(), true) {\n Action::Move(direction) => {\n p15.play(&direction);\n clear().expect(\"failed to clear screen\");\n }\n Action::Quit => {\n clear().expect(\"failed to clear screen\");\n\n println!(\"Bye!\");\n break;\n }\n }\n\n if p15.is_complete() {\n println!(\"Well done! You won in {turns} turns\");\n break;\n }\n }\n}\n\nfn ask_action(moves: &HashMap, render_list: bool) -> Action {\n use Action::*;\n use Direction::*;\n\n if render_list {\n println!(\"Possible moves:\");\n\n if let Some(&Cell::Card(value)) = moves.get(&Up) {\n println!(\"\\tU) {value}\");\n }\n if let Some(&Cell::Card(value)) = moves.get(&Left) {\n println!(\"\\tL) {value}\");\n }\n if let Some(&Cell::Card(value)) = moves.get(&Right) {\n println!(\"\\tR) {value}\");\n }\n if let Some(&Cell::Card(value)) = moves.get(&Down) {\n println!(\"\\tD) {value}\");\n }\n println!(\"\\tQ) Quit\");\n print!(\"Choose your move: \");\n io::stdout().flush().unwrap();\n } else {\n print!(\"Unknown move, try again: \");\n io::stdout().flush().unwrap();\n }\n\n let mut action = String::new();\n io::stdin().read_line(&mut action).expect(\"read error\");\n match action.to_uppercase().trim() {\n \"U\" if moves.contains_key(&Up) => Move(Up),\n \"L\" if moves.contains_key(&Left) => Move(Left),\n \"R\" if moves.contains_key(&Right) => Move(Right),\n \"D\" if moves.contains_key(&Down) => Move(Down),\n \"Q\" => Quit,\n _ => {\n if unknown_action() {\n ask_action(moves, true)\n } else {\n ask_action(moves, false)\n }\n }\n }\n}\n\nfn unknown_action() -> bool {\n use crossterm::{\n cursor::MoveToPreviousLine,\n terminal::{Clear, ClearType},\n ExecutableCommand,\n };\n std::io::stdout().execute(MoveToPreviousLine(1)).unwrap();\n std::io::stdout()\n .execute(Clear(ClearType::CurrentLine))\n .unwrap();\n false\n}\n", "safe": true }, { "filename": "15 puzzle game_115.txt", "content": "import java.util.Random\n\nimport jline.console._\n\nimport scala.annotation.tailrec\nimport scala.collection.immutable\nimport scala.collection.parallel.immutable.ParVector\n\nobject FifteenPuzzle {\n def main(args: Array[String]): Unit = play()\n \n @tailrec def play(len: Int = 1000): Unit = if(gameLoop(Board.randState(len))) play(len)\n def gameLoop(board: Board): Boolean = {\n val read = new ConsoleReader()\n val km = KeyMap.keyMaps().get(\"vi-insert\")\n val opMap = immutable.HashMap[Operation, Char](\n Operation.PREVIOUS_HISTORY -> 'u',\n Operation.BACKWARD_CHAR -> 'l',\n Operation.NEXT_HISTORY -> 'd',\n Operation.FORWARD_CHAR -> 'r')\n \n @tailrec\n def gloop(b: Board): Boolean = {\n println(s\"\\u001B[2J\\u001B[2;0H$b\\n\u2190\u2191\u2192\u2193q\")\n if(b.isSolved) println(\"Solved!\\nPlay again? (y/n)\")\n \n read.readBinding(km) match{\n case Operation.SELF_INSERT => read.getLastBinding match{\n case \"q\" => false\n case \"y\" if b.isSolved => true\n case \"n\" if b.isSolved => false\n case _ => gloop(b)\n }\n case op: Operation if opMap.isDefinedAt(op) => gloop(b.move(opMap(op)))\n case _ => gloop(b)\n }\n }\n \n gloop(board)\n }\n \n case class Board(mat: immutable.HashMap[(Int, Int), Int], x: Int, y: Int) {\n def move(mvs: Seq[Char]): Board = mvs.foldLeft(this){case (b, m) => b.move(m)}\n def move(mov: Char): Board = mov match {\n case 'r' if x < 3 => Board(mat ++ Seq(((x, y), mat((x + 1, y))), ((x + 1, y), 0)), x + 1, y)\n case 'l' if x > 0 => Board(mat ++ Seq(((x, y), mat((x - 1, y))), ((x - 1, y), 0)), x - 1, y)\n case 'd' if y < 3 => Board(mat ++ Seq(((x, y), mat((x, y + 1))), ((x, y + 1), 0)), x, y + 1)\n case 'u' if y > 0 => Board(mat ++ Seq(((x, y), mat((x, y - 1))), ((x, y - 1), 0)), x, y - 1)\n case _ => this\n }\n \n def isSolved: Boolean = sumDist == 0\n def sumDist: Int = mat.to(LazyList).map{ case ((a, b), n) => if(n == 0) 6 - a - b else (a + b - ((n - 1) % 4) - ((n - 1) / 4)).abs }.sum\n \n override def toString: String = {\n val lst = mat.toVector.map { case ((a, b), n) => (4 * b + a, n) }.sortWith(_._1 < _._1).map(_._2)\n lst.map { n => if (n == 0) \" \" else f\"$n%2d\" }.grouped(4).map(_.mkString(\" \")).mkString(\"\\n\")\n }\n }\n \n object Board {\n val moves: Vector[Char] = Vector('r', 'l', 'd', 'u')\n \n def apply(config: Vector[Int]): Board = {\n val ind = config.indexOf(0)\n val formed = config.zipWithIndex.map { case (n, i) => ((i % 4, i / 4), n) }\n val builder = immutable.HashMap.newBuilder[(Int, Int), Int]\n builder ++= formed\n Board(builder.result, ind % 4, ind / 4)\n }\n \n def solveState: Board = apply((1 to 15).toVector :+ 0)\n def randState(len: Int, rand: Random = new Random()): Board = Iterator\n .fill(len)(moves(rand.nextInt(4)))\n .foldLeft(Board.solveState) { case (state, mv) => state.move(mv) }\n }\n}\n", "safe": true }, { "filename": "15 puzzle game_116.txt", "content": "(import (scheme base)\n (scheme read)\n (scheme write)\n (srfi 27)) ; random numbers\n\n(define *start-position* #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #\\space))\n(random-source-randomize! default-random-source)\n\n;; return a 16-place vector with the tiles randomly shuffled\n(define (create-start-position)\n (let ((board (vector-copy *start-position*)))\n (do ((i 0 (+ 1 i))\n (moves (find-moves board) (find-moves board)))\n ((and (>= i 100)\n (not (finished? board)))\n board)\n (make-move board\n (list-ref moves (random-integer (length moves)))))))\n\n;; return index of space\n(define (find-space board)\n (do ((i 0 (+ 1 i)))\n ((equal? #\\space (vector-ref board i)) i)))\n\n;; return a list of symbols indicating available moves\n(define (find-moves board)\n (let* ((posn (find-space board))\n (row (quotient posn 4))\n (col (remainder posn 4))\n (result '()))\n (when (> row 0) (set! result (cons 'up result)))\n (when (< row 3) (set! result (cons 'down result)))\n (when (> col 0) (set! result (cons 'left result)))\n (when (< col 3) (set! result (cons 'right result)))\n result))\n\n;; make given move - assume it is legal\n(define (make-move board move)\n (define (swap posn-1 posn-2)\n (let ((tmp (vector-ref board posn-1)))\n (vector-set! board posn-1 (vector-ref board posn-2))\n (vector-set! board posn-2 tmp)))\n ;\n (let ((posn (find-space board)))\n (case move\n ((left)\n (swap posn (- posn 1)))\n ((right)\n (swap posn (+ posn 1)))\n ((up)\n (swap posn (- posn 4)))\n ((down)\n (swap posn (+ posn 4))))))\n\n(define (finished? board)\n (equal? board *start-position*))\n\n(define (display-board board)\n (do ((i 0 (+ 1 i)))\n ((= i (vector-length board)) (newline))\n (when (zero? (modulo i 4)) (newline))\n (let ((curr (vector-ref board i)))\n (display curr)\n (display (if (and (number? curr) \n (> curr 9)) \n \" \"\n \" \")))))\n\n;; the main game loop\n(define (play-game)\n (let ((board (create-start-position)))\n (do ((count 1 (+ count 1))\n (moves (find-moves board) (find-moves board)))\n ((finished? board) \n (display (string-append \"\\nCOMPLETED PUZZLE in \"\n (number->string count)\n \" moves\\n\")))\n (display-board board)\n (display \"Enter a move: \") (display moves) (newline)\n (let ((move (read)))\n (if (memq move moves)\n (make-move board move)\n (display \"Invalid move - try again\"))))))\n\n(play-game)\n", "safe": true }, { "filename": "15 puzzle game_117.txt", "content": "1 2 3 \n5 7 6 11 \n13 14 8 4 \n10 9 15 12 \nEnter a move: (right left down)\nright\n\n1 2 3 \n5 7 6 11 \n13 14 8 4 \n10 9 15 12 \nEnter a move: (left down)\ndown\n\n1 2 3 11 \n5 7 6 \n13 14 8 4 \n10 9 15 12 \nEnter a move: (left down up)\ndown\n\n1 2 3 11 \n5 7 6 4 \n13 14 8 \n10 9 15 12 \nEnter a move: (left down up)\n", "safe": true }, { "filename": "15 puzzle game_118.txt", "content": "tiles=[1:15,0];\nsolution=[tiles(1:4);...\n tiles(5:8);...\n tiles(9:12);...\n tiles(13:16)];\nsolution=string(solution);\nsolution(16)=\" \";\n \ninit_pos=grand(1,\"prm\",tiles);\npuzzle=[init_pos(1:4);...\n init_pos(5:8);...\n init_pos(9:12);...\n init_pos(13:16)];\npuzzle=string(puzzle);\n\nblank_pos=[];\nfor i=1:4\n for j=1:4\n if puzzle(i,j)==\"0\" then\n blank_pos=[i,j];\n end\n end\nend\n\nclear i j\n\npuzzle(blank_pos(1),blank_pos(2))=\" \";\n\nn_moves=0;\nsolved=%F;\nwhile ~solved\n disp(puzzle); mprintf(\"\\n\");\n \n neighbours=[0 -1;...\n -1 0;...\n 0 +1;...\n +1 0];\n neighbours(:,1)=neighbours(:,1)+blank_pos(1);\n neighbours(:,2)=neighbours(:,2)+blank_pos(2);\n neighbours=[neighbours zeros(4,1)]\n \n i=0;\n for i=1:4\n if ~(neighbours(i,1)<1 | neighbours(i,1)>4 |...\n neighbours(i,2)<1 | neighbours(i,2)>4) then\n neighbours(i,3)=evstr(puzzle(neighbours(i,1),neighbours(i,2)));\n end\n end\n \n valid_move=%F;\n while ~valid_move\n move_tile=[]; \n move_tile=input(\"Enter tile you want to move (0 to exit):\");\n if sum(move_tile==neighbours(:,3)) & move_tile~=0 then\n valid_move=%T;\n n_moves=n_moves+1;\n elseif move_tile==0 then\n disp(\"Exit\");\n abort\n else\n disp(puzzle);\n disp(\"Invalid input\");\n end\n end\n \n neighb_i=find(neighbours(:,3)'==move_tile);\n puzzle(neighbours(neighb_i,1),neighbours(neighb_i,2))=\" \";\n puzzle(blank_pos(1),blank_pos(2))=string(move_tile);\n blank_pos=neighbours(neighb_i,1:2);\n \n if sum(puzzle==solution)==16 then\n solved=%T;\n disp(puzzle);\n mprintf(\"\\n\"+...\n \" _____ _ _ _ \\n\"+...\n \" / ____| | | | | |\\n\"+...\n \" | (___ ___ | |_ _____ __| | |\\n\"+...\n \" \\\\___ \\\\ / _ \\\\| \\\\ \\\\ / / _ \\\\/ _` | |\\n\"+...\n \" ____) | (_) | |\\\\ V / __/ (_| |_|\\n\"+...\n \" |_____/ \\\\___/|_| \\\\_/ \\\\___|\\\\__,_(_)\\n\")\n end\nend\n\ndisp(\"Solved in \"+string(n_moves)+\" moves.\");\n", "safe": true }, { "filename": "15 puzzle game_119.txt", "content": "!1 2 3 4 \u00a0!\n! \u00a0!\n!5 6 7 8 \u00a0!\n! \u00a0!\n!9 14 10 11 \u00a0!\n! \u00a0!\n!13 15 12 \u00a0!\n\nEnter tile you want to move (0 to exit):\n14\n\n!1 2 3 4 \u00a0!\n! \u00a0!\n!5 6 7 8 \u00a0!\n! \u00a0!\n!9 10 11 \u00a0!\n! \u00a0!\n!13 14 15 12 \u00a0!\n\nEnter tile you want to move (0 to exit):\n10\n\n\n!1 2 3 4 \u00a0!\n! \u00a0!\n!5 6 7 8 \u00a0!\n! \u00a0!\n!9 10 11 \u00a0!\n! \u00a0!\n!13 14 15 12 \u00a0!\n\nEnter tile you want to move (0 to exit):\n11\n\n\n!1 2 3 4 \u00a0!\n! \u00a0!\n!5 6 7 8 \u00a0!\n! \u00a0!\n!9 10 11 \u00a0!\n! \u00a0!\n!13 14 15 12 \u00a0!\n\nEnter tile you want to move (0 to exit):\n12\n\n\n!1 2 3 4 \u00a0!\n! \u00a0!\n!5 6 7 8 \u00a0!\n! \u00a0!\n!9 10 11 12 \u00a0!\n! \u00a0!\n!13 14 15 \u00a0!\n\n _____ _ _ _ \n / ____| | | | | |\n | (___ ___ | |_ _____ __| | |\n \\___ \\ / _ \\| \\ \\ / / _ \\/ _` | |\n ____) | (_) | |\\ V / __/ (_| |_|\n |_____/ \\___/|_| \\_/ \\___|\\__,_(_)\n\n Solved in 4 moves.", "safe": true }, { "filename": "15 puzzle game_12.txt", "content": "fpg\u2190{\u2395IO\u21900\n \u237a\u21904 4\n (s\u2228.<0)\u22282\u2260\u2374s\u2190\u237a:'invalid shape:'s\n 0\u2260\u2374\u2374\u2375:'invalid shuffle count:'\u2375\n d\u2190d,-d\u2190\u21932 2\u23743\u21911\n e\u2190\u00af1+\u2374c\u2190'\u2191\u2193\u2190\u2192\u25cb'\n b\u2190w\u2190s\u2374w\u21901\u233d\u2373\u00d7/s\n z\u2190\u2283{\n z p\u2190\u2375\n n\u2190(?\u2374p)\u2283p\u2190(p\u2261\u00a8(\u2282s)|p)/p\u2190(d~p)+\u2282z\n b[z n]\u2190b[n z]\n -\u2368\\n z\n }\u2363\u2375\u22a2(s-1)0\n \u2395\u2190b\n \u236c{\n b\u2261w:'win'\n 0=\u2374\u237a:\u235e\u2207 \u2375\n e=i\u2190c\u2373m\u2190\u2283\u237a:'quit'\n i>e:\u235e\u2207 \u2375\u22a3\u2395\u2190'invalid direction:'m\n n\u2262s|n\u2190\u2375+i\u2283d:\u235e\u2207 \u2375\u22a3'out of bounds:'m\n b[\u2375 n]\u2190b[n \u2375]\n \u2395\u2190(s\u00d70\u2260\u2374\u237a)\u2374b\n (1\u2193\u237a)\u2207 n\n }z\n}\n", "safe": true }, { "filename": "15 puzzle game_120.txt", "content": "BEGIN\n CLASS FIFTEENPUZZLE(NUMTILES, SIDE, WIDTH, SEED);\n INTEGER NUMTILES, SIDE, WIDTH, SEED;\n BEGIN\n INTEGER ARRAY TILES(0:NUMTILES);\n INTEGER BLANKPOS;\n \n PROCEDURE INVARIANT;\n BEGIN\n INTEGER ARRAY UQ(0:NUMTILES);\n INTEGER I;\n FOR I\u00a0:= 0 STEP 1 UNTIL NUMTILES DO UQ(I)\u00a0:= -1;\n FOR I\u00a0:= 0 STEP 1 UNTIL NUMTILES DO\n BEGIN\n INTEGER T;\n T\u00a0:= TILES(I);\n IF UQ(T) <> -1 THEN ERROR(\"TILES ARE NOT UNIQUE\");\n UQ(T)\u00a0:= T;\n END;\n IF TILES(BLANKPOS) <> 0 THEN ERROR(\"BLANKPOS IS NOT BLANK\");\n END;\n\n PROCEDURE SHUFFLE;\n BEGIN\n BOOLEAN B;\n WHILE NOT B DO\n BEGIN\n INTEGER N;\n RESET;\n \u00a0! DON'T INCLUDE THE BLANK SPACE IN THE SHUFFLE, LEAVE IT\n \u00a0! IN THE HOME POSITION\u00a0;\n N\u00a0:= NUMTILES;\n WHILE N > 1 DO\n BEGIN\n INTEGER R, TMP;\n R\u00a0:= UNIFORM(0, N, SEED); N\u00a0:= N - 1;\n TMP\u00a0:= TILES(R);\n TILES(R)\u00a0:= TILES(N);\n TILES(N)\u00a0:= TMP;\n END;\n B\u00a0:= ISSOLVABLE;\n END;\n INVARIANT;\n END;\n \n PROCEDURE RESET;\n BEGIN\n INTEGER I;\n FOR I\u00a0:= 0 STEP 1 UNTIL NUMTILES DO\n TILES(I)\u00a0:= MOD((I + 1), NUMTILES + 1);\n BLANKPOS\u00a0:= NUMTILES;\n INVARIANT;\n END;\n \n \u00a0! ONLY HALF THE PERMUTATIONS OF THE PUZZLE ARE SOLVABLE.\n \u00a0! WHENEVER A TILE IS PRECEDED BY A TILE WITH HIGHER VALUE IT COUNTS\n \u00a0! AS AN INVERSION. IN OUR CASE, WITH THE BLANK SPACE IN THE HOME\n \u00a0! POSITION, THE NUMBER OF INVERSIONS MUST BE EVEN FOR THE PUZZLE\n \u00a0! TO BE SOLVABLE.\n \u00a0! SEE ALSO:\n \u00a0! WWW.CS.BHAM.AC.UK/~MDR/TEACHING/MODULES04/JAVA2/TILESSOLVABILITY.HTML\n \u00a0;\n\n BOOLEAN PROCEDURE ISSOLVABLE;\n BEGIN\n INTEGER COUNTINVERSIONS;\n INTEGER I, J;\n FOR I\u00a0:= 0 STEP 1 UNTIL NUMTILES - 1 DO\n FOR J\u00a0:= 0 STEP 1 UNTIL I - 1 DO\n IF TILES(J) > TILES(I) THEN\n COUNTINVERSIONS\u00a0:= COUNTINVERSIONS + 1;\n ISSOLVABLE\u00a0:= MOD(COUNTINVERSIONS, 2) = 0;\n END;\n\n PROCEDURE PRINTBOARD;\n BEGIN\n INTEGER I, J;\n\n PROCEDURE PRINTLINE;\n BEGIN\n INTEGER ROW, COL;\n \u00a0! +-----+-----+-----+-----+\u00a0;\n FOR ROW\u00a0:= 1 STEP 1 UNTIL SIDE DO\n BEGIN\n OUTCHAR('+');\n FOR COL\u00a0:= 0 STEP 1 UNTIL WIDTH DO OUTCHAR('-');\n END;\n OUTCHAR('+');\n OUTIMAGE;\n END;\n\n PROCEDURE PRINTCELL(T); INTEGER T;\n BEGIN\n IF T = 0 THEN\n BEGIN\n INTEGER R;\n FOR R\u00a0:= 1 STEP 1 UNTIL WIDTH DO\n OUTCHAR(' ');\n END\n ELSE OUTINT(T, WIDTH);\n OUTCHAR(' ');\n END;\n\n \u00a0! +-----+-----+-----+-----+\n \u00a0! | 1 | 2 | 3 | 4 |\n \u00a0! +-----+-----+-----+-----+\n \u00a0! | 5 | 6 | 7 | 8 |\n \u00a0! +-----+-----+-----+-----+\n \u00a0! | 9 | 10 | 11 | |\n \u00a0! +-----+-----+-----+-----+\n \u00a0! | 13 | 14 | 15 | 12 |\n \u00a0! +-----+-----+-----+-----+ \u00a0;\n\n FOR I\u00a0:= 1 STEP 1 UNTIL SIDE DO\n BEGIN\n PRINTLINE;\n OUTCHAR('|');\n FOR J\u00a0:= 1 STEP 1 UNTIL SIDE DO\n BEGIN\n INTEGER T;\n T\u00a0:= TILES((I - 1) * SIDE + (J - 1));\n PRINTCELL(T);\n OUTCHAR('|');\n END;\n OUTIMAGE;\n END;\n PRINTLINE;\n END;\n\n BOOLEAN PROCEDURE DONE;\n BEGIN\n BOOLEAN ORDERED;\n INTEGER I, EXPECT;\n ORDERED\u00a0:= TRUE;\n EXPECT\u00a0:= 1;\n FOR I\u00a0:= 0 STEP 1 UNTIL NUMTILES - 1 DO\n BEGIN\n IF I <> BLANKPOS THEN\n BEGIN\n IF TILES(I) <> EXPECT THEN\n ORDERED\u00a0:= FALSE;\n EXPECT\u00a0:= EXPECT + 1;\n END;\n END;\n DONE\u00a0:= ORDERED;\n END;\n\n PROCEDURE REQUEST;\n BEGIN\n INTEGER ARRAY CANDIDATES(1:4);\n INTEGER I, CANDCOUNT, CHOOSE;\n BOOLEAN VALIDINPUT;\n\n PROCEDURE ADDCAND(IDX); INTEGER IDX;\n BEGIN\n IF IDX >= 0 AND IDX <= NUMTILES THEN\n BEGIN\n CANDCOUNT\u00a0:= CANDCOUNT + 1;\n CANDIDATES(CANDCOUNT)\u00a0:= TILES(IDX);\n END;\n END;\n\n PRINTBOARD;\n\n IF BLANKPOS <= NUMTILES - SIDE THEN ADDCAND(BLANKPOS + SIDE);\n IF BLANKPOS >= SIDE THEN ADDCAND(BLANKPOS - SIDE);\n IF MOD(BLANKPOS, SIDE) <> SIDE - 1 THEN ADDCAND(BLANKPOS + 1);\n IF MOD(BLANKPOS, SIDE) <> 0 THEN ADDCAND(BLANKPOS - 1);\n\n WHILE NOT VALIDINPUT DO\n BEGIN\n OUTTEXT(\"YOUR MOVE: \");\n\n FOR I\u00a0:= 1 STEP 1 UNTIL CANDCOUNT DO\n OUTINT(CANDIDATES(I), SIDE);\n OUTIMAGE;\n CHOOSE\u00a0:= ININT;\n\n FOR I\u00a0:= 1 STEP 1 UNTIL CANDCOUNT DO\n IF CHOOSE = CANDIDATES(I) THEN\n BEGIN\n INTEGER LOOKUP;\n FOR LOOKUP\u00a0:= 0 STEP 1 UNTIL NUMTILES DO\n IF NOT VALIDINPUT AND TILES(LOOKUP) = CHOOSE THEN\n BEGIN\n TILES(BLANKPOS)\u00a0:= TILES(LOOKUP);\n TILES(LOOKUP)\u00a0:= 0;\n BLANKPOS\u00a0:= LOOKUP;\n INVARIANT;\n VALIDINPUT\u00a0:= TRUE;\n END;\n END;\n\n IF NOT VALIDINPUT THEN\n BEGIN\n OUTTEXT(\"INVALID INPUT!\");\n OUTIMAGE;\n END;\n END;\n END;\n\n SHUFFLE;\n END;\n \n REF(FIFTEENPUZZLE) P;\n\n OUTTEXT(\"INPUT RANDOM SEED: \");\n OUTIMAGE;\n P\u00a0:- NEW FIFTEENPUZZLE(15, 4, 3, ININT);\u00a0! ININT = RANDOM SEED\u00a0;\n WHILE NOT P.DONE DO\n P.REQUEST;\n P.PRINTBOARD;\nEND.", "safe": true }, { "filename": "15 puzzle game_121.txt", "content": "INPUT RANDOM SEED:\n456\n+----+----+----+----+\n| 15 | 8 | 13 | 14 |\n+----+----+----+----+\n| 1 | 2 | 9 | 4 |\n+----+----+----+----+\n| 12 | 3 | 5 | 7 |\n+----+----+----+----+\n| 11 | 6 | 10 | |\n+----+----+----+----+\nYOUR MOVE: 7 10\n7\n+----+----+----+----+\n| 15 | 8 | 13 | 14 |\n+----+----+----+----+\n| 1 | 2 | 9 | 4 |\n+----+----+----+----+\n| 12 | 3 | 5 | |\n+----+----+----+----+\n| 11 | 6 | 10 | 7 |\n+----+----+----+----+\nYOUR MOVE: 7 4 5\n4\n+----+----+----+----+\n| 15 | 8 | 13 | 14 |\n+----+----+----+----+\n| 1 | 2 | 9 | |\n+----+----+----+----+\n| 12 | 3 | 5 | 4 |\n+----+----+----+----+\n| 11 | 6 | 10 | 7 |\n+----+----+----+----+\nYOUR MOVE: 4 14 9\n...\n", "safe": true }, { "filename": "15 puzzle game_122.txt", "content": "(* Load required Modules for Moscow ML *)\nload \"Int\";\nload \"Random\";\n\n\n(* Mutable Matrix *)\nsignature MATRIX =\nsig\n\ttype 'a matrix\n\tval construct : 'a -> int * int -> 'a matrix\n\tval size : 'a matrix -> int * int\n\tval get : 'a matrix -> int * int -> 'a\n\tval set : 'a matrix -> int * int -> 'a -> unit\nend\n\nstructure Matrix :> MATRIX =\nstruct\n\t(* Array of rows, where the rows are a array of 'a *)\n\ttype 'a matrix = 'a Array.array Array.array\n\n\tfun 'a construct (a : 'a) (width, height) : 'a matrix =\n\t\tif width < 1 orelse height < 1\n\t\t\tthen raise Subscript\n\t\t\telse Array.tabulate (height, fn _ => Array.tabulate (width, fn _ => a))\n\t\n\tfun size b =\n\t\tlet\n\t\t\tval firstrow = Array.sub (b, 0)\n\t\tin\n\t\t\t(Array.length firstrow, Array.length b)\n\t\tend\n\n\t\n\tfun get b (x, y) = Array.sub (Array.sub (b, y), x)\n\n\tfun set b (x, y) v = Array.update (Array.sub (b, y), x, v)\nend\n\nsignature P15BOARD =\nsig\n\ttype board\n\tdatatype direction = North | East | South | West\n\n\tval construct : int * int -> board\n\tval emptyField : board -> int * int\n\tval get : board -> int * int -> int option\n\tval size : board -> int * int\n\n\texception IllegalMove\n\tval moves : board -> int list\n\tval move : board -> int -> unit\n\n\tval issolved : board -> bool\nend\n\n(* Game Logic and data *)\n\nstructure Board :> P15BOARD =\nstruct\n\t(* Matrix + empty Field position *)\n\ttype board = int option Matrix.matrix * (int * int) ref\n\t\n\tdatatype direction = North | East | South | West\n\n\texception IllegalMove\n\n\tfun numberat width (x, y) = (y*width + x + 1)\n\n\tfun construct (width, height) =\n\t\tlet\n\t\t\tval emptyBoard : int option Matrix.matrix = Matrix.construct NONE (width, height) \n\t\tin\n\t\t\t(* Fill the board with numbers *)\n\t\t\tList.tabulate (height, fn y => List.tabulate (width, fn x =>\n\t\t\t\t\tMatrix.set emptyBoard (x, y) (SOME (numberat width (x, y)))));\n\t\t\t(* Clear the last field *)\n\t\t\tMatrix.set emptyBoard (width-1, height-1) NONE;\n\t\t\t(* Return the board *)\n\t\t\t(emptyBoard, ref (width-1, height-1))\n\t\tend\n\n\tfun emptyField (_, rfield) = !rfield\n\n\tfun get (mat, _) (x, y) = Matrix.get mat (x, y)\n\n\tfun size (mat, _) = Matrix.size mat\n\n\t(* toggle the empty field with a given field *)\n\tfun toggle (mat, rpos) pos =\n\t\tlet\n\t\t\tval pos' = !rpos\n\t\t\tval value = Matrix.get mat pos\n\t\tin\n\t\t\tMatrix.set mat pos NONE;\n\t\t\tMatrix.set mat pos' value;\n\t\t\trpos := pos\n\t\tend\n\n\t(* Get list of positions of the neighbors of a given field *)\n\tfun neighbors mat (x, y) : (int * int) list =\n\t\tlet\n\t\t\tval (width, height) = Matrix.size mat\n\t\t\tval directions = [(x, y-1), (x+1, y), (x, y+1), (x-1, y)]\n\t\tin\n\t\t\tList.mapPartial (fn pos => SOME (Matrix.get mat pos; pos) handle Subscript => NONE) directions\n\t\tend\n\t\n\tfun moves (mat, rpos) =\n\t\tlet\n\t\t\tval neighbors = neighbors mat (!rpos)\n\t\tin\n\t\t\tmap (fn pos => valOf (Matrix.get mat pos)) neighbors\n\t\tend\n\t\t\n\tfun move (mat, rpos) m =\n\t\tlet\n\t\t\tval (hx, hy) = !rpos\n\t\t\tval neighbors = neighbors mat (hx, hy)\n\t\t\tval optNeighbor = List.find (fn pos => SOME m = Matrix.get mat pos) neighbors\n\t\tin\n\t\t\tif isSome optNeighbor\n\t\t\tthen\n\t\t\t\ttoggle (mat, rpos) (valOf optNeighbor)\n\t\t\telse\n\t\t\t\traise IllegalMove\n\t\tend\n\n\tfun issolved board =\n\t\tlet\n\t\t\tval (width, height) = size board\n\t\t\tval xs = List.tabulate (width, fn x => x)\n\t\t\tval ys = List.tabulate (height, fn y => y)\n\t\tin\n\t\t\tList.all (fn x => List.all (fn y => (x + 1 = width andalso y + 1 = height) orelse get board (x, y) = SOME (numberat width (x,y))) ys) xs\n\t\tend\nend\n\n(* Board Shuffle *)\nsignature BOARDSHUFFLE =\nsig\n\tval shuffle : Board.board -> int -> unit\nend\n\nstructure Shuffle :> BOARDSHUFFLE =\nstruct\n\t(*\n\t * Note: Random Number Interfaces are different in SML/NJ and Moscow ML. Comment out the corresponding version:\n\t *)\n\n\t(*\n\t(* SML/NJ - Version *)\n\tval time = Time.now ()\n\tval timeInf = Time.toMicroseconds time\n\tval timens = Int.fromLarge (LargeInt.mod (timeInf, 1073741823));\n\tval rand = Random.rand (timens, timens)\n\n\tfun next n = Random.randRange (0, n) rand\n\t*)\n\n\t(* Moscow ML - Version *)\n\tval generator = Random.newgen ()\n\tfun next n = Random.range (0, n) generator\n\n\n\tfun shuffle board 0 = if (Board.issolved board) then shuffle board 1 else ()\n\t | shuffle board n =\n\t \tlet\n\t\t\tval moves = Board.moves board\n\t\t\tval move = List.nth (moves, next (List.length moves - 1))\n\t\tin\n\t\t\tBoard.move board move;\n\t\t\tshuffle board (n-1)\n\t\tend\nend\n\n\n(* Console interface *)\n\nsignature CONSOLEINTERFACE =\nsig\n\tval start : unit -> unit\n\tval printBoard : Board.board -> unit\nend\n\nstructure Console :> CONSOLEINTERFACE =\nstruct\n\tfun cls () = print \"\\^[[1;1H\\^[[2J\"\n\n\tfun promptNumber prompt =\n\t\tlet\n\t\t\tval () = print prompt\n\t\t\t(* Input + \"\\n\" *)\n\t\t\tval line = valOf (TextIO.inputLine TextIO.stdIn)\n\t\t\tval length = String.size line\n\t\t\tval input = String.substring (line, 0, length - 1)\n\t\t\tval optnum = Int.fromString input\n\t\tin\n\t\t\tif isSome optnum\n\t\t\t\tthen valOf optnum\n\t\t\t\telse (print \"Input is not a number.\\n\"; promptNumber prompt)\n\t\tend\n\n\tfun fieldToString (SOME x) = Int.toString x\n\t | fieldToString (NONE ) = \"\"\n\n\tfun boardToString board =\n\t\tlet\n\t\t\tval (width, height) = Board.size board\n\t\t\tval xs = List.tabulate (width, fn x => x)\n\t\t\tval ys = List.tabulate (height, fn y => y)\n\t\tin\n\t\t\tfoldl (fn (y, str) => (foldl (fn (x, str') => str' ^ (fieldToString (Board.get board (x, y))) ^ \"\\t\") str xs) ^ \"\\n\") \"\" ys\n\t\tend\n\t\n\tfun printBoard board = print (boardToString board)\n\n\n\tfun loop board =\n\t\tlet\n\t\t\tval rvalidInput = ref false\n\t\t\tval rinput = ref 42\n\t\t\tval () = cls ()\n\t\t\tval () = printBoard board\n\t\tin\n\t\t\t(* Ask for a move and repeat until it is a valid move *)\n\t\t\twhile (not (!rvalidInput)) do\n\t\t\t\t(\n\t\t\t\t\trinput := promptNumber \"Input the number to move: \";\n\t\t\t\t\tBoard.move board (!rinput);\n\t\t\t\t\trvalidInput := true\n\t\t\t\t) handle Board.IllegalMove => print \"Illegal move!\\n\"\n\t\tend\n\n\t\n\tfun start () =\n\t\tlet\n\t\t\tval () = cls ()\n\t\t\tval () = print \"Welcome to nxm-Puzzle!\\n\"\n\t\t\tval (width, height) = (promptNumber \"Enter the width: \", promptNumber \"Enter the height: \")\n\t\t\tval diff = (promptNumber \"Enter the difficulty (number of shuffles): \")\n\t\t\tval board = Board.construct (width, height)\n\t\tin\n\t\t\tShuffle.shuffle board diff;\n\t\t\twhile (not (Board.issolved board)) do loop board;\n\t\t\tprint \"Solved!\\n\"\n\t\tend\nend\n\n\nval () = Console.start()\n", "safe": true }, { "filename": "15 puzzle game_123.txt", "content": " # 15puzzle_21.tcl - HaJo Gurt - 2016-02-16\n # http://wiki.tcl.tk/14403\n\n #: 15-Puzzle - with grid, buttons and colors\n\n package require Tk\n\n set progVersion \"15-Puzzle v0.21\"; # 2016-02-20\n\n global Msg Moves PuzzNr GoalNr\n set Msg \" \"\n set Moves -1\n set PuzzNr 0\n set GoalNr 0\n\n set Keys { 11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 }\n\n set Puzz_T { T h e F i f t e e n P u z z l e }; # Title\n set Goal_T { x x x F i f t e e n x x x x x x }; # Title-highlight\n\n set Puzz_0 { E G P N C A F B D L H I O K M _ }; # - / 116\n set Puzz_1 { C A F B E G P N D L H I O K M _ }; # E / 156 from Tk-demo\n set Puzz_2 { E O N K M I _ G B H L P C F A D }; # L / 139\n set Puzz_3 { P G M _ E L N D O K H I B C F A }; # EK / 146\n\n set Goal_0 { A B C D E F G H I K L M N O P _ }; # Rows LTR / 1:E\u00a0: 108\n set Goal_1 { A E I N B F K O C G L P D H M _ }; # Cols forw. / 1:M\u00a0: 114\n\n set Puzz $Puzz_T\n set Goal $Goal_T\n\n#---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+---\n\n proc Move {k} {\n # find the key with the empty tile:\n set e -1\n foreach p $::Keys {\n set t [.key$p cget -text]\n if { $t eq \"_\" } { set e $p }\n }\n if {$e < 0} {return 0}; # no key with empty tile found\n if {$k == $e} {return 0}; # click was on the empty tile\n\n set t [.key$k cget -text]\n .key$e config -text $t\n .key$k config -text \"_\"; \n return 1\n }\n\n proc Check {} {\n set ok 0\n set i 0\n foreach k $::Keys {\n set t [.key$k cget -text]\n set g [lindex $::Goal $i]\n incr i\n\n .key$k config -background white\n if { $t eq $g } { .key$k config -background lightgreen; incr ok }\n if { $t eq \"_\" } { .key$k config -background gray }\n }\n\n # Solved:\n update\n if { $ok > 15 && $::Moves > 0} {\n foreach k $::Keys {\n .key$k flash; bell;\n }\n }\n }\n\n proc Click {k} {\n set ::Msg \"\"\n set val [.key$k cget -text]\n set ok [Move $k]\n\n incr ::Moves $ok\n wm title . \"$::Moves moves\"\n Check\n }\n\n proc ShowKeys {} {\n set i 0\n foreach k $::Keys {\n set t [lindex $::Puzz $i]\n incr i\n .key$k config -text $t -background white; \n }\n Check\n }\n\n proc NewGame {N} {\n global Msg Moves PuzzNr GoalNr\n\n incr PuzzNr $N\n if { $PuzzNr > 3} { set PuzzNr 0 }\n\n set ::Goal $::Goal_0;\n if { $GoalNr == 1} { set ::Goal $::Goal_1; }\n\n if { $PuzzNr == 0} { set ::Puzz $::Puzz_0; }\n if { $PuzzNr == 1} { set ::Puzz $::Puzz_1; }\n if { $PuzzNr == 2} { set ::Puzz $::Puzz_2; }\n if { $PuzzNr == 3} { set ::Puzz $::Puzz_3; }\n\n set Msg \"Try again\"\n if { $N>0 } { set Msg \"New game\" }\n\n set Moves 0\n ShowKeys\n wm title . \"$Msg \"\n }\n\n#---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+---\n\n button .reset -text \"Restart\" -fg blue -command {NewGame 0}\n button .newGame -text \"New Game\" -fg red -command {NewGame +1}\n\n foreach k $::Keys {\n button .key$k -text \"$k\" -width 4 -command \"Click $k\"\n }\n\n grid .newGame x .reset x -sticky nsew\n\n grid .key11 .key12 .key13 .key14 -sticky nsew -padx 2 -pady 2\n grid .key21 .key22 .key23 .key24 -sticky nsew -padx 2 -pady 2\n grid .key31 .key32 .key33 .key34 -sticky nsew -padx 2 -pady 2\n grid .key41 .key42 .key43 .key44 -sticky nsew -padx 2 -pady 2\n\n grid configure .newGame .reset -columnspan 2 -padx 4\n\n ShowKeys; Check\n wm title . $progVersion\n focus -force .\n wm resizable . 0 0\n\n# For some more versions, see: http://wiki.tcl.tk/15067\u00a0: Classic 15 Puzzle and http://wiki.tcl.tk/15085\u00a0: N-Puzzle\n", "safe": true }, { "filename": "15 puzzle game_124.txt", "content": "#!/usr/bin/env bash\nmain() {\n local puzzle=({1..15} \" \") blank moves_kv i key count total last\n printf '\\n'\n show_puzzle \"${puzzle[@]}\"\n printf '\\nPress return to scramble.'\n read _\n IFS= readarray -t puzzle < <(scramble \"${puzzle[@]}\")\n printf '\\r\\e[A\\e[A\\e[A\\e[A\\e[A\\e[A'\n show_puzzle \"${puzzle[@]}\"\n printf '\\nUse hjkl to slide tiles. '\n printf '\\r\\e[A\\e[A\\e[A\\e[A\\e[A'\n total=0\n while ! solved \"${puzzle[@]}\"; do\n show_puzzle \"${puzzle[@]}\"\n { read blank; readarray -t moves_kv; } < <(find_moves \"${puzzle[@]}\")\n local count=${#moves_kv[@]}/2\n local -A moves\n for (( i=0; i= 4 )); then\n moves['j']=$(( blank-4 )) # down\n fi\n if (( blank < 12 )); then\n moves['k']=$(( blank+4 )) # up\n fi\n printf '%s\\n' \"$blank\" \"${!moves[@]}\" \"${moves[@]}\" \n}\n\nscramble() {\n local puzzle=(\"$@\") i j \n for (( i=0; i<256; ++i )); do\n local blank moves\n { read blank; readarray -t moves; } < <(find_moves \"${puzzle[@]}\")\n moves=(${moves[@]:${#moves[@]}/2})\n local dir=$(( RANDOM % ${#moves[@]} ))\n j=${moves[dir]}\n puzzle[blank]=${puzzle[j]}\n puzzle[j]=' '\n done\n printf '%s\\n' \"${puzzle[@]}\"\n}\n\nmain \"$@\"\n", "safe": true }, { "filename": "15 puzzle game_125.txt", "content": " 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 \n\nPress return to scramble.\n", "safe": true }, { "filename": "15 puzzle game_126.txt", "content": "Public iSide As Integer\nPublic iSize As Integer\nPublic iGrid() As Integer\nPublic lMoves As Long\nPublic sMessage As String\nPublic Const sTitle As String = \"Tile Puzzle\"\n\n\nSub PlayGame()\n Dim iNum As Integer\n Dim i As Integer\n Dim vInput As Variant\n\nDefineGrid:\n vInput = InputBox(\"Enter size of grid, as a whole number\" & String(2, vbCr) & \"(e.g. for a 4 x 4 grid, enter '4')\", sTitle, 4)\n If vInput = \"\" Then Exit Sub\n If Not IsNumeric(vInput) Then GoTo DefineGrid\n iSide = vInput\n If iSide < 3 Or iNum > 10 Then GoTo DefineGrid\n iSize = iSide ^ 2\n ReDim iGrid(1 To iSize)\n \nInitalize:\n InitializeGrid\n If Not IsSolvable Then GoTo Initalize\n \nGetInput:\n vInput = InputBox(ShowGrid & vbCr & \"Enter number to move into empty tile\", sTitle)\n If vInput = \"\" Then\n If MsgBox(\"Are you sure? This will end the current game.\", vbExclamation + vbYesNo, sTitle) = vbYes Then Exit Sub\n End If\n If Not IsNumeric(vInput) Then\n sMessage = \"'\" & vInput & \"' is not a valid tile\"\n GoTo GetInput\n End If\n iNum = vInput\n If iNum < 1 Or iNum > iSize - 1 Then\n sMessage = iNum & \" is not a valid tile\"\n GoTo GetInput\n End If\n i = FindTile(iNum)\n If Not ValidMove(i) Then GoTo GetInput\n MoveTile (i)\n If TestGrid Then\n MsgBox \"SUCCESS! You solved the puzzle in \" & lMoves & \" moves\", vbInformation + vbOKOnly, sTitle\n Else\n GoTo GetInput\n End If\nEnd Sub\n\nFunction RandomTile() As Integer\n Randomize\n RandomTile = Int(Rnd * iSize) + 1\nEnd Function\n\nFunction GetX(ByVal i As Integer) As Integer\n GetX = Int((i - 1) / iSide) + 1\nEnd Function\n\nFunction GetY(ByVal i As Integer) As Integer\n GetY = (i - 1) Mod iSide + 1\nEnd Function\n\nFunction GetI(ByVal x As Integer, y As Integer)\n GetI = (x - 1) * iSide + y\nEnd Function\n\nFunction InitializeGrid()\n Dim i As Integer\n Dim x As Integer\n Dim y As Integer\n \n sMessage = \"New \" & iSide & \" x \" & iSide & \" game started\" & vbCr\n \n For i = 1 To iSize\n iGrid(i) = 0\n Next i\n For i = 1 To iSize - 1\n Do\n x = RandomTile\n If iGrid(x) = 0 Then iGrid(x) = i\n Loop Until iGrid(x) = i\n Next i\n lMoves = 0\nEnd Function\n\nFunction IsSolvable() As Boolean\n Dim i As Integer\n Dim j As Integer\n Dim iCount As Integer\n For i = 1 To iSize - 1\n For j = i + 1 To iSize\n If iGrid(j) < iGrid(i) And iGrid(j) > 0 Then iCount = iCount + 1\n Next j\n Next i\n If iSide Mod 2 Then\n IsSolvable = Not iCount Mod 2\n Else\n IsSolvable = iCount Mod 2 = GetX(FindTile(0)) Mod 2\n End If\nEnd Function\n\nFunction TestGrid() As Boolean\n Dim i As Integer\n \n For i = 1 To iSize - 1\n If Not iGrid(i) = i Then\n TestGrid = False\n Exit Function\n End If\n Next i\n TestGrid = True\nEnd Function\n\nFunction FindTile(ByVal iNum As Integer) As Integer\n Dim i As Integer\n For i = 1 To iSize\n If iGrid(i) = iNum Then\n FindTile = i\n Exit Function\n End If\n Next i\nEnd Function\n\nFunction ValidMove(ByVal i As Integer) As Boolean\n Dim e As Integer\n Dim xDiff As Integer\n Dim yDiff As Integer\n \n e = FindTile(0)\n xDiff = GetX(i) - GetX(e)\n yDiff = GetY(i) - GetY(e)\n If xDiff = 0 Then\n If yDiff = 1 Then\n sMessage = \"Tile \" & iGrid(i) & \" was moved left\"\n ValidMove = True\n ElseIf yDiff = -1 Then\n sMessage = \"Tile \" & iGrid(i) & \" was moved right\"\n ValidMove = True\n End If\n ElseIf yDiff = 0 Then\n If xDiff = 1 Then\n sMessage = \"Tile \" & iGrid(i) & \" was moved up\"\n ValidMove = True\n ElseIf xDiff = -1 Then\n sMessage = \"Tile \" & iGrid(i) & \" was moved down\"\n ValidMove = True\n End If\n End If\n If Not ValidMove Then sMessage = \"Tile \" & iGrid(i) & \" may not be moved\"\nEnd Function\n\nFunction MoveTile(ByVal i As Integer)\n Dim e As Integer\n e = FindTile(0)\n iGrid(e) = iGrid(i)\n iGrid(i) = 0\n lMoves = lMoves + 1\nEnd Function\n\nFunction ShowGrid()\n Dim x As Integer\n Dim y As Integer\n Dim i As Integer\n Dim sNum As String\n Dim s As String\n \n For x = 1 To iSide\n For y = 1 To iSide\n sNum = iGrid(GetI(x, y))\n If sNum = \"0\" Then sNum = \"\"\n s = s & sNum & vbTab\n Next y\n s = s & vbCr\n Next x\n If Not sMessage = \"\" Then\n s = s & vbCr & sMessage & vbCr\n End If\n ShowGrid = s\nEnd Function\n", "safe": true }, { "filename": "15 puzzle game_127.txt", "content": "10 4 3 14 \n9 15 1 6 \n12 11 7 8 \n2 5 13 \n\nNew 4 x 4 game started\n\nEnter number to move into empty tile\n", "safe": true }, { "filename": "15 puzzle game_128.txt", "content": "Public Class Board\n Inherits System.Windows.Forms.Form\n\n Const XbyX = 4\n Const XSize = 60\n\n Private Empty As New Panel\n Private Tiles As New List(Of Tile)\n Private Moves As Integer\n\n Public Sub New()\n Me.Text = XbyX ^ 2 - 1 & \" Puzzle Game\"\n Me.ClientSize = New Size(XbyX * XSize, XbyX * XSize)\n Me.FormBorderStyle = FormBorderStyle.FixedToolWindow\n Restart()\n End Sub\n\n Public Sub Restart()\n Dim Start As List(Of Integer) = MakeCompleteable(GetRandamStartOrder())\n\n Empty.SetBounds(((XbyX ^ 2 - 1) Mod XbyX) * XSize, ((XbyX ^ 2 - 1) \\ XbyX) * XSize, XSize, XSize)\n\n Me.Moves = 0\n Me.Tiles.Clear()\n Me.Controls.Clear()\n For No = 0 To XbyX ^ 2 - 2\n Dim Tile As New Tile\n Tile.Text = Start(No)\n Tile.Board = Me\n Tile.SetBounds((No Mod XbyX) * XSize, (No \\ XbyX) * XSize, XSize, XSize)\n Me.Tiles.Add(Tile)\n Me.Controls.Add(Tile)\n Next\n\n End Sub\n\n Public Sub IsComplete()\n Me.Moves += 1\n If Empty.Left = ((XbyX ^ 2 - 1) Mod XbyX) * XSize AndAlso Empty.Top = ((XbyX ^ 2 - 1) \\ XbyX) * XSize Then\n Me.Tiles.Sort()\n For x = 1 To XbyX ^ 2 - 1\n If Not Tiles(x - 1).Text = x Then\n Exit Sub\n End If\n Next\n MsgBox($\"Completed in {Me.Moves} Moves!\", MsgBoxStyle.Information, \"Winner\")\n Restart()\n End If\n End Sub\n\n Public Class Tile\n Inherits Button\n Implements IComparable(Of Tile)\n Public Board As Board\n Private Sub Tile_Click(sender As Object, e As EventArgs) Handles Me.Click\n With Board.Empty\n If Me.Left = .Left AndAlso (Me.Top + Me.Height = .Top OrElse .Top + .Height = Me.Top) Then\n Swap()\n ElseIf Me.Top = .Top AndAlso (Me.Left + Me.Width = .Left OrElse .Left + .Width = Me.Left) Then\n Swap()\n End If\n End With\n End Sub\n Private Sub Swap()\n Dim p = Board.Empty.Location\n Board.Empty.Location = Me.Location\n Me.Location = p\n Board.IsComplete()\n End Sub\n Public Function CompareTo(other As Tile) As Integer Implements IComparable(Of Tile).CompareTo\n Dim Result = Me.Top.CompareTo(other.Top)\n If Result = 0 Then\n Return Me.Left.CompareTo(other.Left)\n End If\n Return Result\n End Function\n End Class\n\n Public Function GetRandamStartOrder() As List(Of Integer)\n Dim List As New List(Of Integer)\n Dim Random As New Random()\n Do While List.Count < XbyX ^ 2 - 1\n Dim Value As Integer = Random.Next(1, XbyX ^ 2)\n If Not List.Contains(Value) Then\n List.Add(Value)\n End If\n Loop\n Return List\n End Function\n\n Public Function MakeCompleteable(List As List(Of Integer)) As List(Of Integer)\n 'ToDo\n Return List\n End Function\n\nEnd Class\n", "safe": true }, { "filename": "15 puzzle game_129.txt", "content": "/* ------------------------------------------------------------------------------------------------------\n\n Copyright (c) 2004 - Gal Zsolt (CalmoSoft)\n\n ------------------------------------------------------------------------------------------------------ */\n\nimplement playDialog\n open core, vpiDomains, vpiOldDomains, resourceIdentifiers\n\n facts\n thisWin\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n\n clauses\n show(Parent):-\n _ = vpi::winCreateDynDialog(Parent, controlList, eventHandler, gui_api::lNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n eventHandler\u00a0: vpiDomains::ehandler.\n clauses\n eventHandler(Win, Event) = Result\u00a0:-\n Result = generatedEventHandler(Win, Event).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n\n predicates\n onDestroy\u00a0: vpiOldDomains::destroyHandler.\n clauses\n onDestroy() = vpiOldDomains::defaultHandling()\u00a0:-\n thisWin\u00a0:= erroneous.\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlCancel\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlCancel(_Ctrl, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull)\u00a0:-\n file::save(\"game.dba\",gameDB),\n retractall(table(_,_)),\n retractall(gameplay(_,_)),\n retractall(empty_cell(_)),\n retractall(cell(_,_)),\n retractall(cellnr(_,_)),\n retractall(good(_,_,_)),\n vpi::winDestroy(thisWin).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onUpdate\u00a0: vpiOldDomains::updateHandler.\n clauses\n onUpdate(Rectangle) = vpiOldDomains::defaultHandling():-\n vpi::winClear( thisWin,Rectangle,0x808040),\n \u00a0!.\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n class facts - gameDB\n table:(integer,string).\n gameplay:(integer,integer).\n empty_cell:(integer).\n\n class facts\n cell:(integer,vpiDomains::windowHandle).\n cellnr:(integer,integer).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n class facts\n step_nr:integer:=0.\n\n predicates\n onCreate\u00a0: vpiOldDomains::createHandler.\n clauses\n onCreate(_CreationData) = vpiOldDomains::defaultHandling():-\n retractall(table(_,_)),\n retractall(gameplay(_,_)),\n retractall(empty_cell(_)),\n retractall(cell(_,_)),\n retractall(cellnr(_,_)),\n retractall(good(_,_,_)),\n\n scrollbars_init(),\n cellhandle_init(),\n empty:=16,\n good_cell(0),\n table_save(),\n step_nr:=0,\n fail.\n onCreate(_CreationData) = vpiOldDomains::defaultHandling().\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n facts\n vsbarr\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n vsbarl\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n hsbart\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n hsbarb\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n\n predicates\n scrollbars_init:().\n clauses\n scrollbars_init():-\n vsbarr\u00a0:= vpi::winGetCtlHandle(thisWin,idc_sbvr),\n vsbarl\u00a0:= vpi::winGetCtlHandle(thisWin,idc_sbvl),\n hsbart\u00a0:= vpi::winGetCtlHandle(thisWin,idc_sbht),\n hsbarb\u00a0:= vpi::winGetCtlHandle(thisWin,idc_sbhb),\n\n\n vpi::winSetScrollRange(vsbarr,sb_Ctl,1,4),\n vpi::winSetScrollProportion(vsbarr,sb_Ctl,1),\n vpi::winSetScrollPos(vsbarr,sb_Ctl,4),\n\n vpi::winSetScrollRange(vsbarl,sb_Ctl,1,4),\n vpi::winSetScrollProportion(vsbarl,sb_Ctl,1),\n vpi::winSetScrollPos(vsbarl,sb_Ctl,4),\n\n vpi::winSetScrollRange(hsbart,sb_Ctl,1,4),\n vpi::winSetScrollProportion(hsbart,sb_Ctl,1),\n vpi::winSetScrollPos(hsbart,sb_Ctl,4),\n\n vpi::winSetScrollRange(hsbarb,sb_Ctl,1,4),\n vpi::winSetScrollProportion(hsbarb,sb_Ctl,1),\n vpi::winSetScrollPos(hsbarb,sb_Ctl,4).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n class facts\n cell1\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell2\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell3\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell4\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell5\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell6\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell7\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell8\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell9\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell10\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell11\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell12\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell13\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell14\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell15\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n cell16\u00a0: vpiDomains::windowHandle\u00a0:= erroneous.\n\n predicates\n cell_handle:().\n clauses\n cell_handle():-\n cell1:=vpi::winGetCtlHandle(thisWin,idc_cell1),\n cell2:=vpi::winGetCtlHandle(thisWin,idc_cell2),\n cell3:=vpi::winGetCtlHandle(thisWin,idc_cell3),\n cell4:=vpi::winGetCtlHandle(thisWin,idc_cell4),\n cell5:=vpi::winGetCtlHandle(thisWin,idc_cell5),\n cell6:=vpi::winGetCtlHandle(thisWin,idc_cell6),\n cell7:=vpi::winGetCtlHandle(thisWin,idc_cell7),\n cell8:=vpi::winGetCtlHandle(thisWin,idc_cell8),\n cell9:=vpi::winGetCtlHandle(thisWin,idc_cell9),\n cell10:=vpi::winGetCtlHandle(thisWin,idc_cell10),\n cell11:=vpi::winGetCtlHandle(thisWin,idc_cell11),\n cell12:=vpi::winGetCtlHandle(thisWin,idc_cell12),\n cell13:=vpi::winGetCtlHandle(thisWin,idc_cell13),\n cell14:=vpi::winGetCtlHandle(thisWin,idc_cell14),\n cell15:=vpi::winGetCtlHandle(thisWin,idc_cell15),\n cell16:=vpi::winGetCtlHandle(thisWin,idc_cell16).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n cellhandle_init:().\n clauses\n cellhandle_init():-\n retractall(cell(_,_)),\n cell_handle(),\n\n assert(cell(1,cell1)),\n assert(cell(2,cell2)),\n assert(cell(3,cell3)),\n assert(cell(4,cell4)),\n assert(cell(5,cell5)),\n assert(cell(6,cell6)),\n assert(cell(7,cell7)),\n assert(cell(8,cell8)),\n assert(cell(9,cell9)),\n assert(cell(10,cell10)),\n assert(cell(11,cell11)),\n assert(cell(12,cell12)),\n assert(cell(13,cell13)),\n assert(cell(14,cell14)),\n assert(cell(15,cell15)),\n assert(cell(16,cell16)).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n class facts\n good_nr:integer:=0.\n good:(integer,integer,integer) nondeterm.\n empty:integer:=16.\n\n predicates\n good_cell:(integer) multi.\n clauses\n good_cell(16):-!.\n good_cell(Number):-\n NumberNew = Number+1,\n good_nr:=0,\n good_above(NumberNew), \u00a0% movable cells above empty cell\n good_before(NumberNew), \u00a0% movable cells before empty cell\n good_after(NumberNew), \u00a0% movable cells after empty cell\n good_under(NumberNew), \u00a0% movable cells under empty cell\n assert(cellnr(NumberNew,good_nr)), \u00a0% number of movable cells around the empty cell\n good_cell(NumberNew).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n good_above:(integer).\n clauses\n good_above(Number):-\n Number > 4, \u00a0% movable cells above empty cell\n good_nr:= good_nr+1,\n assert(good(Number,good_nr,Number-4)),\n fail.\n good_above(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n good_before:(integer).\n clauses\n good_before(Number):-\n (Number mod 4) <> 1, \u00a0% movable cells before empty cell\n good_nr:= good_nr+1,\n assert(good(Number,good_nr,Number-1)),\n fail.\n good_before(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n good_after:(integer).\n clauses\n good_after(Number):-\n (Number mod 4) > 0, \u00a0% movable cells after empty cell\n good_nr:= good_nr+1,\n assert(good(Number,good_nr,Number+1)),\n fail.\n good_after(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n good_under:(integer).\n clauses\n good_under(Number):-\n Number < 13, \u00a0% movable cells under empty cell\n good_nr:= good_nr+1,\n assert(good(Number,good_nr,Number+4)),\n fail.\n good_under(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n cell_click:(integer).\n\n clauses\n cell_click(NrCell):-\n good(empty,_,NrCell),\n cell(empty,EmptyHandle),\n cell(NrCell,NrCellHandle),\n EmptyNr = vpi::winGetText(NrCellHandle),\n vpi::winSetText(EmptyHandle,EmptyNr),\n vpi::winSetText(NrCellHandle,\"\"),\n empty:=NrCell,\n step_nr\u00a0:= step_nr + 1,\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetText( Bingo, \"\"),\n vpi::winSetState(Bingo,[wsf_Invisible]),\n bingo(),\n\n \u00a0% VerVal = uncheckedConvert(integer, math::floor((empty-1)/4)+1),\n \u00a0% HorVal = uncheckedConvert(integer, math::floor((empty-1) mod 4)+1),\n\n VerVal = math::floor((empty-1)/4)+1,\n HorVal = math::floor((empty-1) mod 4)+1,\n\n vpi::winSetScrollPos(vsbarr,sb_Ctl,VerVal),\n vpi::winSetScrollPos(vsbarl,sb_Ctl,VerVal),\n vpi::winSetScrollPos(hsbart,sb_Ctl,HorVal),\n vpi::winSetScrollPos(hsbarb,sb_Ctl,HorVal),\n\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(step_nr)),\n\n assert(gameplay(step_nr,NrCell)),\n\n fail.\n cell_click(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n cell_click_play:(integer).\n\n clauses\n cell_click_play(NrCell):-\n good(empty,_,NrCell),\n cell(empty,EmptyHandle),\n cell(NrCell,NrCellHandle),\n EmptyNr = vpi::winGetText(NrCellHandle),\n vpi::winSetText(EmptyHandle,EmptyNr),\n vpi::winSetText(NrCellHandle,\"\"),\n empty:=NrCell,\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetText(Bingo, \"\"),\n vpi::winSetState(Bingo,[wsf_Invisible]),\n bingo(),\n\n \u00a0% VerVal = uncheckedConvert(integer,math::floor((empty-1)/4)+1),\n \u00a0% HorVal = uncheckedConvert(integer,math::floor((empty-1) mod 4)+1),\n\n VerVal = math::floor((empty-1)/4)+1,\n HorVal = math::floor((empty-1) mod 4)+1,\n\n vpi::winSetScrollPos(vsbarr,sb_Ctl,VerVal),\n vpi::winSetScrollPos(vsbarl,sb_Ctl,VerVal),\n vpi::winSetScrollPos(hsbart,sb_Ctl,HorVal),\n vpi::winSetScrollPos(hsbarb,sb_Ctl,HorVal),\n\n programControl::sleep(1000),\n\n fail.\n cell_click_play(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlmix\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlmix(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n step_nr:=0,\n cell_reset(),\n mix_cells(0),\n Play = vpi::winGetCtlHandle(thisWin,idc_play),\n vpi::winSetState(Play,[wsf_Disabled]),\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetText(Bingo, \"\"),\n vpi::winSetState(Bingo,[wsf_Invisible]),\n step_nr:=0,\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(step_nr)),\n table_save(),\n retractall(gameplay(_,_)),\n fail.\n\n onControlmix(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n class facts\n rand_nr:integer:=0.\n mix_nr:integer:=300.\n\n predicates\n mix_cells:(integer) multi.\n\n clauses\n mix_cells(mix_nr):-!.\n mix_cells(Number):-\n NumberNew = Number+1,\n cellnr(empty,CellNr),\n RandomNr = (math::random(1315) mod CellNr) + 1,\n rand_nr\u00a0:= RandomNr,\n good(empty,rand_nr, I),\n cell_click(I),\n mix_cells(NumberNew).\n mix_cells(_).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n table_save:().\n clauses\n table_save():-\n retractall(table(_,_)),\n retractall(empty_cell(_)),\n assert(empty_cell(empty)),\n\n assert(table(1,vpi::winGetText(cell1))),\n assert(table(2,vpi::winGetText(cell2))),\n assert(table(3,vpi::winGetText(cell3))),\n assert(table(4,vpi::winGetText(cell4))),\n assert(table(5,vpi::winGetText(cell5))),\n assert(table(6,vpi::winGetText(cell6))),\n assert(table(7,vpi::winGetText(cell7))),\n assert(table(8,vpi::winGetText(cell8))),\n assert(table(9,vpi::winGetText(cell9))),\n assert(table(10,vpi::winGetText(cell10))),\n assert(table(11,vpi::winGetText(cell11))),\n assert(table(12,vpi::winGetText(cell12))),\n assert(table(13,vpi::winGetText(cell13))),\n assert(table(14,vpi::winGetText(cell14))),\n assert(table(15,vpi::winGetText(cell15))),\n assert(table(16,vpi::winGetText(cell16))).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlreset\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlreset(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_reset().\n\n/* ------------------------------------------------------------------------------------------------------ */\n predicates\n cell_reset:().\n clauses\n cell_reset():-\n vpi::winSetText(cell1,\"1\"),\n vpi::winSetText(cell2,\"2\"),\n vpi::winSetText(cell3,\"3\"),\n vpi::winSetText(cell4,\"4\"),\n vpi::winSetText(cell5,\"5\"),\n vpi::winSetText(cell6,\"6\"),\n vpi::winSetText(cell7,\"7\"),\n vpi::winSetText(cell8,\"8\"),\n vpi::winSetText(cell9,\"9\"),\n vpi::winSetText(cell10,\"10\"),\n vpi::winSetText(cell11,\"11\"),\n vpi::winSetText(cell12,\"12\"),\n vpi::winSetText(cell13,\"13\"),\n vpi::winSetText(cell14,\"14\"),\n vpi::winSetText(cell15,\"15\"),\n vpi::winSetText(cell16,\"\"),\n\n vpi::winSetScrollPos(vsbarr,sb_Ctl,4),\n vpi::winSetScrollPos(vsbarl,sb_Ctl,4),\n vpi::winSetScrollPos(hsbart,sb_Ctl,4),\n vpi::winSetScrollPos(hsbarb,sb_Ctl,4),\n\n empty:=16,\n step_nr:=0,\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(step_nr)),\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetText(Bingo, \"\"),\n vpi::winSetState(Bingo,[wsf_Invisible]),\n Play = vpi::winGetCtlHandle(thisWin,idc_play),\n vpi::winSetState(Play,[wsf_Disabled]),\n retractall(gameplay(_,_)),\n table_save().\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n bingo:().\n\n clauses\n bingo():-\n toString(1) = vpi::winGetText(cell1),\n toString(2) = vpi::winGetText(cell2),\n toString(3) = vpi::winGetText(cell3),\n toString(4) = vpi::winGetText(cell4),\n toString(5) = vpi::winGetText(cell5),\n toString(6) = vpi::winGetText(cell6),\n toString(7) = vpi::winGetText(cell7),\n toString(8) = vpi::winGetText(cell8),\n toString(9) = vpi::winGetText(cell9),\n toString(10) = vpi::winGetText(cell10),\n toString(11) = vpi::winGetText(cell11),\n toString(12) = vpi::winGetText(cell12),\n toString(13) = vpi::winGetText(cell13),\n toString(14) = vpi::winGetText(cell14),\n toString(15) = vpi::winGetText(cell15),\n \"\" = vpi::winGetText(cell16),\n\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetState(Bingo,[wsf_Visible]),\n vpi::winSetText(Bingo, \"BINGO\u00a0!\"),\n\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(step_nr)),\n\n fail.\n bingo().\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n facts\n fileName:string:=\"\".\n\n predicates\n onControlsave\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlsave(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n try\n \tFileName = vpiCommonDialogs::getFileName(fileName, [\"All files\", \"*.game\"], \"Save game as\", [dlgfn_Save], \"\", _)\n catch _ do\n \tfail\n end try,\n \u00a0!,\n file::save(FileName,gameDB).\n\n onControlsave(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo)= vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlopen\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlopen(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n try\n \tFileName = vpiCommonDialogs::getFileName(\"game_\", [\"All files\", \"*.game\"], \"Open game file\", [], \"\", _)\n catch _ do\n \tfail\n end try,\n \u00a0!,\n retractall(table(_,_)),\n retractall(gameplay(_,_)),\n retractall(empty_cell(_)),\n file::consult(FileName,gameDB),\n play_display(),\n Play = vpi::winGetCtlHandle(thisWin,idc_play),\n vpi::winSetState(Play,[wsf_Enabled]),\n Bingo = vpi::winGetCtlHandle(thisWin,idc_bingo),\n vpi::winSetState(Bingo,[wsf_Invisible]),\n vpi::winSetText(Bingo, \"\"),\n step_nr:=0,\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(step_nr)).\n\n onControlopen(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n play_display:().\n clauses\n play_display():-\n\n table(1,Cell1),\n table(2,Cell2),\n table(3,Cell3),\n table(4,Cell4),\n table(5,Cell5),\n table(6,Cell6),\n table(7,Cell7),\n table(8,Cell8),\n table(9,Cell9),\n table(10,Cell10),\n table(11,Cell11),\n table(12,Cell12),\n table(13,Cell13),\n table(14,Cell14),\n table(15,Cell15),\n table(16,Cell16),\n\n vpi::winSetText(cell1,Cell1),\n vpi::winSetText(cell2,Cell2),\n vpi::winSetText(cell3,Cell3),\n vpi::winSetText(cell4,Cell4),\n vpi::winSetText(cell5,Cell5),\n vpi::winSetText(cell6,Cell6),\n vpi::winSetText(cell7,Cell7),\n vpi::winSetText(cell8,Cell8),\n vpi::winSetText(cell9,Cell9),\n vpi::winSetText(cell10,Cell10),\n vpi::winSetText(cell11,Cell11),\n vpi::winSetText(cell12,Cell12),\n vpi::winSetText(cell13,Cell13),\n vpi::winSetText(cell14,Cell14),\n vpi::winSetText(cell15,Cell15),\n vpi::winSetText(cell16,Cell16),\n\n empty_cell(Empty_Cell),\n empty:=Empty_Cell,\n\n fail.\n play_display().\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlplay\u00a0: vpiOldDomains::controlHandler.\n clauses\n\n onControlplay(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n Play = vpi::winGetCtlHandle(thisWin,idc_play),\n vpi::winSetState(Play,[wsf_Disabled]),\n gameplay(Nr,Nr_cell),\n cell_click_play(Nr_cell),\n Step = vpi::winGetCtlHandle(thisWin,idc_step),\n vpi::winSetText(Step,toString(Nr)),\n fail.\n\n onControlplay(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlsbvr\u00a0: vpiOldDomains::controlHandler. \u00a0% Sets the right vertical scrollbar\n clauses\n onControlsbvr(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineDown,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalr = vpi::winGetScrollPos(vsbarr,sb_Ctl)+1,\n Sbarvalr < 5,\n cell_click(empty+4),\n vpi::winSetScrollPos(vsbarr,sb_Ctl, Sbarvalr),\n vpi::winSetScrollPos(vsbarl,sb_Ctl, Sbarvalr),\n fail.\n\n onControlsbvr(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineUp,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalr = vpi::winGetScrollPos(vsbarr,sb_Ctl)-1,\n Sbarvalr > 0,\n cell_click(empty-4),\n vpi::winSetScrollPos(vsbarr,sb_Ctl, Sbarvalr),\n vpi::winSetScrollPos(vsbarl,sb_Ctl, Sbarvalr),\n fail.\n\n onControlsbvr(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlsbvl\u00a0: vpiOldDomains::controlHandler. \u00a0% Sets the left vertical scrollbar\n clauses\n onControlsbvl(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineDown,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvall = vpi::winGetScrollPos(vsbarl,sb_Ctl)+1,\n Sbarvall < 5,\n cell_click(empty+4),\n vpi::winSetScrollPos(vsbarl,sb_Ctl, Sbarvall),\n vpi::winSetScrollPos(vsbarr,sb_Ctl, Sbarvall),\n fail.\n\n onControlsbvl(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineUp,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvall = vpi::winGetScrollPos(vsbarl,sb_Ctl)-1,\n Sbarvall > 0,\n cell_click(empty-4),\n vpi::winSetScrollPos(vsbarl,sb_Ctl, Sbarvall),\n vpi::winSetScrollPos(vsbarr,sb_Ctl, Sbarvall),\n fail.\n\n onControlsbvl(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlsbht\u00a0: vpiOldDomains::controlHandler. \u00a0% Sets the top horizontal scrollbar\n clauses\n onControlsbht(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineDown,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalt = vpi::winGetScrollPos(hsbart,sb_Ctl)+1,\n Sbarvalt < 5,\n cell_click(empty+1),\n vpi::winSetScrollPos(hsbart,sb_Ctl, Sbarvalt),\n vpi::winSetScrollPos(hsbarb,sb_Ctl, Sbarvalt),\n fail.\n\n onControlsbht(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineUp,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalt = vpi::winGetScrollPos(hsbart,sb_Ctl)-1,\n Sbarvalt > 0,\n cell_click(empty-1),\n vpi::winSetScrollPos(hsbart,sb_Ctl, Sbarvalt),\n vpi::winSetScrollPos(hsbarb,sb_Ctl, Sbarvalt),\n fail.\n\n onControlsbht(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlsbhb\u00a0: vpiOldDomains::controlHandler. \u00a0% Sets the bottom horizontal scrollbar\n clauses\n onControlsbhb(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineDown,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalb = vpi::winGetScrollPos(hsbarb,sb_Ctl)+1,\n Sbarvalb < 5,\n cell_click(empty+1),\n vpi::winSetScrollPos(hsbarb,sb_Ctl, Sbarvalb),\n vpi::winSetScrollPos(hsbart,sb_Ctl, Sbarvalb),\n fail.\n\n onControlsbhb(_CtrlID, _CtrlType, _CtrlWin,scroll(sc_LineUp,_)) = vpiOldDomains::handled(gui_api::rNull):-\n Sbarvalb = vpi::winGetScrollPos(hsbarb,sb_Ctl)-1,\n Sbarvalb > 0,\n cell_click(empty-1),\n vpi::winSetScrollPos(hsbarb,sb_Ctl, Sbarvalb),\n vpi::winSetScrollPos(hsbart,sb_Ctl, Sbarvalb),\n fail.\n\n onControlsbhb(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell1\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell1(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(1).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n\n predicates\n onControlcell2\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell2(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(2).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell3\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell3(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(3).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell4\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell4(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(4).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell5\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell5(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(5).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell6\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell6(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(6).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell7\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell7(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(7).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell8\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell8(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(8).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell9\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell9(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(9).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell10\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell10(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(10).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell11\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell11(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(11).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell12\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell12(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(12).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell13\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell13(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(13).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell14\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell14(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(14).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell15\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell15(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(15).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n predicates\n onControlcell16\u00a0: vpiOldDomains::controlHandler.\n clauses\n onControlcell16(_CtrlID, _CtrlType, _CtrlWin, _CtrlInfo) = vpiOldDomains::handled(gui_api::rNull):-\n cell_click(16).\n\n/* ------------------------------------------------------------------------------------------------------ */\n\n \u00a0% This code is maintained by the VDE do not update it manually, 22:12:35-14.3.2004\n constants\n dialogType\u00a0: vpiDomains::wintype = wd_Modal.\n title\u00a0: string = \"playDialog\".\n rectangle\u00a0: vpiDomains::rct = rct(200,40,359,263).\n dialogFlags\u00a0: vpiDomains::wsflags = [wsf_Close,wsf_TitleBar].\n dialogFont = \"MS Sans Serif\".\n dialogFontSize = 8.\n\n constants\n controlList\u00a0: vpiDomains::windef_list =\n [\n dlgFont(wdef(dialogType, rectangle, title, u_DlgBase),\n dialogFont, dialogFontSize, dialogFlags),\n ctl(wdef(wc_PushButton,rct(40,166,67,178),\"&Mix\",u_DlgBase),idc_mix,[wsf_Group,wsf_TabStop]),\n ctl(wdef(wc_PushButton,rct(67,166,94,178),\"&Reset\",u_DlgBase),idc_reset,[wsf_Group,wsf_TabStop]),\n ctl(wdef(wc_PushButton,rct(40,178,67,190),\"&Save\",u_DlgBase),idc_save,[wsf_Group,wsf_TabStop]),\n ctl(wdef(wc_PushButton,rct(94,178,121,190),\"&Open\",u_DlgBase),idc_open,[wsf_Group,wsf_TabStop]),\n ctl(wdef(wc_PushButton,rct(40,190,121,202),\"&Play\",u_DlgBase),idc_play,[wsf_Group,wsf_TabStop,wsf_Disabled]),\n ctl(wdef(wc_PushButton,rct(94,166,121,178),\"&Exit\",u_DlgBase),idc_cancel,[wsf_Group,wsf_TabStop]),\n ctl(wdef(wc_PushButton,rct(40,40,60,60),\"1\",u_DlgBase),idc_cell1,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(60,40,80,60),\"2\",u_DlgBase),idc_cell2,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(80,40,100,60),\"3\",u_DlgBase),idc_cell3,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(100,40,120,60),\"4\",u_DlgBase),idc_cell4,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(40,60,60,80),\"5\",u_DlgBase),idc_cell5,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(60,60,80,80),\"6\",u_DlgBase),idc_cell6,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(80,60,100,80),\"7\",u_DlgBase),idc_cell7,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(100,60,120,80),\"8\",u_DlgBase),idc_cell8,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(40,80,60,100),\"9\",u_DlgBase),idc_cell9,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(60,80,80,100),\"10\",u_DlgBase),idc_cell10,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(80,80,100,100),\"11\",u_DlgBase),idc_cell11,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(100,80,120,100),\"12\",u_DlgBase),idc_cell12,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(40,100,60,120),\"13\",u_DlgBase),idc_cell13,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(60,100,80,120),\"14\",u_DlgBase),idc_cell14,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(80,100,100,120),\"15\",u_DlgBase),idc_cell15,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(100,100,120,120),\"\",u_DlgBase),idc_cell16,[wsf_Group]),\n ctl(wdef(wc_HScroll,rct(30,18,130,30),\"\",u_DlgBase),idc_sbht,[]),\n ctl(wdef(wc_VScroll,rct(130,30,142,130),\"\",u_DlgBase),idc_sbvr,[]),\n ctl(wdef(wc_HScroll,rct(30,130,130,142),\"\",u_DlgBase),idc_sbhb,[]),\n ctl(wdef(wc_VScroll,rct(18,30,30,130),\"\",u_DlgBase),idc_sbvl,[]),\n ctl(wdef(wc_PushButton,rct(67,178,94,190),\"\",u_DlgBase),idc_step,[wsf_Group]),\n ctl(wdef(wc_PushButton,rct(40,154,121,166),\"\",u_DlgBase),idc_bingo,[wsf_Group,wsf_Invisible])\n ].\n\n predicates\n generatedEventHandler\u00a0: vpiDomains::ehandler.\n clauses\n generatedEventHandler(Win, e_create(_)) = _\u00a0:-\n thisWin\u00a0:= Win,\n fail.\n generatedEventHandler(_Win, e_Create(CreationData)) = Result\u00a0:-\n handled(Result) = onCreate(CreationData).\n generatedEventHandler(_Win, e_Update(Rectangle)) = Result\u00a0:-\n handled(Result) = onUpdate(Rectangle).\n generatedEventHandler(_Win, e_Control(idc_cancel, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlCancel(idc_cancel, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_mix, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlmix(idc_mix, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_reset, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlreset(idc_reset, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_sbvr, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlsbvr(idc_sbvr, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_sbvl, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlsbvl(idc_sbvl, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_sbhb, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlsbhb(idc_sbhb, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_sbht, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlsbht(idc_sbht, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_save, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlsave(idc_save, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_open, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlopen(idc_open, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_play, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlplay(idc_play, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell1, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell1(idc_cell1, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell10, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell10(idc_cell10, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell11, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell11(idc_cell11, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell12, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell12(idc_cell12, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell13, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell13(idc_cell13, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell14, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell14(idc_cell14, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell15, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell15(idc_cell15, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell16, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell16(idc_cell16, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell2, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell2(idc_cell2, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell3, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell3(idc_cell3, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell4, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell4(idc_cell4, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell5, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell5(idc_cell5, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell6, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell6(idc_cell6, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell7, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell7(idc_cell7, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell8, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell8(idc_cell8, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Control(idc_cell9, CtrlType, CtrlWin, CtlInfo)) = Result\u00a0:-\n handled(Result) = onControlcell9(idc_cell9, CtrlType, CtrlWin, CtlInfo).\n generatedEventHandler(_Win, e_Destroy()) = Result\u00a0:-\n handled(Result) = onDestroy().\n \u00a0% end of automatic code\nend implement playDialog", "safe": true }, { "filename": "15 puzzle game_13.txt", "content": " fpg 10\n 1 3 0 4\n 5 2 6 8\n 9 10 7 12\n13 14 11 15\n\u2190\n 1 0 3 4\n 5 2 6 8\n 9 10 7 12\n13 14 11 15\n\u2193\n 1 2 3 4\n 5 0 6 8\n 9 10 7 12\n13 14 11 15\n\u2192\n 1 2 3 4\n 5 6 0 8\n 9 10 7 12\n13 14 11 15\n\u2193\u2193\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 0 15\n\u2192\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\nwin\n\n\n 2 5 fpg 2\n1 2 3 0 4\n6 7 8 9 5\n\u2192\n1 2 3 4 0\n6 7 8 9 5\n\u2193\n1 2 3 4 5\n6 7 8 9 0\nwin\n", "safe": true }, { "filename": "15 puzzle game_130.txt", "content": "'----------------15 game-------------------------------------\n'WARNING: this script uses ANSI escape codes to position items on console so \n'it won't work in Windows from XP to 8.1 where Microsoft removed ANSI support...\n'Windows 10, 11 or 98 are ok!!!\n\noption explicit\nconst maxshuffle=100 'level \n\ndim ans0:ans0=chr(27)&\"[\"\ndim anscls:anscls=ans0 & \"2J\"\n\ndim dirs:dirs=array(6,-1,-6,1)\ndim a:a=array(-1,-1,-1,-1,-1,-1,_\n -1, 1, 2, 3, 4,-1,_\n -1, 5, 6, 7, 8,-1,_\n -1, 9,10,11,12,-1,_\n -1,13,14,15, 0,-1,_\n -1,-1,-1,-1,-1,-1)\ndim b(35)\ndim pos0\ndim s:s=Array(\"W+Enter: up Z+Enter: down A+Enter: left S+Enter right \",_\n \"Bad move!! \",_\n\t \"You did it! Another game? [y/n]+Enter \",_\n\t \"Bye! \")\n\n\ndo\n shuffle\n draw\n toxy 10,1,s(0)\n do \n if usr(wait()) then \n draw \n toxy 10,1,s(0)\n else \t\n toxy 10,1,s(1)\n end if\n loop until checkend\n toxy 10,1,s(2)\nloop until wait()=\"n\"\ntoxy 10,1,s(3)\n\nfunction wait():\n toxy 11,1,\"\":\n wait=left(lcase(wscript.stdin.readline),1):\t\nend function\n\nsub toxy(x,y,s)\n wscript.StdOut.Write ans0 & x & \";\" & y & \"H\"& \" \"& s \nend sub\n\nsub draw\n dim i,j \n wscript.stdout.write anscls\n for i=0 to 3 'row\n for j=0 to 3 'col\n toxy (j*2)+2,(i*3)+3,iif(b(j*6+i+7)<>0,b(j*6+i+7),\" \")\n next\n next\n toxy 10,1,\"\"\nend sub\n\n\nfunction checkend\n dim i\n for i=0 to ubound(a)\n if (b(i)<>a(i)) then checkend=false : exit function\n next\n checkend=true\nend function\t\n\nfunction move(d) \n dim p1 \n p1=pos0+d\n if b(p1) <>-1 then \n b(pos0)=b(p1):\n b(p1)=0:\n pos0=p1:\n move=true\n else\n move=false\n end if \nend function \n\nsub shuffle\n dim cnt,r,i\n randomize timer\n for i=0 to ubound(a):b(i)=a(i):next\n pos0=28\n cnt=0\n do\n r=int(rnd*4)\n if move(dirs(r))=true then cnt=cnt+1\n loop until cnt=maxshuffle\nend sub\t \n\nfunction iif(a,b,c): if a then iif=b else iif=c end if:end function\t\t\t \n\nfunction usr(a)\n dim d \n select case lcase(a)\n case \"w\" :d=-6\n case \"z\" :d=6\n case \"a\" :d=-1\n case \"s\" :d=1\n end select\n usr= move(d) \nend function\n", "safe": true }, { "filename": "15 puzzle game_131.txt", "content": "import \"random\" for Random\nimport \"./dynamic\" for Enum\nimport \"./ioutil\" for Input\nimport \"./fmt\" for Fmt\n\nvar Move = Enum.create(\"Move\", [\"up\", \"down\", \"right\", \"left\"])\n\nvar Rand = Random.new()\nvar RandMove = Fn.new { Rand.int(4) }\n\nvar SolvedBoard = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]\n\nvar AreEqual = Fn.new { |l1, l2|\n if (l1.count != l2.count) return false\n for (i in 0...l1.count) {\n if (l1[i] != l2[i]) return false\n }\n return true\n}\n\nclass Puzzle {\n construct new() {\n _board = SolvedBoard.toList\n _empty = 15 // _board[empty] == 0\n _moves = 0\n _quit = false\n // Could make this configurable, 10 == easy, 50 == normal, 100 == hard\n shuffle(50)\n }\n\n shuffle(moves) {\n // we use some number of random moves to \"shuffle\" the board\n var i = 0\n while (i < moves || AreEqual.call(_board, SolvedBoard)) {\n if (doMove(RandMove.call())) i = i + 1\n }\n }\n\n isValidMove(m) {\n if (m == Move.up) return [_empty - 4, (_empty/4).floor > 0]\n if (m == Move.down) return [_empty + 4, (_empty/4).floor < 3] \n if (m == Move.right) return [_empty + 1, _empty % 4 < 3]\n if (m == Move.left) return [_empty - 1, _empty % 4 > 0]\n Fiber.abort(\"not reached\")\n }\n\n doMove(m) {\n var i = _empty\n var res = isValidMove(m)\n var j = res[0]\n var ok = res[1]\n if (ok) {\n _board.swap(i, j)\n _empty = j\n _moves = _moves + 1\n }\n return ok\n }\n\n play() {\n var instructions = \"\"\"\nPlease enter \"U\", \"D\", \"L\", or \"R\" to move the empty cell\nup, down, left, or right. You can also enter \"Q\" to quit.\nUpper or lowercase is accepted and only the first character\nis important (i.e. you may enter \"up\" if you like).\n\"\"\"\n System.print(instructions)\n System.write(\"\\nStarting board:\")\n while (!AreEqual.call(_board, SolvedBoard) && !_quit) {\n System.print(\"\\n%(this)\")\n playOneMove()\n }\n if (AreEqual.call(_board, SolvedBoard)) {\n System.print(\"\\n%(this)\")\n System.print(\"You solved the puzzle in %(_moves) moves.\")\n }\n }\n\n playOneMove() {\n while (true) {\n var s = Input.option(\"Enter move #%(_moves + 1) (U, D, L, R or Q): \", \"UuDdLlRrQq\")\n var m\n if (s == \"U\" || s == \"u\") {\n m = Move.up\n } else if (s == \"D\" || s == \"d\") {\n m = Move.down\n } else if (s == \"L\" || s == \"l\") {\n m = Move.left\n } else if (s == \"R\" || s == \"r\") {\n m = Move.right\n } else if (s == \"Q\" || s == \"q\") {\n System.print(\"Quiting after %(_moves).\")\n _quit = true\n return\n }\n if (!doMove(m)) {\n System.print(\"That is not a valid move at the moment.\")\n continue\n }\n return\n }\n }\n\n toString {\n var buf = \"\"\n var i = 0\n for (c in _board) {\n if (c == 0) {\n buf = buf + \" .\"\n } else {\n buf = buf + Fmt.swrite(\"$3d\", c)\n }\n if (i % 4 == 3) buf = buf + \"\\n\"\n i = i + 1\n }\n return buf\n }\n}\n\nvar p = Puzzle.new()\np.play()\n", "safe": true }, { "filename": "15 puzzle game_132.txt", "content": "Please enter \"U\", \"D\", \"L\", or \"R\" to move the empty cell\nup, down, left, or right. You can also enter \"Q\" to quit.\nUpper or lowercase is accepted and only the first character\nis important (i.e. you may enter \"up\" if you like).\n\nStarting board:\n 1 2 3 4\n 6 . 7 8\n 5 9 11 12\n 13 10 14 15\n\nEnter move #51 (U, D, L, R or Q): l\n\n 1 2 3 4\n . 6 7 8\n 5 9 11 12\n 13 10 14 15\n\nEnter move #52 (U, D, L, R or Q): d\n\n 1 2 3 4\n 5 6 7 8\n . 9 11 12\n 13 10 14 15\n\nEnter move #53 (U, D, L, R or Q): r\n\n 1 2 3 4\n 5 6 7 8\n 9 . 11 12\n 13 10 14 15\n\nEnter move #54 (U, D, L, R or Q): d\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 . 14 15\n\nEnter move #55 (U, D, L, R or Q): r\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 . 15\n\nEnter move #56 (U, D, L, R or Q): r\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 .\n\nYou solved the puzzle in 56 moves.\n", "safe": true }, { "filename": "15 puzzle game_133.txt", "content": " \u00a0; Puzzle15 by grosged (march 2019)\n \u00a0; How to play\u00a0?.. Just press one of the arrow keys then [enter] to valid\n \u00a0; ( press [Ctrl+C] to escape )\n\n segment\t.data\ncheck:\tdb\t\"1 2 3 4\",10,\" 5 6 7 8\",10,\" 9 10 11 12\",10,\" 13 14 1\"\npuzzle:\tdb\t27,\"c\",10,\" 1 2 3 4\",10,\" 5 6 7 8\",10,\" 9 10 11 12\",10,\" 13 14 15 \",10,10\n\tdb\t\" Direction\u00a0?\",13 \n\tdb\t\" Well done\u00a0! \",10,10\ninKey:\tdw\t0,0,0,0\n\t\n\tsegment\t.text\n\tglobal\t_start\n\n_start:\tmov\trax,100\n\tsyscall\n\tmov\trcx,rax\n\tshr\trcx,3\n\tand\trcx,255\n\tand\trax,31\n\tlea\trsi,[_start+rax]\n\tmov\trbx,15\n\nMixing:\tpush\trcx\n\tmov\tdi,word[rsi+rcx*2]\n\tmov\trcx,8\nquatre:\tmov\tax,di\n\tshr\tdi,2\n\tand\tax,3\n\tadd\tax,65\n\tcall\tSWAPPIN\n\tloop\tquatre\n\tpop\trcx\n\tloop\tMixing\n\tcmp\tcx,ax\n\nMainLp:\tmov\trdx,80\t\nSucces:\tlea\trsi,[puzzle]\n\tmov\trdi,1\n\tmov\trax,1\nEnd?:\tsyscall\n\tmov\trax,60\n\tje\tEnd?\n\tmov\trdx,8\n\tlea\trsi,[inKey]\n\tmov\trdi,0\n\tmov\trax,0\n\tsyscall\n\tmov\tal,byte [rsi+rax-2]\n\tcall\tSWAPPIN\n\tlea \trsi,[check]\n\tlea\trdi,[puzzle+5]\n\tmov\trcx,7\n\trepe\tcmpsq\n\tjne\tMainLp\n\tmov\trdx,95\n\tjmp\tSucces\n\nSWAPPIN:mov\trdx,rbx\n\tcmp\tal,\"A\"\n\tjne\tNotUp\n\tadd\trbx,4\n\tcmp\trbx,16\n\tcmovae\trbx,rdx\nNotUp:\tcmp\tal,\"B\"\n\tjne\tNotDwn\t\n\tsub\trbx,4\n\tcmovc\trbx,rdx\t\nNotDwn:\tcmp\tal,\"C\"\n\tjne\tNotLft\n\ttest\trbx,3\n\tjz\tEndcll\n\tdec\trbx\nNotLft:\tcmp\tal,\"D\"\n\tjne\tEndcll\n\tinc\trbx\n\ttest\trbx,3\n\tcmovz\trbx,rdx\nEndcll:\tmov\tax,\" \"\n\txchg\tax,word[puzzle+4+rbx*4]\n\tmov\tword[puzzle+4+rdx*4],ax\n\tret", "safe": true }, { "filename": "15 puzzle game_134.txt", "content": "PROGRAM \"fifteenpuzzlegame\"\nVERSION \"0.0001\"\n\nIMPORT \"xst\"\n\nDECLARE FUNCTION Entry()\nINTERNAL FUNCTION PrintPuzzle(d%[])\nINTERNAL FUNCTION IntroAndLevel(shCnt%[])\nINTERNAL FUNCTION BuildBoard(d%[], shCnt%[], level%)\nINTERNAL FUNCTION IsMoveValid(d%[], piece%, piecePos%, emptyPos%)\nINTERNAL FUNCTION IsPuzzleComplete(d%[])\nINTERNAL FUNCTION PiecePosition(d%[], piece%)\n\n' Pseudo-random number generator\n' Based on the rand, srand functions from Kernighan & Ritchie's book\n' 'The C Programming Language'\nDECLARE FUNCTION Rand()\nDECLARE FUNCTION SRand(seed%%)\n\nFUNCTION Entry()\n DIM d%[15]\n DIM shCnt%[2]\n BuildBoard(@d%[], @shCnt%[], IntroAndLevel(@shCnt%[]))\n PrintPuzzle(@d%[])\n DO\n x% = SSHORT(INLINE$(\"To move a piece, enter its number: \"))\n DO WHILE IsMoveValid(@d%[], x%, @y%, @z%) = 0\n PRINT \"Wrong move.\"\n PrintPuzzle(@d%[])\n x% = SSHORT(INLINE$(\"To move a piece, enter its number: \"))\n LOOP\n d%[z% - 1] = x%\n d%[y% - 1] = 0\n PrintPuzzle(@d%[])\n LOOP UNTIL IsPuzzleComplete(@d%[])\n PRINT \"YOU WON!\"\nEND FUNCTION\n\nFUNCTION PrintPuzzle(d%[])\n DIM ds$[15] ' Board pieces\n FOR p%% = 0 TO 15\n IF d%[p%%] = 0 THEN\n ds$[p%%] = \" \"\n ELSE\n ds$[p%%] = FORMAT$(\"### \", d%[p%%])\n END IF\n NEXT p%%\n PRINT \"+-----+-----+-----+-----+\"\n PRINT \"|\"; ds$[0]; \"|\"; ds$[1]; \"|\"; ds$[2]; \"|\"; ds$[3]; \"|\"\n PRINT \"+-----+-----+-----+-----+\"\n PRINT \"|\"; ds$[4]; \"|\"; ds$[5]; \"|\"; ds$[6]; \"|\"; ds$[7]; \"|\"\n PRINT \"+-----+-----+-----+-----+\"\n PRINT \"|\"; ds$[8]; \"|\"; ds$[9]; \"|\"; ds$[10]; \"|\"; ds$[11]; \"|\"\n PRINT \"+-----+-----+-----+-----+\"\n PRINT \"|\"; ds$[12]; \"|\"; ds$[13]; \"|\"; ds$[14]; \"|\"; ds$[15]; \"|\"\n PRINT \"+-----+-----+-----+-----+\"\nEND FUNCTION\n\nFUNCTION IntroAndLevel(shCnt%[])\n XstClearConsole()\n shCnt%[0] = 10\n shCnt%[1] = 50\n shCnt%[2] = 100\n PRINT \"15 PUZZLE GAME\"\n PRINT\n PRINT\n PRINT \"Please enter level of difficulty,\"\n DO\n level% = SSHORT(INLINE$(\"1 (easy), 2 (medium) or 3 (hard): \"))\n LOOP UNTIL (level% >= 1) && (level% <= 3)\nEND FUNCTION level%\n\nFUNCTION BuildBoard(d%[], shCnt%[], level%)\n ' Set pieces in correct order first\n FOR p%% = 1 TO 15\n d%[p%% - 1] = p%%\n NEXT p%%\n d%[15] = 0 ' 0 = empty piece/slot\n z% = 16 ' z% = empty position\n PRINT\n PRINT \"Shuffling pieces\";\n XstGetSystemTime (@msec)\n SRand(INT(msec) MOD 32768)\n FOR n% = 1 TO shCnt%[level% - 1]\n PRINT \".\";\n DO\n x% = INT(Rand() / 32768.0 * 4.0) + 1\n PRINT x%\n SELECT CASE x%\n CASE 1:\n r% = z% - 4\n CASE 2:\n r% = z% + 4\n CASE 3:\n IF (z% - 1) MOD 4 <> 0 THEN\n r% = z% - 1\n END IF\n CASE 4:\n IF z% MOD 4 <> 0 THEN\n r% = z% + 1\n END IF\n END SELECT\n LOOP UNTIL (r% >= 1) && (r% <= 16)\n d%[z% - 1] = d%[r% - 1]\n z% = r%\n d%[z% - 1] = 0\n NEXT n%\n XstClearConsole()\nEND FUNCTION\n\nFUNCTION IsMoveValid(d%[], piece%, piecePos%, emptyPos%)\n mv% = 0\n IF (piece% >= 1) && (piece% <= 15) THEN\n piecePos% = PiecePosition(@d%[], piece%)\n emptyPos% = PiecePosition(@d%[], 0)\n ' Check if empty piece is above, below, left or right to piece\n IF (piecePos% - 4 = emptyPos%) || (piecePos% + 4 = emptyPos%) || ((piecePos% - 1 = emptyPos%) && (emptyPos% MOD 4 <> 0)) || ((piecePos% + 1 = emptyPos%) && (piecePos% MOD 4 <> 0)) THEN\n mv% = 1\n END IF\n END IF\nEND FUNCTION mv%\n\nFUNCTION PiecePosition(d%[], piece%)\n p%% = 0\n DO WHILE d%[p%%] <> piece%\n INC p%%\n IF p%% > 15 THEN\n PRINT \"UH OH!\"\n QUIT(1)\n END IF\n LOOP\nEND FUNCTION p%% + 1\n\nFUNCTION IsPuzzleComplete(d%[])\n pc% = 0\n p%% = 1\n DO WHILE (p%% < 16) && (d%[p%% - 1] = p%%)\n INC p%%\n LOOP\n IF p%% = 16 THEN\n pc% = 1\n END IF\nEND FUNCTION pc%\n\n' Return pseudo-random integer on 0..32767\nFUNCTION Rand() \n #next&& = #next&& * 1103515245 + 12345\nEND FUNCTION USHORT(#next&& / 65536) MOD 32768\n\n' Set seed for Rand()\nFUNCTION SRand(seed%%) \n #next&& = seed%%\nEND FUNCTION\n\nEND PROGRAM\n", "safe": true }, { "filename": "15 puzzle game_135.txt", "content": "int Box, Hole, I;\n[Box:= [^ ,^F,^E,^D, \\starting configuration\n ^C,^B,^A,^9, \\slide digits into ascending order\n ^8,^7,^6,^5, \\with blank in lower-right corner\n ^4,^3,^2,^1];\nHole:= 0; \\index for hole position\nloop [Clear; \\erase screen and move to start\n for I:= 0 to 15 do \\show puzzle\n [ChOut(0, Box(I)); ChOut(0, ^ );\n if (I & 3) = 3 then CrLf(0)];\n case ChIn(1) of \\get move\n $1B: quit; \\Esc\n $48: if Hole < 12 then \\UpArrow scan code\n [Box(Hole):= Box(Hole+4);\n Hole:= Hole+4;\n Box(Hole):= ^ ];\n $50: if Hole > 3 then \\DnArrow\n [Box(Hole):= Box(Hole-4);\n Hole:= Hole-4;\n Box(Hole):= ^ ];\n $4B: if (Hole & 3) < 3 then \\LfArrow\n [Box(Hole):= Box(Hole+1);\n Hole:= Hole+1;\n Box(Hole):= ^ ];\n $4D: if (Hole & 3) > 0 then \\RtArrow\n [Box(Hole):= Box(Hole-1);\n Hole:= Hole-1;\n Box(Hole):= ^ ]\n other []; \\ignore 0 scan code prefix etc.\n ];\n]", "safe": true }, { "filename": "15 puzzle game_136.txt", "content": " F E D \nC B A 9 \n8 7 6 5 \n4 3 2 1 \n", "safe": true }, { "filename": "15 puzzle game_137.txt", "content": "dx = 4\u00a0: dy = 4\u00a0: dxy = dx * dy\ndim grid(dx, dy)\n\ndim t(dxy)\n\nfor x = 1 to dx\n\tfor y = 1 to dy\n\t\tfin = false\n\t\trepeat\n\t\t\ti = int(ran(dxy) + 1)\n\t\t\tif t(i) = 0 then\n\t\t\t\tt(i) = 1\n\t\t\t\tfin = true\n\t\t\t\tif i < dxy then\n\t\t\t\t\tgrid(x, y) = i\n\t\t\t\telse\n\t\t\t\t\tex = x\u00a0: ey = y\n\t\t\t\tend if\n\t\t\tend if\n\t\tuntil(fin = true)\n\tnext y\nnext x\n\ndrawTable()\n\nrepeat\n\tmoveTile()\n\tdrawTable()\nuntil(finish())\n\nprint \"\\n\\n\\nNumber of movements: \",mov,\"\\nEnd\\n\"\n\nsub finish()\n\tlocal x, y, v\n\t\n\tfor y = 1 to dy\n\t\tfor x = 1 to dx\n\t\t\tv = v + 1\n\t\t\tif (v < dxy) and (grid(x, y) <> v) return false\n\t\tnext x\n\tnext y\n\treturn true\nend sub\n\nsub moveTile()\n\tlocal direction$\n\t\n\tdirection$ = inkey$\n\t\n\tswitch direction$\n\t\tcase \"up\": if (ey + 1) < (dy + 1) then grid(ex, ey) = grid(ex, ey + 1)\u00a0: ey = ey + 1 end if\u00a0: break\n\t\tcase \"down\": if (ey - 1) > 0 then grid(ex, ey) = grid(ex, ey - 1)\u00a0: ey = ey - 1 end if\u00a0: break\n\t\tcase \"right\": if (ex - 1) > 0 then grid(ex, ey) = grid(ex - 1, ey)\u00a0: ex = ex - 1 end if\u00a0: break\n\t\tcase \"left\": if (ex + 1) < (dx + 1) then grid(ex, ey) = grid(ex + 1, ey)\u00a0: ex = ex + 1 end if\u00a0: break\n\t\tdefault: return\u00a0: break\n\tend switch\n\tmov = mov + 1\n\tgrid(ex, ey) = 0\nend sub\n\nsub drawTable()\n\tlocal x, y\n\t\n\tclear screen\n\t\n\tprint \" Use the cursor keys\"\n\t\n\tfor x = 1 to dx\n\t\tfor y = 1 to dy\n\t\t\tprint at(x * 3, y * 2);\n\t\t\tif grid(x, y) then\n\t\t\t\tprint color(\"yellow\",\"magenta\") grid(x, y) using \"##\"\n\t\t\telse\n\t\t\t\tprint \" \"\n\t\t\tend if\n\t\tnext y\n\tnext x\nend sub", "safe": true }, { "filename": "15 puzzle game_138.txt", "content": "board$ = \"123456789ABCDEF0\"\nsolve$ = board$\npos = 16\n \nsub print_board()\n local i, n$\n\t\n clear screen\n for i = 1 to len(board$)\n \tif i = pos then\n print \" \";\n \telse\n \t n$ = str$(dec(mid$(board$, i, 1)), \"###\")\n \t print n$; \n end if\n if mod(i, 4) = 0 print\n next\n print\nend sub\n \nsub move(d)\n local new_pos, delta(4)\n \n delta(1) = 4\u00a0: delta(2) = 1\u00a0: delta(3) = -1\u00a0: delta(4) = -4\n \n new_pos = pos + delta(d)\n if new_pos >= 1 and new_pos <= 16 and (mod(pos, 4) = mod(new_pos, 4) or floor((pos - 1) / 4) = floor((new_pos - 1) / 4)) then\n \tmid$(board$, pos, 1) = mid$(board$, new_pos, 1)\n \tmid$(board$, new_pos, 1) = \"0\"\n pos = new_pos\n end if\nend sub\n \nfor i = 1 to 100\u00a0: move(int(ran(4))+1)\u00a0: next\ndo\n print_board()\n if board$ = solve$ break\n c = ((instr(\"esc up left rightdown \", inkey$) - 1) / 5)\n if c < 1 break\n move(c)\nloop\nprint \"solved!\\n\"", "safe": true }, { "filename": "15 puzzle game_139.txt", "content": "const std = @import(\"std\");\nconst stdout = std.io.getStdOut().writer();\n\nconst tokens = [16][]const u8{ \" 1\", \" 2\", \" 3\", \" 4\", \" 5\", \" 6\", \" 7\", \" 8\", \" 9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \" \" };\n\nconst empty_token = 15;\nvar empty: u8 = empty_token;\nvar cells: [16]u8 = undefined;\nvar invalid: bool = false;\n\nconst Move = enum { no, up, down, left, right };\n\nfn showBoard() !void {\n try stdout.writeAll(\"\\n\");\n\n var solved = true;\n var i: u8 = 0;\n while (i < 16) : (i += 1) {\n try stdout.print(\" {s} \", .{tokens[cells[i]]});\n if ((i + 1) % 4 == 0) try stdout.writeAll(\"\\n\");\n if (i != cells[i]) solved = false;\n }\n\n try stdout.writeAll(\"\\n\");\n\n if (solved) {\n try stdout.writeAll(\"\\n\\n** You did it! **\\n\\n\");\n std.posix.exit(0);\n }\n}\n\nfn updateToken(move: Move) !void {\n const newEmpty = switch (move) {\n Move.up => if (empty / 4 < 3) empty + 4 else empty,\n Move.down => if (empty / 4 > 0) empty - 4 else empty,\n Move.left => if (empty % 4 < 3) empty + 1 else empty,\n Move.right => if (empty % 4 > 0) empty - 1 else empty,\n else => empty,\n };\n\n if (empty == newEmpty) {\n invalid = true;\n } else {\n invalid = false;\n cells[empty] = cells[newEmpty];\n cells[newEmpty] = empty_token;\n empty = newEmpty;\n }\n}\n\nfn waitForMove() !Move {\n const reader = std.io.getStdIn().reader();\n if (invalid) try stdout.writeAll(\"(invalid) \");\n try stdout.writeAll(\"enter u/d/l/r or q: \");\n const input = try reader.readBytesNoEof(2);\n switch (std.ascii.toLower(input[0])) {\n 'q' => std.posix.exit(0),\n 'u' => return Move.up,\n 'd' => return Move.down,\n 'l' => return Move.left,\n 'r' => return Move.right,\n else => return Move.no,\n }\n}\n\nfn shuffle(moves: u8) !void {\n var random = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));\n const rand = random.random();\n var n: u8 = 0;\n while (n < moves) {\n const move: Move = rand.enumValue(Move);\n try updateToken(move);\n if (!invalid) n += 1;\n }\n invalid = false;\n}\n\npub fn main() !void {\n var n: u8 = 0;\n while (n < 16) : (n += 1) {\n cells[n] = n;\n }\n\n try shuffle(50);\n try showBoard();\n\n while (true) {\n try updateToken(try waitForMove());\n try showBoard();\n }\n}\n", "safe": true }, { "filename": "15 puzzle game_14.txt", "content": "/* ARM assembly Raspberry PI */\n/* program puzzle15.s */\n \n/************************************/\n/* Constantes */\n/************************************/\n.equ STDIN, 0 @ Linux input console\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ IOCTL, 0x36 @ Linux syscall\n.equ SIGACTION, 0x43 @ Linux syscall\n.equ SYSPOLL, 0xA8 @ Linux syscall\n\n.equ TCGETS, 0x5401\n.equ TCSETS, 0x5402\n.equ ICANON, 2\n.equ ECHO, 10\n.equ POLLIN, 1\n\n.equ SIGINT, 2 @ Issued if the user sends an interrupt signal (Ctrl + C)\n.equ SIGQUIT, 3 @ Issued if the user sends a quit signal (Ctrl + D)\n.equ SIGTERM, 15 @ Software termination signal (sent by kill by default)\n.equ SIGTTOU, 22 @ \n\n.equ NBBOX, 16\n.equ TAILLEBUFFER, 10\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structure termios see doc linux*/\n .struct 0\nterm_c_iflag: @ input modes\n .struct term_c_iflag + 4 \nterm_c_oflag: @ output modes\n .struct term_c_oflag + 4 \nterm_c_cflag: @ control modes\n .struct term_c_cflag + 4 \nterm_c_lflag: @ local modes\n .struct term_c_lflag + 4 \nterm_c_cc: @ special characters\n .struct term_c_cc + 20 @ see length if necessary \nterm_fin:\n\n/* structure sigaction see doc linux */\n .struct 0\nsa_handler:\n .struct sa_handler + 4 \nsa_mask:\n .struct sa_mask + 4 \nsa_flags:\n .struct sa_flags + 4 \nsa_sigaction:\n .struct sa_sigaction + 4 \nsa_fin:\n\n/* structure poll see doc linux */\n .struct 0\npoll_fd: @ File Descriptor\n .struct poll_fd + 4 \npoll_events: @ events mask\n .struct poll_events + 4 \npoll_revents: @ events returned\n .struct poll_revents + 4 \npoll_fin:\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \" \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\nszMessGameWin: .ascii \"You win in \"\nsMessCounter: .fill 11, 1, ' ' @ size => 11\n .asciz \" move number\u00a0!!!!\\n\"\nszMessMoveError: .asciz \"Huh... Impossible move\u00a0!!!!\\n\"\nszMessErreur: .asciz \"Error detected.\\n\"\nszMessSpaces: .asciz \" \"\niGraine: .int 123456\n/*************************************************/\nszMessErr: .ascii\t\"Error code hexa\u00a0: \"\nsHexa: .space 9,' '\n .ascii \" decimal\u00a0: \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\nszClear: .byte 0x1B \n\t\t .byte 'c' @ console clear\n\t\t .byte 0\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\niCodeError: .skip 4\nibox: .skip 4 * NBBOX @ game boxes\niEnd: .skip 4 @ 0 loop 1 = end loop\niTouche: .skip 4 @ value key pressed\nstOldtio: .skip term_fin @ old terminal state\nstCurtio: .skip term_fin @ current terminal state\nstSigAction: .skip sa_fin @ area signal structure\nstSigAction1: .skip sa_fin\nstPoll1: .skip poll_fin @ area poll structure\nstPoll2: .skip poll_fin\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: @ entry of program \n mov r0,#0\n ldr r2,iAdribox\n mov r9,#0 @ move counter \n1: @ loop init boxs\n add r1,r0,#1 @ box value\n str r1,[r2,r0, lsl #2] @ store value\n add r0,#1 @ increment counter\n cmp r0,#NBBOX - 2 @ end\u00a0?\n ble 1b\n mov r10,#15 @ empty box location \n ldr r0,iAdribox\n bl shuffleGame\n2: @ loop moves\n ldr r0,iAdribox\n bl displayGame\n //ldr r0,iAdribox\n //bl gameOK @ end game\u00a0?\n //cmp r0,#1\n //beq 50f\n bl readKey @ read key \n cmp r0,#-1\n beq 100f @ error or control-c\n mov r1,r0 @ key\n ldr r0,iAdribox\n bl keyMove\n ldr r0,iAdribox\n bl gameOK @ end game\u00a0?\n cmp r0,#1\n bne 2b @ no -> loop\n50: @ win\n mov r0,r9 @ move counter\n ldr r1,iAdrsMessCounter\n bl conversion10\n ldr r0,iAdrszMessGameWin\n bl affichageMess\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdribox: .int ibox\niAdrszMessGameWin: .int szMessGameWin\niAdrsMessCounter: .int sMessCounter\n/******************************************************************/\n/* key move */ \n/******************************************************************/\n/* r0 contains boxs address */\n/* r1 contains key value */\n/* r9 move counter */\n/* r10 contains location empty box */\nkeyMove:\n push {r1-r8,lr} @ save registers\n mov r8,r0\n cmp r1,#0x42 @ down arrow \n bne 1f\n cmp r10,#4 @ if r10 < 4 error\n blt 80f\n sub r2,r10,#4 @ compute location\n b 90f\n1:\n cmp r1,#0x41 @ high arrow\n bne 2f\n cmp r10,#11 @ if r10 > 11 error\n bgt 80f\n add r2,r10,#4 @ compute location\n b 90f\n2:\n cmp r1,#0x43 @ right arrow\n bne 3f\n tst r10,#0b11 @ if r10 = 0,4,8,12 error\n beq 80f\n sub r2,r10,#1 @ compute location\n b 90f\n3:\n cmp r1,#0x44 @ left arrow\n bne 100f\n and r3,r10,#0b11 @ error if r10 = 3 7 11 and 15\n cmp r3,#3\n beq 80f\n add r2,r10,#1 @ compute location\n b 90f\n\n80: @ move error\n ldr r0,iAdriCodeError\n mov r1,#1\n str r1,[r0]\n b 100f\n90: @ white box and move box inversion\n ldr r3,[r8,r2,lsl #2]\n str r3,[r8,r10,lsl #2]\n mov r10,r2\n mov r3,#0\n str r3,[r8,r10,lsl #2]\n add r9,#1 @ increment move counter\n100:\n pop {r1-r8,lr} @ restaur registers \n bx lr @return\niAdriCodeError: .int iCodeError\n/******************************************************************/\n/* shuffle game */ \n/******************************************************************/\n/* r0 contains boxs address */\nshuffleGame:\n push {r1-r6,lr} @ save registers\n mov r1,r0\n mov r0,#4\n bl genereraleas\n lsl r4,r0,#1\n mov r0,r8\n1:\n mov r0,#14\n bl genereraleas\n add r6,r0,#1\n mov r0,#14\n bl genereraleas\n add r5,r0,#1\n ldr r2,[r1,r6,lsl #2]\n ldr r3,[r1,r5,lsl #2]\n str r2,[r1,r5,lsl #2]\n str r3,[r1,r6,lsl #2]\n subs r4,#1\n bgt 1b\n\n100:\n pop {r1-r6,lr} @ restaur registers \n bx lr @return\n/******************************************************************/\n/* game Ok\u00a0? */ \n/******************************************************************/\n/* r0 contains boxs address */\ngameOK:\n push {r1-r8,lr} @ save registers\n mov r8,r0\n mov r2,#0\n ldr r3,[r8,r2,lsl #2]\n add r2,#1\n1:\n ldr r4,[r8,r2,lsl #2]\n cmp r4,r3\n movlt r0,#0 @ game mot Ok\n blt 100f\n mov r3,r4\n add r2,#1\n cmp r2,#NBBOX -2\n ble 1b\n mov r0,#1 @ game Ok\n\n100:\n pop {r1-r8,lr} @ restaur registers \n bx lr @return\n/******************************************************************/\n/* display game */ \n/******************************************************************/\n/* r0 contains boxs address */\ndisplayGame:\n push {r1-r5,lr} @ save registers\n @ clear\u00a0!\n mov r4,r0\n ldr r0,iAdrszClear\n bl affichageMess \n mov r2,#0\n ldr r1,iAdrsMessValeur\n1:\n ldr r0,[r4,r2,lsl #2]\n cmp r0,#0\n ldreq r0,iSpaces @ store spaces\n streq r0,[r1]\n beq 2f\n bl conversion10 @ call conversion decimal\n mov r0,#0\n strb r0,[r1,#3] @ z\u00e9ro final\n2:\n\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r0,r2,#1\n tst r0,#0b11\n bne 3f\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display message\n3:\n add r2,#1\n cmp r2,#NBBOX - 1\n ble 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display line return\n ldr r0,iAdriCodeError @ error detected\u00a0?\n ldr r1,[r0]\n cmp r1,#0\n beq 100f\n mov r1,#0 @ raz error code\n str r1,[r0]\n ldr r0,iAdrszMessMoveError @ display error message\n bl affichageMess\n100:\n pop {r1-r5,lr} @ restaur registers \n bx lr @return\niSpaces: .int 0x00202020 @ spaces\niAdrszClear: .int szClear \niAdrszMessMoveError: .int szMessMoveError\n/******************************************************************/\n/* display text with size calculation */ \n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ \n bx lr @ return \n/******************************************************************/\n/* Converting a register to a decimal unsigned */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n \n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n/***************************************************/\n/* Generation random number */\n/***************************************************/\n/* r0 contains limit */\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n/*****************************************************/\niAdriGraine: .int iGraine\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n/***************************************************/\n/* integer division unsigned */\n/***************************************************/\ndivision:\n /* r0 contains dividend */\n /* r1 contains divisor */\n /* r2 returns quotient */\n /* r3 returns remainder */\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n/***************************************************/\n/* read touch */\n/***************************************************/\nreadKey:\n push {r1-r7,lr}\n mov r5,#0\n /* read terminal state */\n mov r0,#STDIN @ input console\n mov r1,#TCGETS\n ldr r2,iAdrstOldtio\n mov r7, #IOCTL @ call system Linux\n svc #0 \n cmp r0,#0 @ error\u00a0?\n beq 1f\n ldr r1,iAdrszMessErreur @ error message\n bl displayError\n mov r0,#-1\n b 100f\n1:\n adr r0,sighandler @ adresse routine traitement signal\n ldr r1,iAdrstSigAction @ adresse structure sigaction\n str r0,[r1,#sa_handler] @ maj handler\n mov r0,#SIGINT @ signal type\n ldr r1,iAdrstSigAction\n mov r2,#0 @ NULL\n mov r7, #SIGACTION @ call system\n svc #0 \n cmp r0,#0 @ error\u00a0?\n bne 97f\n mov r0,#SIGQUIT\n ldr r1,iAdrstSigAction\n mov r2,#0 @ NULL\n mov r7, #SIGACTION @ call system \n svc #0 \n cmp r0,#0 @ error\u00a0?\n bne 97f\n mov r0,#SIGTERM\n ldr r1,iAdrstSigAction\n mov r2,#0 @ NULL\n mov r7, #SIGACTION @ appel systeme \n svc #0 \n cmp r0,#0\n bne 97f\n @\n adr r0,iSIG_IGN @ address signal ignore function\n ldr r1,iAdrstSigAction1\n str r0,[r1,#sa_handler]\n mov r0,#SIGTTOU @invalidate other process signal\n ldr r1,iAdrstSigAction1\n mov r2,#0 @ NULL\n mov r7,#SIGACTION @ call system \n svc #0 \n cmp r0,#0\n bne 97f\n @\n /* read terminal current state */\n mov r0,#STDIN\n mov r1,#TCGETS\n ldr r2,iAdrstCurtio @ address current termio\n mov r7,#IOCTL @ call systeme \n svc #0 \n cmp r0,#0 @ error\u00a0?\n bne 97f\n mov r2,#ICANON | ECHO @ no key pressed echo on display\n mvn r2,r2 @ and one key \n ldr r1,iAdrstCurtio\n ldr r3,[r1,#term_c_lflag]\n and r3,r2 @ add flags \n str r3,[r1,#term_c_lflag] @ and store\n mov r0,#STDIN @ maj terminal current state \n mov r1,#TCSETS\n ldr r2,iAdrstCurtio\n mov r7, #IOCTL @ call system\n svc #0 \n cmp r0,#0\n bne 97f\n @\n2: @ loop waiting key\n ldr r0,iAdriEnd @ if signal ctrl-c -> end\n ldr r0,[r0]\n cmp r0,#0\n movne r5,#-1\n bne 98f\n ldr r0,iAdrstPoll1 @ address structure poll\n mov r1,#STDIN\n str r1,[r0,#poll_fd] @ maj FD\n mov r1,#POLLIN @ action code\n str r1,[r0,#poll_events]\n mov r1,#1 @ items number structure poll\n mov r2,#0 @ timeout = 0 \n mov r7,#SYSPOLL @ call system POLL\n svc #0 \n cmp r0,#0 @ key pressed\u00a0?\n ble 2b @ no key pressed -> loop\n @ read key\n mov r0,#STDIN @ File Descriptor\n ldr r1,iAdriTouche @ buffer address\n mov r2,#TAILLEBUFFER @ buffer size\n mov r7,#READ @ read key\n svc #0\n cmp r0,#0 @ error\u00a0?\n bgt 98f\n\n97: @ error detected\n ldr r1,iAdrszMessErreur @ error message\n bl displayError\n mov r5,#-1\n98: @ end then restaur begin state terminal\n mov r0,#STDIN\n mov r1,#TCSETS\n ldr r2,iAdrstOldtio\n mov r7,#IOCTL @ call system \n svc #0\n cmp r0,#0\n beq 99f @ restaur ok\n ldr r1,iAdrszMessErreur @ error message\n bl displayError\n mov r0,#-1\n b 100f\n99:\n cmp r5,#0 @ error or control-c\n ldreq r2,iAdriTouche @ key address\n ldreqb r0,[r2,#2] @ return key byte\n movne r0,r5 @ or error\n100:\n pop {r1-r7, lr}\n bx lr\niSIG_IGN: .int 1\niAdriEnd: .int iEnd\niAdrstPoll1: .int stPoll1\niAdriTouche: .int iTouche\niAdrstOldtio: .int stOldtio\niAdrstCurtio: .int stCurtio\niAdrstSigAction: .int stSigAction\niAdrstSigAction1: .int stSigAction1\niAdrszMessErreur\u00a0: .int szMessErreur \n/******************************************************************/\n/* traitement du signal */ \n/******************************************************************/\nsighandler:\n push {r0,r1}\n ldr r0,iAdriEnd\n mov r1,#1 @ maj zone end\n str r1,[r0]\n pop {r0,r1}\n bx lr\n/***************************************************/\n/* display error message */\n/***************************************************/\n/* r0 contains error code r1\u00a0: message address */\ndisplayError:\n push {r0-r2,lr} @ save registers\n mov r2,r0 @ save error code\n mov r0,r1\n bl affichageMess\n mov r0,r2 @ error code\n ldr r1,iAdrsHexa\n bl conversion16 @ conversion hexa\n mov r0,r2 @ error code\n ldr r1,iAdrsDeci @ result address\n bl conversion10 @ conversion decimale\n ldr r0,iAdrszMessErr @ display error message\n bl affichageMess\n100:\n pop {r0-r2,lr} @ restaur registers\n bx lr @ return \niAdrszMessErr: .int szMessErr\niAdrsHexa: .int sHexa\niAdrsDeci: .int sDeci\n/******************************************************************/\n/* Converting a register to hexadecimal */ \n/******************************************************************/\n/* r0 contains value and r1 address area */\nconversion16:\n push {r1-r4,lr} @ save registers\n mov r2,#28 @ start bit position\n mov r4,#0xF0000000 @ mask\n mov r3,r0 @ save entry value\n1: @ start loop\n and r0,r3,r4 @value register and mask\n lsr r0,r2 @ move right \n cmp r0,#10 @ compare value\n addlt r0,#48 @ <10 ->digit\t\n addge r0,#55 @ >10 ->letter A-F\n strb r0,[r1],#1 @ store digit on area and + 1 in area address\n lsr r4,#4 @ shift mask 4 positions\n subs r2,#4 @ counter bits - 4 <= zero \u00a0?\n bge 1b @ no -> loop\n\n100:\n pop {r1-r4,lr} @ restaur registers \n bx lr @return", "safe": true }, { "filename": "15 puzzle game_140.txt", "content": " 1 2 3 4 \n 5 6 7 8 \n 9 10 12 \n 13 14 11 15 \n\nenter u/d/l/r or q: r\n\n 1 2 3 4 \n 5 6 7 8 \n 9 10 12 \n 13 14 11 15 \n\nenter u/d/l/r or q: u\n\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n 13 14 15 \n\nenter u/d/l/r or q: l\n\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n 13 14 15 \n\n\n** You did it! **\n", "safe": true }, { "filename": "15 puzzle game_15.txt", "content": ";; ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~\n;; ===>> ~~ Game's functions ~~ <<===\n;; --->> ~~ Init functions ~~ <<---\n\n;; This is a solved sample that is used to\n;; init and finish the game\nsolvedTable: @[ \" 1 \" \" 2 \" \" 3 \" \" 4 \"\n \" 5 \" \" 6 \" \" 7 \" \" 8 \"\n \" 9 \" \" 10 \" \" 11 \" \" 12 \"\n \" 13 \" \" 14 \" \" 15 \" \" \" ]\n\n;; Use this once in :game's init, to get a player position\n;; Q: Why use it once?\n;; A: This algorithm is slower than just get a stored varible\n;; yet this searches for a string for every value from :game\ngetPlayerPosition: $[table :block][\n return index table \" \"\n]\n\n;; This is the object that represents the game\n;; 'table\u00a0\u00bb The sample table to generate the game\ndefine :game [\n table :block\n][\n\n init: [\n ; checks if 'table has 16 elements\n ensure [16 = size this\\table]\n\n ;; The game's table itself\n this\\table: (shuffle this\\table) ; creates a random game\n ;; The current movement. When less, better is your punctuation\n this\\movements: 0\n ;; The current 'playerPosition in table\n ;; Used to evaluate if certain movement is possible or not\n this\\playerPosition: getPlayerPosition this\\table\n ;; Defines it the gameLoop still running\n this\\running?: true\n ]\n\n ;; A builtin print function that simplifies the use\n print: [\n render {\n Movements: |this\\movements|, Position: |this\\playerPosition|\n *-----*-----*-----*-----*\n |this\\table\\0| |this\\table\\1| |this\\table\\2| |this\\table\\3|\n *-----*-----*-----*-----*\n |this\\table\\4| |this\\table\\5| |this\\table\\6| |this\\table\\7|\n *-----*-----*-----*-----*\n |this\\table\\8| |this\\table\\9| |this\\table\\10| |this\\table\\11|\n *-----*-----*-----*-----*\n |this\\table\\12| |this\\table\\13| |this\\table\\14| |this\\table\\15|\n *-----*-----*-----*-----*\n }\n ]\n\n ;; Compares the internal's 'table with another :block\n compare: [\n if this\\table = that\n -> return true\n ]\n\n]\n\n;; These are the commands used internally on game\n;; To avoid ambiguity, User's input'll to be translated to this\ngameActions: ['up, 'left, 'down, 'right, 'quit]\n\n\n;; ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~\n;; -->> Print funnctions <<---\n\n;; A template for print instructions\nprintInstructions: [\n color #cyan \"Type (WASD) to move and (Q) to quit.\"\n]\n\n;; A template for print input warning\n;; 'input: the wrong input itself that will be printed\nprintWrongInput: $[inp :string][\n print color #red\n ~\"Wrong input: '|inp|'\"\n]\n\n;; A template for print input warning\n;; 'action: could be 'up, 'down, 'left or 'right\nprintWrongMovement: $[action :literal][\n print color #red\n ~\"Wrong movement. Can't go |action|\"\n]\n\n\n;; ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~\n;; --->> Validators/Checkers functions <<---\n\n;; Checks if a 'input is in 'gameActions\n;; Valids for: 'up, 'down, 'left, 'right and 'quit\nvalidInput?: $[inp :any][\n return (in? inp gameActions)\n]\n\n;; Checks if the current movement tried is possible\n;; 'game\u00a0\u00bb is the current game\n;; 'movement\u00a0\u00bb must be in 'gameActions, but can't be 'quit\nvalidMovement?: $[\n game :game\n movement :literal\n][\n pos: game\\playerPosition\n case [movement]\n when? [='up]\n -> return (not? in? pos [0..3])\n when? [='down]\n -> return (not? in? pos [12..15])\n when? [='left]\n -> return (not? in? pos [0 4 8 12])\n when? [='right]\n -> return (not? in? pos [3 7 11 15])\n else\n -> return false\n]\n\n\n;; ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~\n;; --->> Action functions <<---\n\n;; Gets user input from terminal\n;; returning a :literal from 'gameActions\n;; Raises: In case of wrong input,\n;; will be returned the same input as a :string\nparseInput: $[inp :string][\n lowerInp: lower inp\n case [lowerInp]\n when? [=\"w\"] -> return 'up\n when? [=\"a\"] -> return 'left\n when? [=\"s\"] -> return 'down\n when? [=\"d\"] -> return 'right\n when? [=\"q\"] -> return 'quit\n else -> return inp\n]\n\n;; Moves the player in Game's Table\n;; Note that this's a unsafe function,\n;; use 'validMovement? to check a 'movement given a game,\n;; and then use this\nmovePlayer: $[\n game :game\n movement :literal\n][\n\n position: game\\playerPosition\n\n updateGame: $[\n game :game\n playerPosition :integer\n relativePosition :integer\n ][\n try [\n\n ; 'otherPosition is the real index of the 'relativePosition\n otherPosition: + playerPosition relativePosition\n\n ; -- Updates the table, swaping the positions\n temp: game\\table\\[playerPosition]\n game\\table\\[playerPosition]: game\\table\\[otherPosition]\n game\\table\\[otherPosition]: temp\n\n ; -- Updates player's status\n game\\playerPosition: otherPosition\n game\\movements: inc game\\movements\n ] else -> panic \"'movement didn't checked.\"\n ]\n\n case [movement]\n when? [='up]\n -> (updateGame game position (neg 4))\n when? [='down]\n -> (updateGame game position (4))\n when? [='left]\n -> (updateGame game position (neg 1))\n when? [='right]\n -> (updateGame game position (1))\n else -> panic \"'movement didn't checked.\"\n\n]\n\nendGame: $[\n message :string\n][\n print message\n exit\n]\n\n\n;; ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~\n;; --->> Run function <<---\n\n;; Inits ans runs the game\n;; 'sampleTable must be already solved\nrunGame: $[sampleTable :block][\n game: to :game [sampleTable]\n\n while [game\\running?] [\n print game\n print printInstructions\n command: parseInput input \">> \"\n\n if command = 'quit\n -> endGame \"Exiting game...\"\n\n validInp: validInput? command\n if? validInp [\n validMov: validMovement? game command\n (validMov)?\n -> movePlayer game command\n -> printWrongMovement command\n ] else\n -> printWrongInput command\n\n if sampleTable = game\n -> endGame \"Congratulations! You won!\"\n print \"\"\n ]\n]\n\n\nrunGame solvedTable\n", "safe": true }, { "filename": "15 puzzle game_16.txt", "content": "type Puzzle(var items: {}, var position: -1)\n\nfun mainframe(puz):\n let d = puz.items\n print('+-----+-----+-----+-----+')\n print(d[1], d[2], d[3], d[4], first: '|', sep: '|', last: '|')\n print('+-----+-----+-----+-----+')\n print(d[5], d[6], d[7], d[8], first: '|', sep: '|', last: '|')\n print('+-----+-----+-----+-----+')\n print(d[9], d[10], d[11], d[12], first: '|', sep: '|', last: '|')\n print('+-----+-----+-----+-----+')\n print(d[13], d[14], d[15], d[16], first: '|', sep: '|', last: '|')\n print('+-----+-----+-----+-----+')\n\nfun format(puz, ch):\n match ch.trim().length:\n 1 => ' $ch '\n 2 => ' $ch '\n 0 => ' '\n\nfun change(puz, to):\n let fro = puz.position\n for a, b in puz.items where b == puz.format(str i):\n to = a\n break\n\n swap(puz.items[fro], :[to])\n puz.position = to;\n\nfun buildboard(puz, difficulty):\n for i in 1..16:\n puz.items[i] = puz.format(str i)\n\n var tmp = a\n for a, b in puz.items where b == ' 16 ':\n puz.items[a] = ' '\n tmp = a\n break\n\n puz.position = tmp\n let diff = match difficulty:\n 0 => 10\n 1 => 50\n _ => 100\n\n for i in 1..diff:\n let lst = puz.validmoves()\n let lst1 = []\n for j in lst:\n lst1.push! j.trim().int()\n puz.change(lst1[random(1, lst1.length - 1)])\n\nfun validmoves(puz):\n match puz.position:\n 6 | 7 | 10 | 11 =>\n puz.items[pos - 4], :[pos - 1], :[pos + 1], :[pos + 4]\n 5 | 9 =>\n puz.items[pos - 4], :[pos + 4], :[pos + 1]\n 8 | 12 =>\n puz.items[pos - 4], :[pos + 4], :[pos - 1]\n 2 | 3 =>\n puz.items[pos - 1], :[pos + 1], :[pos + 4]\n 14 | 15 =>\n puz.items[pos - 1], :[pos + 1], :[pos - 4]\n 1 =>\n puz.items[pos + 1], :[pos + 4]\n 4 =>\n puz.items[pos - 1], :[pos + 4]\n 13 =>\n puz.items[pos + 1], :[pos - 4]\n 16 =>\n puz.items[pos - 1], :[pos - 4]\n\nfun mainframe(puz):\n var flag = false\n for a, b in puz.items:\n if b == ' ':\n pass\n else:\n flag = (a == b.trim().int())\n ..\n return flag\n\nlet game = Puzzle()\ngame.buildboard(\n int(input('Enter the difficulty\u00a0: 0 1 2\\n2 => highest 0=> lowest\\n'))\n)\ngame.mainframe()\n\nprint 'Enter 0 to exit'\n\nloop:\n print 'Hello user:\\nTo change the position just enter the no. near it'\n\n var lst = game.validmoves()\n var lst1 = []\n for i in lst:\n lst1.push! i.trim().int()\n print(i.strip(), '\\t', last: '')\n\n print()\n\n let value = int(input())\n if value == 0:\n break\n elif x not in lst1:\n print('Wrong move')\n else:\n game.change(x)\n\n game.mainframe()\n if g.gameover():\n print 'You WON'\n break\n", "safe": true }, { "filename": "15 puzzle game_17.txt", "content": "Size := 20\nGrid := [], Deltas := [\"-1,0\",\"1,0\",\"0,-1\",\"0,1\"], Width := Size * 2.5\nGui, font, S%Size%\nGui, add, text, y1\nloop, 4\n{\n\tRow := A_Index\n\tloop, 4\n\t{\n\t\tCol := A_Index\n\t\tGui, add, button, % (Col=1 ? \"xs y+1\" : \"x+1 yp\") \" v\" Row \"_\" Col \" w\" Width \" gButton -TabStop\", % Grid[Row,Col] := Col + (Row-1)*4\u00a0; 1-16\n\t}\n}\nGuiControl, Hide, % Row \"_\" Col\t; 4_4\nGui, add, Button, % \"xs gShuffle w\" 4 * Width + 3, Shuffle\nGui, show,, 15 Puzzle\nreturn\n;------------------------------\nGuiClose:\nExitApp\nreturn\n;------------------------------\nShuffle:\nShuffle := true\nloop, 1000\n{\n\tRandom, Rnd, 1,4\n\tMove(StrSplit(Deltas[Rnd], \",\").1, StrSplit(Deltas[Rnd], \",\").2)\n}\nShuffle := false\nreturn\n;------------------------------\nButton:\nbuttonRow := SubStr(A_GuiControl, 1, 1), ButtonCol := SubStr(A_GuiControl, 3, 1)\nif Abs(buttonRow-Row) > 1 || Abs(ButtonCol-Col) > 1 || Abs(buttonRow-Row) = Abs(ButtonCol-Col)\n\treturn\nMove(buttonRow-Row, ButtonCol-Col)\nreturn\n;------------------------------\n#IfWinActive, 15 Puzzle\n;------------------------------\nDown::\nMove(-1, 0)\nreturn\n;------------------------------\nUp::\nMove(1, 0)\nreturn\n;------------------------------\nRight::\nMove(0, -1)\nreturn\n;------------------------------\nLeft::\nMove(0, 1)\nreturn\n;------------------------------\n#IfWinActive\n;------------------------------\nMove(deltaRow, deltaCol){\n\tglobal\n\tif (Row+deltaRow=0) || (Row+deltaRow=5) || (Col+deltaCol=0) || (Col+deltaCol=5)\n\t\treturn\n\tGuiControl, Hide, % Row+deltaRow \"_\" Col+deltaCol\n\tGuiControl, Show, % Row \"_\" Col\n\tGuiControl,, %Row%_%Col%, % Grid[Row+deltaRow, Col+deltaCol]\n\tGrid[Row, Col] := Grid[Row+deltaRow, Col+deltaCol]\n\tGrid[Row+=deltaRow, Col+=deltaCol] := 16\n\tif Shuffle\n\t\treturn\n\tgridCont := \"\"\n\tfor m, obj in grid\n\t\tfor n, val in obj\n\t\t\tgridCont .= val \",\"\n\tif (Trim(gridCont, \",\") = \"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16\")\n\t\tMsgBox, 262208, 15 Puzzle, You solved 15 Puzzle\n}\n", "safe": true }, { "filename": "15 puzzle game_18.txt", "content": " 100 GOSUB 500INITIALIZE\n 110 FOR Q = 1 TO 1\n 120 IF I <> X OR J <> Y THEN GOSUB 200MOVE\n 130 ON W GOSUB 330,450\n 140 LET I = K(0, K) + X\n 150 LET J = K(1, K) + Y\n 160 LET Q = K(2, K) OR W = 3\n 170 NEXT Q\n 180 VTAB T + 3\n 190 END\n\n REM MOVE\n 200 IF I < 0 THEN RETURN\n 210 IF I > 3 THEN RETURN\n 220 IF J < 0 THEN RETURN\n 230 IF J > 3 THEN RETURN\n 240 LET M = (I + J * 4) * 3\n 250 LET N = (X + Y * 4) * 3\n 260 IF N > M GOTO 290SWAP\n 270 LET N = M\n 280 LET M = (X + Y * 4) * 3\n REM SWAP\n 290 LET A$ = MID$(A$, 1, M) + MID$(A$, N + 1, 2) + MID$(A$,M + 3, N - M - 2) + MID$(A$, M + 1, 2) + MID$(A$, N + 3)\n 300 LET X = I\n 310 LET Y = J\n 320 ON W GOTO 440,400\n\n REM RANDOM MOVE\n 330 VTAB T + 3\n 340 HTAB 2\n 350 PRINT MID$(S$, S + 1, 10);\n 360 LET S = NOT S\n 370 LET K = INT(RND(1) * 4) + 1\n 380 IF PEEK(49152) < 128 OR A$ = W$ THEN RETURN\n 390 LET K = PEEK(49168) * 0\n REM SHOW\n 400 VTAB T\n 410 HTAB 1\n 420 PRINT A$;\n 430 LET W = (A$ = W$) + 2\n REM DON'T SHOW\n 440 RETURN\n\n REM GET KEY\n 450 VTAB T + Y\n 460 HTAB X * 3 + 2\n 470 GET K$\n 480 LET K = ASC (K$)\n 490 RETURN\n\n REM INITIALIZE\n 500 PRINT \" 15-PUZZLE\"\n\n REM KEYBOARD\n\n REM ARROW KEYS TWO HANDED CLASSIC T REVERSE T SEQUENCED\n REM ^K A I G ^C\n REM ^H ^J ^U , Z . J K L H T F ^B ^D ^A\n\n REM RIGHT , J H ^A\n 510 DATA8,44,74,106,72,104,1\n\n REM LEFT . L F ^B\n 520 DATA21,46,76,108,70,102,2\n\n REM DOWN A I G ^C\n 530 DATA11,65,97,73,105,71,103,3\n\n REM UP Z K T ^D\n 540 DATA10,90,122,75,107,84,116,4\n\n REM QUIT ^Q ESC\n 550 DATA0,17,27,0\n \n 560 DIM K(2,127)\n 570 FOR V = 0 TO 2\n 580 FOR D = - 1 TO 1 STEP 2\n 590 FOR R = 1 TO 1\n 600 READ K\n 610 LET K(V,K) = D\n 620 LET R = K < 5\n 630 NEXT R,D,V\n 640 LET A$ = \" 1 2 3 4\"\n 650 LET M$ = CHR$ (13)\n 660 LET L$ = \" 5 6 7 8\"\n 670 LET A$ = A$ + M$ + L$\n 680 LET L$ = \" 9 10 11 12\"\n 690 LET A$ = A$ + M$ + L$\n 700 LET L$ = \"13 14 15 \"\n 710 LET A$ = A$ + M$ + L$\n 720 LET W$ = A$\n 730 DATA3,3,3,3,1,0\n 740 READ X,Y,I,J,W,k(2, 0)\n 750 PRINT \"PRESS A KEY\"\n 760 PRINT \" TO STOP\"\n 770 LET S$ = \" SHUFFLING \"\n 780 LET T = PEEK(37) - 2\n 790 RETURN\n", "safe": true }, { "filename": "15 puzzle game_19.txt", "content": "10 REM 15-PUZZLE GAME\n20 REM COMMODORE BASIC 2.0\n30 REM ********************************\n40 GOSUB 400 : REM INTRO AND LEVEL\n50 GOSUB 510 : REM SETUP BOARD\n60 GOSUB 210 : REM PRINT PUZZLE\n70 PRINT \"TO MOVE A PIECE, ENTER ITS NUMBER:\"\n80 INPUT X\n90 GOSUB 760 : REM CHECK IF MOVE IS VALID\n100 IF MV=0 THEN PRINT \"WRONG MOVE\" : GOSUB 1130 : GOTO 60\n110 D(Z)=X : D(Y)=0\n120 GOSUB 210 : REM PRINT PUZZLE\n130 GOSUB 1030: REM CHECK IF PUZZLE COMPLETE\n140 IF PC THEN 160\n150 GOTO 70\n160 PRINT\"YOU WON!\"\n170 END\n180 REM\n190 REM *******************************\n200 REM PRINT/DRAW THE PUZZLE\n210 FOR P=1 TO 16\n220 IF D(P)=0 THEN D$(P)=\" \" : GOTO 260\n230 S$=STR$(D(P))\n240 N=LEN(S$)\n250 D$(P) = LEFT$(\" \",3-N)+S$+\" \"\n260 NEXT\n270 PRINT \"+-----+-----+-----+-----+\"\n280 PRINT \"!\"D$(1)\"!\"D$(2)\"!\"D$(3)\"!\"D$(4)\"!\"\n290 PRINT \"+-----+-----+-----+-----+\"\n300 PRINT \"!\"D$(5)\"!\"D$(6)\"!\"D$(7)\"!\"D$(8)\"!\"\n310 PRINT \"+-----+-----+-----+-----+\"\n320 PRINT \"!\"D$(9)\"!\"D$(10)\"!\"D$(11)\"!\"D$(12)\"!\"\n330 PRINT \"+-----+-----+-----+-----+\"\n340 PRINT \"!\"D$(13)\"!\"D$(14)\"!\"D$(15)\"!\"D$(16)\"!\"\n350 PRINT \"+-----+-----+-----+-----+\"\n360 RETURN\n370 REM\n380 REM *******************************\n390 REM INTRO AND LEVEL OF DIFFICULTY\n400 PRINT CHR$(147)\n410 DIM SH(3) : SH(1)=10 : SH(2)=50 : SH(3)=100\n420 PRINT \"15 PUZZLE GAME FOR COMMODORE BASIC 2.0\" : PRINT : PRINT\n430 PRINT \"PLEASE ENTER LEVEL OF DIFFICULTY,\"\n440 PRINT \"1(EASY), 2(MEDIUM) OR 3(HARD):\";\n450 INPUT V\n460 IF V<1 OR V>3 THEN 440\n470 RETURN\n480 REM\n490 REM *******************************\n500 REM BUILD THE BOARD\n510 DIM D(16) : DIM D$(16) : REM BOARD PIECES\n520 REM SET PIECES IN CORRECT ORDER FIRST\n530 FOR P=1 TO 15\n540 D(P) = P\n550 NEXT\n560 D(16) = 0 : REM 0 = EMPTY PIECE/SLOT\n570 Z=16 : REM Z = EMPTY POSITION\n580 PRINT: PRINT \"SHUFFLING PIECES\";\n590 FOR N=1 TO SH(V)\n600 PRINT\".\";\n610 X = INT(RND(0)*4)+1\n620 IF X=1 THEN R=Z-4\n630 IF X=2 THEN R=Z+4\n640 IF (X=3) AND (INT((Z-1)/4)<>(Z-1)/4) THEN R=Z-1\n650 IF (X=4) AND (INT(Z/4)<>Z/4) THEN R=Z+1\n660 IF R<1 OR R>16 THEN 610\n670 D(Z)=D(R)\n680 Z=R\n690 D(Z)=0\n700 NEXT\n710 PRINT CHR$(147)\n720 RETURN\n730 REM\n740 REM *******************************\n750 REM CHECK IF MOVE IS VALID\n760 MV = 0\n770 IF X<1 OR X>15 THEN RETURN\n780 REM FIND POSITION OF PIECE X AND OF EMPTY PIECE\n790 AX=X\n800 GOSUB 940 : REM FIND POSITION OF PIECE AX\n810 Y=P\n820 AX=0\n830 GOSUB 940 : REM FIND POSITION OF PIECE AX\n840 Z=P\n850 REM CHECK IF EMPTY PIECE IS ABOVE, BELOW, LEFT OR RIGHT TO PIECE X\n860 IF Y-4=Z THEN MV=1 : RETURN\n870 IF Y+4=Z THEN MV=1 : RETURN\n880 IF (Y-1=Z) AND (INT(Z/4)<>Z/4) THEN MV=1 : RETURN\n890 IF (Y+1=Z) AND (INT(Y/4)<>Y/4) THEN MV=1 : RETURN\n900 RETURN\n910 REM\n920 REM *******************************\n930 REM FIND POSITION OF PIECE AX\n940 P=1\n950 IF D(P)=AX THEN 990\n960 P=P+1\n970 IF P>16 THEN PRINT \"UH OH!\" : STOP\n980 GOTO 950\n990 RETURN\n1000 REM\n1010 REM *******************************\n1020 REM CHECK IF PUZZLE IS COMPLETE / GAME OVER\n1030 PC = 0\n1040 P=1\n1050 IF (P>=16) OR (D(P)<>P) THEN 1080\n1060 P=P+1\n1070 GOTO 1050\n1080 IF P=16 THEN PC=1\n1090 RETURN\n1100 REM\n1110 REM ******************************\n1120 REM A SMALL DELAY\n1130 FOR T=0 TO 400\n1140 NEXT\n1150 RETURN\n", "safe": true }, { "filename": "15 puzzle game_2.txt", "content": ";15 PUZZLE GAME\n;Ram Variables\nCursor_X equ $00FF0000\t\t;Ram for Cursor Xpos\nCursor_Y equ $00FF0000+1\t;Ram for Cursor Ypos\njoypad1 equ $00FF0002\n\nGameRam equ $00FF1000\t\t;Ram for where the pieces are\nGameRam_End equ $00FF100F\t;the last valid slot in the array\n;Video Ports\nVDP_data\tEQU\t$C00000\t; VDP data, R/W word or longword access only\nVDP_ctrl\tEQU\t$C00004\t; VDP control, word or longword writes only\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; \t\t\t\t\tVECTOR TABLE\n;org $00000000\n\tDC.L\t$00FFFFFE\t\t;SP register value\n\tDC.L\tProgramStart\t;Start of Program Code\n\tDC.L\tIntReturn\t\t; bus err\n\tDC.L\tIntReturn\t\t; addr err\n\tDC.L\tIntReturn\t\t; illegal inst\n\tDC.L\tIntReturn\t\t; divzero\n\tDC.L\tIntReturn\t\t; CHK\n\tDC.L\tIntReturn\t\t; TRAPV\n\tDC.L\tIntReturn\t\t; privilege viol\n\tDC.L\tIntReturn\t\t; TRACE\n\tDC.L\tIntReturn\t\t; Line A (1010) emulator\n\tDC.L\tIntReturn\t\t; Line F (1111) emulator\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn\t\t; Reserved /Coprocessor/Format err/ Uninit Interrupt\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn\n\tDC.L\tIntReturn\t\t; spurious interrupt\n\tDC.L\tIntReturn\t\t; IRQ level 1\n\tDC.L\tIntReturn\t\t; IRQ level 2 EXT\n\tDC.L\tIntReturn\t\t; IRQ level 3\n\tDC.L\tIntReturn\t\t; IRQ level 4 Hsync\n\tDC.L\tIntReturn\t\t; IRQ level 5\n\tDC.L\tIntReturn\t\t; IRQ level 6 Vsync\n\tDC.L\tIntReturn\t\t; IRQ level 7 (NMI)\n;org $00000080\n;TRAPS\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn\n;org $000000C0\n;FP/MMU\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn\n\tDC.L\tIntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn,IntReturn\n\n\t\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tHeader\nHEADER:\n\tDC.B\t\"SEGA GENESIS \"\t ;System Name\tMUST TAKE UP 16 BYTES, USE PADDING IF NECESSARY\n\tDC.B\t\"(C)PDS \"\t\t\t;Copyright\tMUST TAKE UP 8 BYTES, USE PADDING IF NECESSARY\n \tDC.B\t\"2022.JUN\"\t\t\t;Date\t\tMUST TAKE UP 8 BYTES, USE PADDING IF NECESSARY\nCARTNAME:\n\tDC.B \t\"15 PUZZLE\"\nCARTNAME_END:\n\tDS.B 48-(CARTNAME_END-CARTNAME)\t;ENSURES PROPER SPACING\nCARTNAMEALT:\n\tDC.B\t\"15 PUZZLE\"\nCARTNAMEALT_END:\n\tDS.B 48-(CARTNAMEALT_END-CARTNAMEALT)\t;ENSURES PROPER SPACING\ngameID:\n\tDC.B\t\"GM PUPPY001-00\"\t ;TT NNNNNNNN-RR T=Type (GM=Game) N=game Num R=Revision\n\tDC.W\t$0000\t\t\t\t;16-bit Checksum (Address $000200+)\nCTRLDATA:\n\tDC.B\t\"J \"\t ;Control Data (J=3button K=Keyboard 6=6button C=cdrom) \n ;(MUST TAKE UP 16 BYTES, USE PADDING IF NECESSARY)\nROMSTART:\n\tDC.L\t$00000000\t\t\t;ROM Start\nROMLEN:\n\tDC.L\t$003FFFFF\t\t\t;ROM Length\nRAMSTART:\n\tDC.L\t$00FF0000\nRAMEND:\n\tDC.L\t$00FFFFFF\t;RAM start/end (fixed)\n\n\tDC.B\t\" \"\t\t;External RAM Data\t(MUST TAKE UP 12 BYTES, USE PADDING IF NECESSARY)\n\tDC.B\t\" \"\t\t;Modem Data\t\t(MUST TAKE UP 12 BYTES, USE PADDING IF NECESSARY)\nMEMO:\n\tDC.B\t\" \" ;(MUST TAKE UP 40 BYTES, USE PADDING IF NECESSARY)\nREGION:\n\tDC.B\t\"JUE \"\t;Regions Allowed (MUST TAKE UP 16 BYTES, USE PADDING IF NECESSARY)\n\teven\nHEADER_END:\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tGeneric Interrupt Handler\nIntReturn:\n\trte ;immediately return to game\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tProgram Start\nProgramStart:\n\t;initialize TMSS (TradeMark Security System)\n\tmove.b ($A10001),D0\t\t;A10001 test the hardware version\n\tand.b #$0F,D0\n\tbeq\tNoTmss\t\t\t\t;branch if no TMSS chip\n\tmove.l #'SEGA',($A14000);A14000 disable TMSS \nNoTmss:\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tSet Up Graphics\n\n\tlea VDPSettings,A5\t\t ;Initialize Screen Registers\n\tmove.l #VDPSettingsEnd-VDPSettings,D1 ;length of Settings\n\t\n\tmove.w (VDP_ctrl),D0\t ;C00004 read VDP status (interrupt acknowledge?)\n\tmove.l #$00008000,d5\t ;VDP Reg command (%8rvv)\n\t\nNextInitByte:\n\tmove.b (A5)+,D5\t\t\t ;get next video control byte\n\tmove.w D5,(VDP_ctrl)\t ;C00004 send write register command to VDP\n\t\t; 8RVV - R=Reg V=Value\n\tadd.w #$0100,D5\t\t\t ;point to next VDP register\n\tdbra D1,NextInitByte\t ;loop for rest of block\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Set up palette\n\t\n\t;Define palette\n\tmove.l #$C0000000,d0\t;Color 0 (background)\n\tmove.l d0,VDP_Ctrl\n\t; ----BBB-GGG-RRR-\n\tmove.w #%0000011000000000,VDP_data\n\t\n\tmove.l #$C01E0000,d0\t;Color 15 (Font)\n\tmove.l d0,VDP_Ctrl\n\tmove.w #%0000000011101110,VDP_data\n\t\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;\t\t\t\t\tSet up Font\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n; FONT IS 1BPP, THIS ROUTINE CONVERTS IT TO A 4BPP FORMAT.\n\tlea Font,A1\t\t\t\t\t ;Font Address in ROM\n\tmove.l #Font_End-Font,d6\t ;Our font contains 96 letters 8 lines each\n\t\n\tmove.l #$40000000,(VDP_Ctrl);Start writes to VRAM address $0000\nNextFont:\n\tmove.b (A1)+,d0\t\t;Get byte from font\n\tmoveq.l #7,d5\t\t;Bit Count (8 bits)\n\tclr.l d1\t\t;Reset BuildUp Byte\n\t\nFont_NextBit:\t\t\t;1 color per nibble = 4 bytes\n\n\trol.l #3,d1\t\t;Shift BuildUp 3 bits left\n\troxl.b #1,d0\t\t;Shift a Bit from the 1bpp font into the Pattern\n\troxl.l #1,d1\t\t;Shift bit into BuildUp\n\tdbra D5,Font_NextBit ;Next Bit from Font\n\t\n\tmove.l d1,d0\t\t; Make fontfrom Color 1 to color 15\n\trol.l #1,d1\t\t;Bit 1\n\tor.l d0,d1\n\trol.l #1,d1\t\t;Bit 2\n\tor.l d0,d1\n\trol.l #1,d1\t\t;Bit 3\n\tor.l d0,d1\n\t\n\tmove.l d1,(VDP_Data);Write next Long of char (one line) to VDP\n\tdbra d6,NextFont\t;Loop until done\n\n\t\n\n\tclr.b Cursor_X\t\t;Clear Cursor XY\n\tclr.b Cursor_Y\n\t\n\t;Turn on screen\n\tmove.w\t#$8144,(VDP_Ctrl);C00004 reg 1 = 0x44 unblank display\n\t\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; all of the above was just the prep work to boot the Sega Genesis, and had nothing to do with a 15 Puzzle.\n; That's hardware for you!\n\n\tLEA GameRam,A0 \n ;load the initial state of the puzzle. There is no randomization here unfortunately, as creating a sufficient pseudo-RNG\n ;to make the game \"believable\" is more difficult than programming the game itself!\n ;so instead we'll start in such a manner that the player has to do quite a bit of work to win.\n\tMOVE.B #'F',(A0)+\n\tMOVE.B #'E',(A0)+\n\tMOVE.B #'D',(A0)+\n\tMOVE.B #'C',(A0)+\n\tMOVE.B #'B',(A0)+\n\tMOVE.B #'A',(A0)+\n\tMOVE.B #'9',(A0)+\n\tMOVE.B #'8',(A0)+\n\tMOVE.B #'7',(A0)+\n\tMOVE.B #'6',(A0)+\n\tMOVE.B #'5',(A0)+\n\tMOVE.B #'4',(A0)+\n\tMOVE.B #'3',(A0)+\n\tMOVE.B #'2',(A0)+\n\tMOVE.B #'1',(A0)+\n\tMOVE.B #' ',(A0)+\n\n ;puzzle will look like:\n ;FEDC\n ;BA98\n ;7654\n ;321 \n\nmain:\n\tJSR Player_ReadControlsDual ;get controller input\n\tmove.w d0,(joypad1)\n\n\n\t;adjust the number of these as you see fit.\n\t;this affects the game's overall speed.\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\tJSR waitVBlank\n\n ;find where the blank space is among GameRAM\n\tLEA GameRAM,a0\n\tMOVE.B #' ',D0\n\tJSR REPNE_SCASB\n\tMOVE.L A0,A1\t\n\t\n;;;;;;;;;;;;;;;;;;; check controller presses\nJOYPAD_BITFLAG_M equ 2048\nJOYPAD_BITFLAG_Z equ 1024\nJOYPAD_BITFLAG_Y equ 512\nJOYPAD_BITFLAG_X equ 256\nJOYPAD_BITFLAG_S equ 128\nJOYPAD_BITFLAG_C equ 64\nJOYPAD_BITFLAG_B equ 32\nJOYPAD_BITFLAG_A equ 16\nJOYPAD_BITFLAG_R equ 8\nJOYPAD_BITFLAG_L equ 4\nJOYPAD_BITFLAG_D equ 2\nJOYPAD_BITFLAG_U equ 1\n\nJOYPAD_BITNUM_M equ 11\nJOYPAD_BITNUM_Z equ 10\nJOYPAD_BITNUM_Y equ 9\nJOYPAD_BITNUM_X equ 8\nJOYPAD_BITNUM_S equ 7\nJOYPAD_BITNUM_C equ 6\nJOYPAD_BITNUM_B equ 5\nJOYPAD_BITNUM_A equ 4\nJOYPAD_BITNUM_R equ 3\nJOYPAD_BITNUM_L equ 2\nJOYPAD_BITNUM_D equ 1\nJOYPAD_BITNUM_U equ 0\n\n\n\n\n\tmove.w (joypad1),D0\n\n\tBTST #JOYPAD_BITNUM_U,D0\n\tBNE JoyNotUp\n\t\tMOVEM.L D0/A1,-(SP)\n\t\t\tADDA.L #4,A1\n\t\t\tCMPA.L #GameRam_End,A1\n\t\t\tBHI .doNothing\n\t\t\t;OTHERWISE SWAP THE EMPTY SPACE WITH THE BYTE BELOW IT.\n\t\t\t\tMOVE.B (A1),D7\n\t\t\t\tMOVE.B (A0),(A1)\n\t\t\t\tMOVE.B D7,(A0)\t\n.doNothing\n\t\tMOVEM.L (SP)+,D0/A1\n\t\tbra vdraw\t\nJoyNotUp:\n\tBTST #JOYPAD_BITNUM_D,D0\n\tBNE JoyNotDown\n\t\tMOVEM.L D0/A1,-(SP)\n\n\t\t\tSUBA.L #4,A1\t\t;CHECK ONE ROW ABOVE WHERE WE ARE\n\t\t\tCMPA.L #GameRam,A1\n\t\t\tBCS .doNothing\t\t;if A1-4 IS BELOW THE START OF GAME RAM, DON'T MOVE\n\t\t\t;OTHERWISE SWAP THE EMPTY SPACE WITH THE BYTE ABOVE IT.\n\t\t\t\tMOVE.B (A1),D7\n\t\t\t\tMOVE.B (A0),(A1)\n\t\t\t\tMOVE.B D7,(A0)\t\t\t\t\n.doNothing:\n\t\tMOVEM.L (SP)+,D0/A1\n\t\tbra vdraw\nJoyNotDown:\n\tBTST #JOYPAD_BITNUM_L,D0\n\tBNE JoyNotLeft\n\t\tMOVEM.L D0/A1,-(SP)\n\t\t\tADDA.L #1,A1\n\t\t\tMOVE.L A1,D4\n\t\t\tMOVE.L A0,D3\n\t\t\tAND.L #3,D4\n\t\t\tAND.L #3,D3\n\t\t\tCMP.L D3,D4\t\n\t\t\tBCS .doNothing\n\t\t\t;OTHERWISE SWAP THE EMPTY SPACE WITH THE BYTE TO THE LEFT\n\t\t\t\tMOVE.B (A1),D7\n\t\t\t\tMOVE.B (A0),(A1)\n\t\t\t\tMOVE.B D7,(A0)\t\t\t\t\n.doNothing:\n\t\tMOVEM.L (SP)+,D0/A1\n\t\tbra vdraw\nJoyNotLeft:\n\tBTST #JOYPAD_BITNUM_R,D0\n\tBNE JoyNotRight\n\t\tMOVEM.L D0/A1,-(SP)\n\t\t\tSUBA.L #1,A1\n\t\t\tMOVE.L A1,D4\n\t\t\tMOVE.L A0,D3\n\t\t\tAND.L #3,D4\n\t\t\tAND.L #3,D3\n\t\t\tCMP.L D3,D4\t\n\t\t\tBHI .doNothing\n\t\t\t;OTHERWISE SWAP THE EMPTY SPACE WITH THE BYTE TO THE RIGHT\n\t\t\t\tMOVE.B (A1),D7\n\t\t\t\tMOVE.B (A0),(A1)\n\t\t\t\tMOVE.B D7,(A0)\t\t\t\t\n.doNothing:\n\t\tMOVEM.L (SP)+,D0/A1\n\t\tbra vdraw\nJoyNotRight:\n\nvdraw:\n\t;this actually draws the current state of the puzzle to the screen.\n\tLEA GameRam,A0\n\tCLR.B (Cursor_X) ;reset text cursors to top left of screen\n\tCLR.B (Cursor_Y)\n\t\n;draw the puzzle\n\n;anything insize a REPT N...ENDR block is in-lined N times, back to back.\n rept 4\n\n\t MOVE.B (A0)+,D0 \n\t JSR PrintChar\n\n\t MOVE.B (A0)+,D0\n\t JSR PrintChar\n\n\t MOVE.B (A0)+,D0\n\t JSR PrintChar\n\n\t MOVE.B (A0)+,D0\n\t JSR PrintChar ;we just finished drawing one row of the puzzle. Now, begin a new line and continue drawing.\n\n jsr newline\n endr\n\t\n\t\ncheckIfWin:\n\t;YES THIS IS MESSY, I TRIED IT WITH A LOOP BUT IT WOULDN'T WORK SO I JUST UNROLLED THE LOOP.\n\tLEA GameRam,a4\n\tMOVE.B (A4)+,D5\n\tCMP.B #'1',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'2',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'3',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'4',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'5',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'6',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'7',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'8',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'9',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'A',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'B',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'C',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'D',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'E',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #'F',D5\n\tBNE .keepGoing\n\n\tMOVE.B (A4)+,D5\n\tCMP.B #' ',D5\n\tBNE .keepGoing\n\t\n\tclr.b (Cursor_X)\n\tmove.b #7,(Cursor_Y)\n\tLEA victoryMessage,a3\n\tjsr PrintString\n\tjmp * ;game freezes after you win.\n\n.keepGoing:\n;it's unlikely that the label \"main\" is in range of here so I didn't bother checking and just assumed it was out of range.\n;Otherwise I would have said \"BEQ main\" instead of BNE .keepGoing\n\tjmp main\n\t\t\n\nVictoryMessage:\n\tDC.B \"A WINNER IS YOU\",255\n\tEVEN\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nREPNE_SCASB:\n\t;INPUT: \n\t;A0 = POINTER TO START OF MEMORY\n\t;D0 = THE BYTE TO SEARCH FOR\n\t;OUTPUT = A0 POINTS TO THE BYTE THAT CONTAINED D0\n\tMOVE.B (A0),D1\n\tCMP.B D0,D1\n\tBEQ .done\n\tADDA.L #1,A0\n\tBRA REPNE_SCASB\n.done:\n\tRTS\n\t\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n\n\nPlayer_ReadControlsDual:\n\t\n\tmove.b #%01000000,($A1000B)\t; Set direction IOIIIIII (I=In O=Out)\n\tmove.l #$A10003,a0\t\t;RW port for player 1\n\n\tmove.b #$40,(a0)\t; TH = 1\n\tnop\t\t;Delay\n\tnop\n\tmove.b (a0),d2\t\t; d0.b = --CBRLDU\tStore in D2\n\t\n\tmove.b\t#$0,(a0)\t; TH = 0\n\tnop\t\t;Delay\n\tnop\n\tmove.b\t(a0),d1\t\t; d1.b = --SA--DU\tStore in D1\n\t\n\tmove.b #$40,(a0)\t; TH = 1\n\tnop\t\t;Delay\n\tnop\n\tmove.b\t#$0,(a0)\t; TH = 0\n\tnop\t\t;Delay\n\tnop\n\tmove.b #$40,(a0)\t; TH = 1\n\tnop\t\t;Delay\n\tnop\n\tmove.b\t(a0),d3\t\t; d1.b = --CBXYZM\tStore in D3\n\tmove.b\t#$0,(a0)\t; TH = 0\n\t\n\tclr.l d0\t\t\t;Clear buildup byte\n\troxr.b d2\n\troxr.b d0\t\t\t;U\n\troxr.b d2\n\troxr.b d0\t\t\t;D\n\troxr.b d2\n\troxr.b d0\t\t\t;L\n\troxr.b d2\n\troxr.b d0\t\t\t;R\n\troxr.b #5,d1\n\troxr.b d0\t\t\t;A\n\troxr.b d2\n\troxr.b d0\t\t\t;B\n\troxr.b d2\n\troxr.b d0\t\t\t;C\n\troxr.b d1\n\troxr.b d0\t\t\t;S\n\t\n\tmove.l d3,d1\n\troxl.l #7,d1\t\t;XYZ\n\tand.l #%0000011100000000,d1\n\tor.l d1,d0\t\t\t\n\t\n\tmove.l d3,d1\n\troxl.l #8,d1\t\t;M\n\troxl.l #3,d1\t\t\n\tand.l #%0000100000000000,d1\n\tor.l d1,d0\n\t\n\tor.l #$FFFFF000,d0\t;Set unused bits to 1\n\n\t\n\t\n\t;this returns player 1's buttons into D0 as the following:\n\t;----MZYXSCBARLDU\n\trts\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\nwaitVBlank:\t\t\t\t\t\t\t;Bit 3 defines if we're in Vblank\n\tMOVE.L d0,-(sp)\n.wait:\n\t\tmove.w VDP_ctrl,d0\n\t\tand.w #%0000000000001000,d0\t\t;See if vblank is running\n\t\tbne .wait\t\t\t\t\t;wait until it is\n\t\t\nwaitVBlank2:\n\t\tmove.w VDP_ctrl,d0\n\t\tand.w #%0000000000001000,d0\t\t;See if vblank is running\n\t\tbeq waitVBlank2\t\t\t\t\t;wait until it isnt\n\tMOVE.L (SP)+,d0\n\trts\t\t\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\t\nPrintChar:\t\t\t\t;Show D0 to screen\n\tmoveM.l d0-d7/a0-a7,-(sp)\n\t\tand.l #$FF,d0\t\t\t;Keep only 1 byte\n\t\tsub #32,d0\t\t\t\t;No Characters in our font below 32\nPrintCharAlt:\t\t\n\t\tMove.L #$40000003,d5\t;top 4=write, bottom $3=Cxxx range\n\t\tclr.l d4\t\t\t\t\t;Tilemap at $C000+\n\n\t\tMove.B (Cursor_Y),D4\t\n\t\trol.L #8,D4\t\t\t\t;move $-FFF to $-FFF----\n\t\trol.L #8,D4\n\t\trol.L #7,D4\t\t\t\t;2 bytes per tile * 64 tiles per line\n\t\tadd.L D4,D5\t\t\t\t;add $4------3\n\t\t\n\t\tMove.B (Cursor_X),D4\n\t\trol.L #8,D4\t\t\t\t;move $-FFF to $-FFF----\n\t\trol.L #8,D4\n\t\trol.L #1,D4\t\t\t\t;2 bytes per tile\n\t\tadd.L D4,D5\t\t\t\t;add $4------3\n\t\t\n\t\tMOVE.L\tD5,(VDP_ctrl)\t; C00004 write next character to VDP\n\t\tMOVE.W\tD0,(VDP_data)\t; C00000 store next word of name data\n\n\t\taddq.b #1,(Cursor_X)\t;INC Xpos\n\t\tmove.b (Cursor_X),d0\n\t\tcmp.b #39,d0\n\t\tbls nextpixel_Xok\n\t\tjsr NewLine\t\t\t;If we're at end of line, start newline\nnextpixel_Xok:\n\tmoveM.l (sp)+,d0-d7/a0-a7\n\trts\n\t\nPrintString:\n\t\tmove.b (a3)+,d0\t\t\t;Read a character in from A3\n\t\tcmp.b #255,d0\n\t\tbeq PrintString_Done\t;return on 255\n\t\tjsr PrintChar\t\t\t;Print the Character\n\t\tbra PrintString\nPrintString_Done:\t\t\n\trts\n\t\nNewLine:\n\taddq.b #1,(Cursor_Y)\t\t;INC Y\n\tclr.b (Cursor_X)\t\t\t;Zero X\n\trts\t\n\t\nFont:\t\t\t\t\t\t\t\n;1bpp font - 8x8 96 characters\n;looks just like your typical \"8-bit\" font. You'll just have to take my word for it.\n DC.B $00,$00,$00,$00,$00,$00,$00,$00,$18,$3c,$3c,$18,$18,$00,$18,$18\n DC.B $36,$36,$12,$24,$00,$00,$00,$00,$00,$12,$7f,$24,$24,$fe,$48,$00\n DC.B $00,$04,$1e,$28,$1c,$0a,$3c,$10,$00,$62,$64,$08,$10,$26,$46,$00\n DC.B $00,$18,$24,$20,$12,$2c,$44,$3a,$18,$18,$08,$10,$00,$00,$00,$00\n DC.B $08,$10,$20,$20,$20,$20,$10,$08,$10,$08,$04,$04,$04,$04,$08,$10\n DC.B $00,$10,$38,$10,$28,$00,$00,$00,$00,$00,$10,$10,$7c,$10,$10,$00\n DC.B $00,$00,$00,$00,$0c,$0c,$04,$08,$00,$00,$00,$00,$7e,$00,$00,$00\n DC.B $00,$00,$00,$00,$00,$18,$18,$00,$01,$02,$04,$08,$10,$20,$40,$00\n DC.B $1c,$26,$63,$63,$63,$32,$1c,$00,$0c,$1c,$0c,$0c,$0c,$0c,$3f,$00\n DC.B $3e,$63,$07,$1e,$3c,$70,$7f,$00,$3f,$06,$0c,$1e,$03,$63,$3e,$00\n DC.B $0e,$1e,$36,$66,$7f,$06,$06,$00,$7e,$60,$7e,$03,$03,$63,$3e,$00\n DC.B $1e,$30,$60,$7e,$63,$63,$3e,$00,$7f,$63,$06,$0c,$18,$18,$18,$00\n DC.B $3c,$62,$72,$3c,$4f,$43,$3e,$00,$3e,$63,$63,$3f,$03,$06,$3c,$00\n DC.B $00,$18,$18,$00,$18,$18,$00,$00,$00,$0c,$0c,$00,$0c,$0c,$04,$08\n DC.B $00,$00,$06,$18,$60,$18,$06,$00,$00,$00,$00,$7e,$00,$7e,$00,$00\n DC.B $00,$00,$60,$18,$06,$18,$60,$00,$1c,$36,$36,$06,$0c,$00,$0c,$0c\n DC.B $3c,$42,$99,$a1,$a1,$99,$42,$3c,$1c,$36,$63,$63,$7f,$63,$63,$00\n DC.B $7e,$63,$63,$7e,$63,$63,$7e,$00,$1e,$33,$60,$60,$60,$33,$1e,$00\n DC.B $7c,$66,$63,$63,$63,$66,$7c,$00,$3f,$30,$30,$3e,$30,$30,$3f,$00\n DC.B $7f,$60,$60,$7e,$60,$60,$60,$00,$1f,$30,$60,$67,$63,$33,$1f,$00\n DC.B $63,$63,$63,$7f,$63,$63,$63,$00,$3f,$0c,$0c,$0c,$0c,$0c,$3f,$00\n DC.B $03,$03,$03,$03,$03,$63,$3e,$00,$63,$66,$6c,$78,$7c,$6e,$67,$00\n DC.B $30,$30,$30,$30,$30,$30,$3f,$00,$63,$77,$7f,$7f,$6b,$63,$63,$00\n DC.B $63,$73,$7b,$7f,$6f,$67,$63,$00,$3e,$63,$63,$63,$63,$63,$3e,$00\n DC.B $7e,$63,$63,$63,$7e,$60,$60,$00,$3e,$63,$63,$63,$6f,$66,$3d,$00\n DC.B $7e,$63,$63,$67,$7c,$6e,$67,$00,$3c,$66,$60,$3e,$03,$63,$3e,$00\n DC.B $3f,$0c,$0c,$0c,$0c,$0c,$0c,$00,$63,$63,$63,$63,$63,$63,$3e,$00\n DC.B $63,$63,$63,$77,$3e,$1c,$08,$00,$63,$63,$6b,$7f,$7f,$77,$63,$00\n DC.B $63,$77,$3e,$1c,$3e,$77,$63,$00,$33,$33,$33,$1e,$0c,$0c,$0c,$00\n DC.B $7f,$07,$0e,$1c,$38,$70,$7f,$00,$00,$38,$20,$20,$20,$20,$38,$00\n DC.B $80,$40,$20,$10,$08,$04,$02,$00,$00,$1c,$04,$04,$04,$04,$1c,$00\n DC.B $10,$28,$44,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$7e,$00\n DC.B $00,$20,$10,$00,$00,$00,$00,$00,$00,$18,$04,$1c,$24,$2c,$1c,$00\n DC.B $00,$20,$20,$38,$24,$24,$38,$00,$00,$00,$1c,$20,$20,$20,$1c,$00\n DC.B $00,$04,$04,$1c,$24,$24,$1c,$00,$00,$00,$1c,$24,$3c,$20,$1c,$00\n DC.B $00,$18,$24,$20,$30,$20,$20,$00,$00,$1c,$24,$24,$1c,$04,$3c,$00\n DC.B $00,$20,$20,$38,$24,$24,$24,$00,$00,$10,$00,$10,$10,$10,$10,$00\n DC.B $08,$00,$08,$08,$08,$08,$28,$10,$20,$20,$24,$28,$30,$28,$24,$00\n DC.B $10,$10,$10,$10,$10,$10,$18,$00,$00,$00,$40,$68,$54,$54,$54,$00\n DC.B $00,$00,$28,$34,$24,$24,$24,$00,$00,$00,$1c,$22,$22,$22,$1c,$00\n DC.B $00,$00,$38,$24,$24,$38,$20,$20,$00,$00,$1c,$24,$24,$1c,$04,$04\n DC.B $00,$00,$2c,$30,$20,$20,$20,$00,$00,$00,$1c,$20,$1c,$02,$3c,$00\n DC.B $00,$10,$3c,$10,$10,$14,$08,$00,$00,$00,$24,$24,$24,$24,$1a,$00\n DC.B $00,$00,$24,$24,$24,$14,$18,$00,$00,$00,$92,$92,$92,$5a,$6c,$00\n DC.B $00,$00,$22,$14,$08,$14,$22,$00,$00,$00,$24,$24,$1c,$04,$18,$00\n DC.B $00,$00,$3c,$04,$18,$20,$3c,$00,$00,$08,$10,$10,$20,$10,$10,$08\n DC.B $18,$18,$18,$18,$18,$18,$18,$18,$00,$10,$08,$08,$04,$08,$08,$10\n DC.B $00,$00,$00,$30,$4a,$04,$00,$00,$1c,$7f,$00,$7f,$55,$55,$55,$00\nFont_End:\n\nVDPSettings:\n\tDC.B $04 ; 0 mode register 1\t\t\t\t\t\t\t\t\t\t\t---H-1M-\n\tDC.B $04 ; 1 mode register 2\t\t\t\t\t\t\t\t\t\t\t-DVdP---\n\tDC.B $30 ; 2 name table base for scroll A (A=top 3 bits)\t\t\t\t--AAA--- = $C000\n\tDC.B $3C ; 3 name table base for window (A=top 4 bits / 5 in H40 Mode)\t--AAAAA- = $F000\n\tDC.B $07 ; 4 name table base for scroll B (A=top 3 bits)\t\t\t\t-----AAA = $E000\n\tDC.B $6C ; 5 sprite attribute table base (A=top 7 bits / 6 in H40)\t\t-AAAAAAA = $D800\n\tDC.B $00 ; 6 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $00 ; 7 background color (P=Palette C=Color)\t\t\t\t\t\t--PPCCCC\n\tDC.B $00 ; 8 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $00 ; 9 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $FF ;10 H interrupt register (L=Number of lines)\t\t\t\t\tLLLLLLLL\n\tDC.B $00 ;11 mode register 3\t\t\t\t\t\t\t\t\t\t\t----IVHL\n\tDC.B $81 ;12 mode register 4 (C bits both1 = H40 Cell)\t\t\t\t\tC---SIIC\n\tDC.B $37 ;13 H scroll table base (A=Top 6 bits)\t\t\t\t\t\t\t--AAAAAA = $FC00\n\tDC.B $00 ;14 unused register\t\t\t\t\t\t\t\t\t\t\t--------\n\tDC.B $02 ;15 auto increment (After each Read/Write)\t\t\t\t\t\tNNNNNNNN\n\tDC.B $01 ;16 scroll size (Horiz & Vert size of ScrollA & B)\t\t\t\t--VV--HH = 64x32 tiles\n\tDC.B $00 ;17 window H position (D=Direction C=Cells)\t\t\t\t\tD--CCCCC\n\tDC.B $00 ;18 window V position (D=Direction C=Cells)\t\t\t\t\tD--CCCCC\n\tDC.B $FF ;19 DMA length count low\t\t\t\t\t\t\t\t\t\tLLLLLLLL\n\tDC.B $FF ;20 DMA length count high\t\t\t\t\t\t\t\t\t\tHHHHHHHH\n\tDC.B $00 ;21 DMA source address low\t\t\t\t\t\t\t\t\t\tLLLLLLLL\n\tDC.B $00 ;22 DMA source address mid\t\t\t\t\t\t\t\t\t\tMMMMMMMM\n\tDC.B $80 ;23 DMA source address high (C=CMD)\t\t\t\t\t\t\tCCHHHHHH\nVDPSettingsEnd:\n\teven\n", "safe": true }, { "filename": "15 puzzle game_20.txt", "content": " IF INKEY(-256)=77 OR (INKEY(-256) AND &F0)=&A0 THEN MODE 1: COLOUR 0: COLOUR 143: *FX4,1\n\n SIZE=4 : DIFFICULTY=3\n\n MAX=SIZE * SIZE - 1\n DIM Board(MAX)\n FOR I%=1 TO MAX : Board(I% - 1)=I% : NEXT\n Gap=MAX\n WHILE N% < DIFFICULTY ^ 2 PROCSlide(RND(4)) : ENDWHILE : REM Shuffle\n N%=0\n\n @%=2 + LOG(MAX + 1)\n PROCShowAndTest\n WHILE NOT Solved\n PRINT \"Use arrow keys to move the gap around. Moves taken: \";N%\n PROCSlide(GET - 135)\n PROCShowAndTest\n ENDWHILE\n PRINT \"Solved after \";N% LEFT$(\" moves\", 6 + (N% = 1)) \".\"\n END\n\n DEF PROCSlide(dir%)\n NewGap=Gap\n CASE dir% OF\n WHEN 1: IF Gap MOD SIZE > 0 NewGap=Gap - 1 : N%+=1 : REM Left\n WHEN 2: IF Gap MOD SIZE < SIZE - 1 NewGap=Gap + 1 : N%+=1 : REM Right\n WHEN 3: IF Gap < MAX - SIZE + 1 NewGap=Gap + SIZE : N%+=1 : REM Down\n WHEN 4: IF Gap > SIZE - 1 NewGap=Gap - SIZE : N%+=1 : REM Up\n ENDCASE\n SWAP Board(Gap), Board(NewGap)\n Gap=NewGap\n ENDPROC\n\n DEF PROCShowAndTest\n CLS\n Solved=TRUE\n FOR I%=0 TO MAX\n COLOUR 12 : COLOUR 135\n IF I% = Gap COLOUR 1 : COLOUR 129\n IF I% MOD SIZE = SIZE - 1 PRINT Board(I%) ELSE PRINT Board(I%),;\n IF Solved IF I% < MAX - 1 IF Board(I%) > Board(I% + 1) OR I% = Gap Solved=FALSE\n NEXT\n COLOUR 0 : COLOUR 143\n PRINT\n ENDPROC\n", "safe": true }, { "filename": "15 puzzle game_21.txt", "content": "_while_ \u2190 {\ud835\udd3d\u235f\ud835\udd3e\u2218\ud835\udd3d_\ud835\udd63_\ud835\udd3e\u2218\ud835\udd3d\u235f\ud835\udd3e\ud835\udd69}\nFPG\u2190{\n \ud835\udd4a\ud835\udd69: 4\u203f4\ud835\udd4a\ud835\udd69;\n (\u2227\u00b4\ud835\udd68<0)\u22282\u2260\u2260\ud835\udd68 ? \u2022Out \"Invalid shape: \"\u223e\u2022Fmt \ud835\udd68;\n 0\u2260=\ud835\udd69 ? \u2022Out \"Invalid shuffle count: \"\u223e\u2022Fmt \ud835\udd69;\n s\ud835\udd4a\ud835\udd69:\n d\u2190\u27e81\u203f0\u22c4\u00af1\u203f0\u22c40\u203f1\u22c40\u203f\u00af1\u27e9 # Directions\n w\u2190\ud835\udd68\u294a1\u233d\u2195\u00d7\u00b4\ud835\udd68 # Solved grid\n b\u2190w # Board\n z\u2190\u2291{\n z\u203fp\u2190\ud835\udd69\n p\u21a9(\u22a2\u2261s\u22b8|)\u00a8\u22b8/(4 ? \u2022Out \"Invalid direction: \"\u223ex, Check x;\n (\u22a2\u2262s\u22b8|)z+i\u2291d ? \u2022Out \"Out of bounds: \"\u223ex, Check x;\n i\n }\n } @\n {\n \ud835\udd69=4 ? \u2022Out \"Quitting\", 0;\n mv\u2190z+\ud835\udd69\u2291d\n b\u233d\u233e(mv\u203fz\u22b8\u2291)\u21a9\n z\u21a9mv\n 1\n } inp\n } _while_ \u22a2 1\n @\n}\n", "safe": true }, { "filename": "15 puzzle game_22.txt", "content": " )ex 15_puzzle.bqn\n FPG 10\n\u250c\u2500 \n\u2575 1 2 0 3 \n 5 6 7 4 \n 9 10 11 8 \n 13 14 15 12 \n \u2518\nEnter move: \na\nInvalid direction: a\nEnter move: \n\u2191\n\u250c\u2500 \n\u2575 1 2 7 3 \n 5 6 0 4 \n 9 10 11 8 \n 13 14 15 12 \n \u2518\nEnter move: \n\u2193\n\u250c\u2500 \n\u2575 1 2 0 3 \n 5 6 7 4 \n 9 10 11 8 \n 13 14 15 12 \n \u2518\nEnter move: \n\u2193\nOut of bounds: \u2193\n...\n", "safe": true }, { "filename": "15 puzzle game_23.txt", "content": "/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, \u00a7 22 */\n#define _CRT_SECURE_NO_WARNINGS\n#include \n#include \n#include \n#define N 4\n#define M 4\nenum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int\nupdate(enum Move m){const int dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int i=hR\n+dy[m];int j=hC+dx[m];if(i>= 0&&i=0&&j\n#include \n#include \n\nenum Move { MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_RIGHT = 3 };\n\n/* *****************************************************************************\n * Model\n */\n\n#define NROWS 4\n#define NCOLLUMNS 4\nint holeRow; \nint holeCollumn; \nint cells[NROWS][NCOLLUMNS];\nconst int nShuffles = 100;\n\nint Game_update(enum Move move){\n const int dx[] = { 0, 0, -1, +1 };\n const int dy[] = { -1, +1, 0, 0 };\n int i = holeRow + dy[move];\n int j = holeCollumn + dx[move]; \n if ( i >= 0 && i < NROWS && j >= 0 && j < NCOLLUMNS ){\n cells[holeRow][holeCollumn] = cells[i][j];\n cells[i][j] = 0; holeRow = i; holeCollumn = j;\n return 1;\n }\n return 0;\n}\n\nvoid Game_setup(void){\n int i,j,k;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ )\n cells[i][j] = i * NCOLLUMNS + j + 1;\n cells[NROWS-1][NCOLLUMNS-1] = 0;\n holeRow = NROWS - 1;\n holeCollumn = NCOLLUMNS - 1;\n k = 0;\n while ( k < nShuffles )\n k += Game_update((enum Move)(rand() % 4));\n}\n\nint Game_isFinished(void){\n int i,j; int k = 1;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ) \n if ( (k < NROWS*NCOLLUMNS) && (cells[i][j] != k++ ) )\n return 0;\n return 1; \n}\n\n\n/* *****************************************************************************\n * View \n */\n\nvoid View_showBoard(){\n int i,j;\n putchar('\\n');\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ){\n if ( cells[i][j] )\n printf(j != NCOLLUMNS-1 ? \" %2d \" : \" %2d \\n\", cells[i][j]);\n else\n printf(j != NCOLLUMNS-1 ? \" %2s \" : \" %2s \\n\", \"\");\n }\n putchar('\\n');\n}\n\nvoid View_displayMessage(char* text){\n printf(\"\\n%s\\n\", text);\n}\n\n\n/* *****************************************************************************\n * Controller\n */\n\nenum Move Controller_getMove(void){\n int c;\n for(;;){\n printf(\"%s\", \"enter u/d/l/r\u00a0: \");\n c = getchar();\n while( getchar() != '\\n' )\n ;\n switch ( c ){\n case 27: exit(EXIT_SUCCESS);\n case 'd' : return MOVE_UP; \n case 'u' : return MOVE_DOWN;\n case 'r' : return MOVE_LEFT;\n case 'l' : return MOVE_RIGHT;\n }\n }\n}\n\nvoid Controller_pause(void){\n getchar();\n}\n\nint main(void){\n\n srand((unsigned)time(NULL));\n\n do Game_setup(); while ( Game_isFinished() );\n\n View_showBoard();\n while( !Game_isFinished() ){ \n Game_update( Controller_getMove() ); \n View_showBoard(); \n }\n\n View_displayMessage(\"You win\");\n Controller_pause();\n\n return EXIT_SUCCESS;\n}\n", "safe": true }, { "filename": "15 puzzle game_25.txt", "content": " 9 1 4 7\n 6 5 3 2\n 13 10 8\n 14 15 11 12\n\nenter u/d/l/r\u00a0: u\n\n 9 1 4 7\n 6 5 3 2\n 13 10 11 8\n 14 15 12\n\nenter u/d/l/r\u00a0: l\n\n 9 1 4 7\n 6 5 3 2\n 13 10 11 8\n 14 15 12\n\nenter u/d/l/r\u00a0: d\n\n 9 1 4 7\n 6 5 3 2\n 13 10 11\n 14 15 12 8\n\nenter u/d/l/r\u00a0:", "safe": true }, { "filename": "15 puzzle game_26.txt", "content": "/**\n * RosettaCode: Fifteen puzle game, C89, MS Windows Console API, MVC\n *\n * @version 0.2 (added TTY and ncurses modes)\n */\n\n#define UNDEFINED_WIN32API_CONSOLE\n#define UNDEFINED_NCURSES_CONSOLE\n#if !defined (TTY_CONSOLE) && !defined(WIN32API_CONSOLE) && !defined(NCURSES_CONSOLE)\n#define TTY_CONSOLE\n#endif\n\n#define _CRT_SECURE_NO_WARNINGS /* enable printf etc. */\n#define _CRT_NONSTDC_NO_DEPRECATE /* POSIX functions enabled */\n\n#include \n#include \n#include \n#include \n#if defined(NCURSES_CONSOLE)\n#include \"curses.h\" /* see http://pdcurses.sourceforge.net/ */\n#elif defined(WIN32API_CONSOLE)\n#define NOGDI /* we don't need GDI */\n#define WIN32_LEAN_AND_MEAN /* we don't need OLE etc. */\n#include /* MS Windows stuff */\n#include /* kbhit() and getch() */\n#endif\n\nenum Move { MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_RIGHT = 3 };\n\n/* *****************************************************************************\n * Model\n */\n\n#define NROWS 4\n#define NCOLLUMNS 4\nint holeRow; \nint holeCollumn; \nint cells[NROWS][NCOLLUMNS];\nconst int nShuffles = 100;\n\nint Game_update(enum Move move){\n const int dx[] = { 0, 0, -1, +1 };\n const int dy[] = { -1, +1, 0, 0 };\n int i = holeRow + dy[move];\n int j = holeCollumn + dx[move]; \n if ( i >= 0 && i < NROWS && j >= 0 && j < NCOLLUMNS ){\n cells[holeRow][holeCollumn] = cells[i][j];\n cells[i][j] = 0; holeRow = i; holeCollumn = j;\n return 1;\n }\n return 0;\n}\n\nvoid Game_setup(void){\n int i,j,k;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ )\n cells[i][j] = i * NCOLLUMNS + j + 1;\n cells[NROWS-1][NCOLLUMNS-1] = 0;\n holeRow = NROWS - 1;\n holeCollumn = NCOLLUMNS - 1;\n k = 0;\n while ( k < nShuffles )\n k += Game_update((enum Move)(rand() % 4));\n}\n\nint Game_isFinished(void){\n int i,j; int k = 1;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ) \n if ( (k < NROWS*NCOLLUMNS) && (cells[i][j] != k++ ) )\n return 0;\n return 1; \n}\n\n\n/* *****************************************************************************\n * View \n */\n\nint fieldWidth;\n#ifdef WIN32API_CONSOLE\nHANDLE hConsole;\nCONSOLE_SCREEN_BUFFER_INFO csbi; \n#endif\n\nvoid View_setup_base(void)\n{\n int i;\n fieldWidth = 0;\n for ( i = NROWS * NCOLLUMNS - 1; i > 0; i /= 10 )\n fieldWidth++;\n}\n\n#if defined(TTY_CONSOLE)\n\nvoid View_setup(void) {\n View_setup_base();\n}\n\nvoid View_showBoard()\n{\n int i,j;\n putchar('\\n');\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ){\n if ( cells[i][j] )\n printf(j != NCOLLUMNS-1 ? \"\u00a0%*d \" : \"\u00a0%*d \\n\", fieldWidth, cells[i][j]);\n else\n printf(j != NCOLLUMNS-1 ? \"\u00a0%*s \" : \"\u00a0%*s \\n\", fieldWidth, \"\");\n }\n putchar('\\n');\n}\n\nvoid View_displayMessage(char* text)\n{\n printf(\"\\n%s\\n\", text);\n}\n\n#elif defined(NCURSES_CONSOLE)\n\nvoid View_setup(void) {\n View_setup_base();\n initscr(); \n clear();\n}\n\nvoid View_showBoard()\n{\n int i,j;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ){\n int x = (fieldWidth+1)*j;\n int y = 2*i;\n if ( cells[i][j] ){\n attron(A_REVERSE);\n mvprintw(y,x,\"%*d\", fieldWidth, cells[i][j]);\n }else{\n attroff(A_REVERSE);\n mvprintw(y,x,\"%*s\", fieldWidth, \" \");\n }\n }\n attrset(A_NORMAL);\n}\n\nvoid View_displayMessage(char* text)\n{\n mvprintw(2*NROWS,0, \"%s\", text);\n}\n\n#elif defined(WIN32API_CONSOLE)\n\nvoid View_setup(void) {\n const COORD coordHome = { 0, 0 }; \n CONSOLE_CURSOR_INFO cci;\n DWORD size, nWritten;\n View_setup_base();\n hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\n cci.bVisible = FALSE; \n cci.dwSize = 1;\n SetConsoleCursorInfo(hConsole,&cci); \n GetConsoleScreenBufferInfo(hConsole,&(csbi));\n size = csbi.dwSize.X*csbi.dwSize.Y;\n FillConsoleOutputCharacter(hConsole,' ',size,coordHome,&nWritten);\n FillConsoleOutputAttribute(hConsole,csbi.wAttributes,size,coordHome,&nWritten);\n\n}\n\nvoid View_showBoard()\n{\n int i,j;\n char labelString[32];\n WORD attributes;\n DWORD nWritten;\n for ( i = 0; i < NROWS; i++ )\n for ( j = 0; j < NCOLLUMNS; j++ ){\n COORD coord = { ((SHORT)fieldWidth+1)*j, coord.Y = 2*i };\n if ( cells[i][j] ){\n sprintf(labelString,\"%*d\", fieldWidth, cells[i][j]); \n attributes = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;\n }else{\n sprintf(labelString,\"%*s\", fieldWidth, \" \");\n attributes = csbi.wAttributes;\n }\n WriteConsoleOutputCharacter(hConsole,labelString,fieldWidth,coord,&nWritten);\n FillConsoleOutputAttribute (hConsole,attributes,fieldWidth,coord,&nWritten);\n }\n}\n\nvoid View_displayMessage(char* text)\n{\n DWORD nWritten;\n COORD coord = { 0, 2 * NROWS };\n WriteConsoleOutputCharacter(hConsole,text,strlen(text),coord,&nWritten);\n}\n\n#endif\n\n\n/* *****************************************************************************\n * Controller\n */\n\n#if defined(TTY_CONSOLE)\n\nvoid Controller_setup(void){\n}\n\nenum Move Controller_getMove(void){\n int c;\n for(;;){\n printf(\"%s\", \"enter u/d/l/r\u00a0: \");\n c = getchar();\n while( getchar() != '\\n' )\n ;\n switch ( c ){\n case 27: exit(EXIT_SUCCESS);\n case 'd' : return MOVE_UP; \n case 'u' : return MOVE_DOWN;\n case 'r' : return MOVE_LEFT;\n case 'l' : return MOVE_RIGHT;\n }\n }\n}\n\nvoid Controller_pause(void)\n{\n getchar();\n}\n\n#elif defined(NCURSES_CONSOLE)\n\nvoid Controller_setup(void){\n noecho();\n cbreak();\n curs_set(0);\n keypad(stdscr,TRUE);\n}\n\nenum Move Controller_getMove(void){\n for(;;){\n switch ( wgetch(stdscr) ){\n case 27: exit(EXIT_SUCCESS);\n case KEY_DOWN : return MOVE_UP; \n case KEY_UP : return MOVE_DOWN;\n case KEY_RIGHT : return MOVE_LEFT;\n case KEY_LEFT : return MOVE_RIGHT;\n case ERR: /* NOP */;\n }\n }\n}\n\nvoid Controller_pause(void){\n while ( wgetch(stdscr) == ERR )\n ;\n}\n\n\n#elif defined(WIN32API_CONSOLE)\n\nvoid Controller_setup(void){\n}\n\nenum Move Controller_getMove(void){\n for(;;){\n switch ( getch() ){\n case 27: exit(EXIT_SUCCESS);\n case 0:\n case 224: switch ( getch() ){\n case 80 : return MOVE_UP; \n case 72 : return MOVE_DOWN;\n case 77 : return MOVE_LEFT;\n case 75 : return MOVE_RIGHT;\n }\n }\n }\n}\n\nvoid Controller_pause(void){\n while( kbhit() ) getch();\n while( !kbhit() ) ;\n while( kbhit() ) getch();\n}\n\n#endif\n\n\n/* *****************************************************************************\n * Main function: create model, view and controller. Run main loop.\n */\nint main(void) {\n\n srand((unsigned)time(NULL));\n\n do Game_setup(); while ( Game_isFinished() );\n View_setup(); \n Controller_setup();\n\n View_showBoard();\n while( !Game_isFinished() ){ \n Game_update( Controller_getMove() ); \n View_showBoard(); \n }\n\n View_displayMessage(\"You win\");\n Controller_pause();\n\n return EXIT_SUCCESS;\n}\n", "safe": true }, { "filename": "15 puzzle game_27.txt", "content": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class FifteenPuzzle\n{\n const int GridSize = 4; //Standard 15 puzzle is 4x4\n const int BlockCount = 16;\n\n static readonly Random R = new Random();\n\n private List
\n \n \n \n \n \n\n

\n\n \n\n \n\n\n\n", "safe": true }, { "filename": "21 game_51.txt", "content": "function trytowin(n)\n if 21 - n < 4\n println(\"Computer chooses $(21 - n) and wins. GG!\")\n exit(0)\n end\nend\n\nfunction choosewisely(n)\n trytowin(n)\n targets = [1, 5, 9, 13, 17, 21]\n pos = findfirst(x -> x > n, targets)\n bestmove = targets[pos] - n\n if bestmove > 3\n println(\"Looks like I could lose. Choosing a 1, total now $(n + 1).\")\n return n + 1\n end\n println(\"On a roll, choosing a $bestmove, total now $(n + bestmove).\")\n n + bestmove\nend\n\nfunction choosefoolishly(n)\n trytowin(n)\n move = rand([1, 2, 3])\n println(\"Here goes, choosing $move, total now $(n + move).\")\n n + move\nend\n\nfunction choosesemiwisely(n)\n trytowin(n)\n if rand() > 0.75\n choosefoolishly(n)\n else\n choosewisely(n)\n end\nend\n\nprompt(s) = (println(s, \": => \"); return readline())\n\nfunction playermove(n)\n rang = (n > 19) ? \"1 is all\" : ((n > 18) ? \"1 or 2\" : \"1, 2 or 3\")\n choice = 0\n while true\n nstr = prompt(\"Your choice ($rang), 0 to exit\")\n if nstr == \"0\"\n exit(0)\n elseif nstr == \"1\"\n return n + 1\n elseif nstr == \"2\" && n < 20\n return n + 2\n elseif nstr == \"3\" && n < 19\n return n + 3\n end\n end\nend\n\n\nfunction play21game()\n n = 0\n level = prompt(\"Level of play (1=dumb, 3=smart)\")\n algo = choosewisely\n if level == \"1\"\n algo = choosefoolishly\n elseif level == \"2\"\n algo = choosesemiwisely\n elseif level != \"3\"\n println(\"Bad choice syntax--default to smart choice\")\n end\n whofirst = prompt(\"Does computer go first? (y or n)\")\n if whofirst[1] == 'y' || whofirst[1] == 'Y'\n n = algo(n)\n end\n while n < 21\n n = playermove(n)\n if n == 21\n println(\"Player wins! Game over, gg!\")\n break\n end\n n = algo(n)\n end\nend\n\nplay21game()\n", "safe": true }, { "filename": "21 game_52.txt", "content": "import std/num/random\nimport std/os/readline\n\neffect exit\n final ctl exit(): ()\n\ntype player\n Player\n Computer\n\nfun other(p: player): player\n match p\n Player -> Computer\n Computer -> Player\n\nfun show(p: player): string\n match p\n Player -> \"Player\"\n Computer -> \"Computer\"\n\nfun get-selection(max-int: int)\n val i = readline().trim().parse-int()\n match i\n Just(x) | x >= 1 && x <= max-int -> x\n _ ->\n println(\"Please enter a number between 1 and \" ++ max-int.show ++ \" or press q to quit\")\n get-selection(max-int)\n\nfun play(p: player, total: int)\n println(\"Total: \" ++ total.show)\n match total\n 21 ->\n // The player who reaches 21 wins the game, which is the player in the last loop\n println(p.other.show ++ \" wins!\")\n return ()\n _ -> ()\n val max = if total + 3 > 21 then 21 - total else 3\n match p\n Player ->\n println(\"Player's turn\")\n val selection = get-selection(max)\n play(p.other, total + selection)\n Computer ->\n println(\"Computer's turn\")\n val selection = (random-int() % max) + 1\n println(\"Computer chooses \" ++ selection.show)\n play(p.other, total + selection)\n\nfun main()\n with final ctl exit() ()\n \"21 is a two player game. The game is played by choosing a number (1, 2, 3) to\".println\n \"be added to the running total. The game is won by the player whose chosen number\".println\n \"causes the running total to reach exactly 21. The running total starts at zero.\".println\n \"\".println\n \"You can quit the game at any time by typing 'q'.\".println\n val playerGoesFirst = random-bool()\n val p1 = if playerGoesFirst then Player else Computer\n play(p1, 0)\n", "safe": true }, { "filename": "21 game_53.txt", "content": "gamewon = false\nrunning_total = 0\nplayer = 1\nopponent = 2\n\nwhile not gamewon do\n num = 0\n \n if player == 1 then\n opponent = 2\n repeat\n print(\"Enter a number between 1 and 3 (0 to quit):\")\n num = io.read(\"*n\")\n if num == 0 then\n os.exit()\n end\n until (num > 0) and (num <=3)\n end\n \n if player == 2 and not (gamewon) then\n opponent = 1\n if (21 - running_total <= 3) then\n num = 21 - running_total\n else\n num = math.random(1,3)\n end\n print(\"Player 2 picks number \"..num)\n end\n \n running_total = running_total + num\n print(\"Total: \"..running_total)\n \n if running_total == 21 then\n print(\"Player \"..player..\" wins!\")\n gamewon = true\n end\n \n if running_total > 21 then\n print(\"Player \"..player..\" lost...\")\n print(\"Player \"..opponent..\" wins!\")\n gamewon = true\n end\n \n if player == 1 then\n player = 2\n else player = 1 \n end\n\nend\n", "safe": true }, { "filename": "21 game_54.txt", "content": "SeedRandom[1234];\nClearAll[ComputerChoose, HumanChoose]\nComputerChoose[n_] := If[n < 18, RandomChoice[{1, 2, 3}], 21 - n]\nHumanChoose[] := ChoiceDialog[\"How many?\", {1 -> 1, 2 -> 2, 3 -> 3, \"Quit\" -> -1}]\nrunningtotal = 0;\nwhofirst = ChoiceDialog[\"Who goes first?\", {\"You\" -> 1, \"Computer\" -> 2}];\nWhile[runningtotal < 21,\n If[whofirst == 1,\n choice = HumanChoose[];\n If[choice == -1, Break[]];\n Print[\"You choose = \", choice];\n runningtotal += choice;\n Print[\"Running total = \", runningtotal];\n If[runningtotal == 21, Print[\"You won!\"]; Break[]];\n choice = ComputerChoose[runningtotal];\n Print[\"Computer choose = \", choice];\n runningtotal += choice;\n Print[\"Running total = \", runningtotal];\n If[runningtotal == 21, Print[\"Computer won!\"]; Break[]];\n ,\n choice = ComputerChoose[runningtotal];\n Print[\"Computer choose = \", choice];\n runningtotal += choice;\n Print[\"Running total = \", runningtotal];\n If[runningtotal == 21, Print[\"Computer won!\"]; Break[]];\n choice = HumanChoose[];\n If[choice == -1, Break[]];\n Print[\"You choose = \", choice];\n runningtotal += choice;\n Print[\"Running total = \", runningtotal];\n If[runningtotal == 21, Print[\"You won!\"]; Break[]];\n ];\n ]\n", "safe": true }, { "filename": "21 game_55.txt", "content": "You choose = 2\nRunning total = 2\nComputer choose = 3\nRunning total = 5\nYou choose = 3\nRunning total = 8\nComputer choose = 1\nRunning total = 9\nYou choose = 3\nRunning total = 12\nComputer choose = 1\nRunning total = 13\nYou choose = 1\nRunning total = 14\nComputer choose = 2\nRunning total = 16\nYou choose = 1\nRunning total = 17\nComputer choose = 3\nRunning total = 20\nYou choose = 1\nRunning total = 21\nYou won!", "safe": true }, { "filename": "21 game_56.txt", "content": "# 21 game.\n\nimport random\nimport strformat\nimport strutils\n\nconst\n Target = 21\n PossibleChoices: array[18..20, seq[string]] = [@[\"1\", \"2\", \"3\"], @[\"1\", \"2\"], @[\"1\"]]\n Targets = [1, 5, 9, 13, 17, 21] # Totals that a player must obtain to win.\n\n#---------------------------------------------------------------------------------------------------\n\nproc printTotal(total: int) =\n ## Print the running total.\n echo fmt\"Running total is now {total}.\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc computerPlays(total: var int) =\n ## Make the computer play.\n var choice: int\n if total in Targets:\n # No winning choice. Choose a random value.\n choice = rand(1..3)\n else:\n # Find the running total to get.\n for val in Targets:\n if val > total:\n choice = val - total\n break\n inc total, choice\n echo fmt\"I choose {choice}.\"\n printTotal(total)\n\n#---------------------------------------------------------------------------------------------------\n\nproc prompt(message: string; answers: openArray[string]): int =\n ## Prompt a message and get an answer checking its validity against possible answers.\n\n while true:\n stdout.write(message & ' ')\n try:\n result = answers.find(stdin.readLine())\n if result >= 0:\n break\n echo fmt\"Please answer one of: {answers.join(\"\", \"\")}.\"\n except EOFError:\n echo \"\"\n return # Quit.\n\n#---------------------------------------------------------------------------------------------------\n\nrandomize()\n\necho \"21 is a two player game. The game is played by choosing a number (1, 2, 3) to\\n\" &\n \"be added to the running total. The game is won by the player whose chosen number\\n\" &\n \"causes the running total to reach exactly 21. The running total starts at zero.\\n\"\necho \"You can quit the game at any time by typing 'q'.\"\n\nblock mainLoop:\n\n while true:\n var total = 0\n\n # Choose the player who will play first.\n var answer = prompt(\"Who will play first ('you', 'me')?\", [\"q\", \"you\", \"me\"])\n if answer == 0:\n echo \"Quitting game.\"\n break\n elif answer == 1:\n computerPlays(total)\n\n # Internal game loop.\n while true:\n\n # Ask player its choice.\n let choices = if total > 18: PossibleChoices[total] else: PossibleChoices[18]\n let choice = prompt(fmt\"Your choice ({choices.join(\"\", \"\")})?\", \"q\" & choices)\n if choice == 0:\n echo \"Quitting game.\"\n break mainLoop\n\n # Update running total and check if player win.\n inc total, choice\n printTotal(total)\n if total == Target:\n echo \"Congratulations, you win.\"\n break\n\n # Make computer play.\n computerPlays(total)\n if total == Target:\n echo \"Sorry, I win.\"\n break\n\n # Ask player for another game.\n answer = prompt(\"Do you want to play another game (y, n)\", [\"q\", \"y\", \"n\"])\n if answer != 1:\n echo \"Quitting game.\"\n break\n", "safe": true }, { "filename": "21 game_57.txt", "content": "21 is a two player game. The game is played by choosing a number (1, 2, 3) to\nbe added to the running total. The game is won by the player whose chosen number\ncauses the running total to reach exactly 21. The running total starts at zero.\n\nYou can quit the game at any time by typing 'q'.\nWho will play first (you, me)? x\nPlease, answer one of: q, you, me.\nWho will play first ('you', 'me')? you\nI choose 1.\nRunning total is now 1.\nYour choice (1, 2, 3)? 4\nPlease answer one of: q, 1, 2, 3.\nYour choice (1, 2, 3)? 3\nRunning total is now 4.\nI choose 1.\nRunning total is now 5.\nYour choice (1, 2, 3)? 3\nRunning total is now 8.\nI choose 1.\nRunning total is now 9.\nYour choice (1, 2, 3)? 3\nRunning total is now 12.\nI choose 1.\nRunning total is now 13.\nYour choice (1, 2, 3)? 3\nRunning total is now 16.\nI choose 1.\nRunning total is now 17.\nYour choice (1, 2, 3)? 3\nRunning total is now 20.\nI choose 1.\nRunning total is now 21.\nSorry, I win.\nDo you want to play another game (y, n) y\nWho will play first (you, me)? me\nYour choice (1, 2, 3)? 1\nRunning total is now 1.\nI choose 2.\nRunning total is now 3.\nYour choice (1, 2, 3)? 2\nRunning total is now 5.\nI choose 2.\nRunning total is now 7.\nYour choice (1, 2, 3)? 2\nRunning total is now 9.\nI choose 1.\nRunning total is now 10.\nYour choice (1, 2, 3)? 3\nRunning total is now 13.\nI choose 3.\nRunning total is now 16.\nYour choice (1, 2, 3)? 1\nRunning total is now 17.\nI choose 2.\nRunning total is now 19.\nYour choice (1, 2)? 2\nRunning total is now 21.\nCongratulations, you win.\nDo you want to play another game (y, n) n\nQuitting game.\n", "safe": true }, { "filename": "21 game_58.txt", "content": "class TwentyOne {\n @quit\u00a0: Bool;\n @player_total\u00a0: Int;\n @computer_total\u00a0: Int;\n\n function\u00a0: Main(args\u00a0: String[]) ~ Nil {\n TwentyOne->New()->Play();\n }\n\n New() {\n }\n\n method\u00a0: Play() ~ Nil {\n player_first\u00a0:= Int->Random(1) = 1;\n\n \"Enter 'q' to quit\\n===\"->PrintLine();\n do {\n if(player_first) {\n PlayerTurn();\n if(<>@quit) {\n \"---\"->PrintLine();\n ComputerTurn();\n };\n }\n else {\n ComputerTurn();\n \"---\"->PrintLine();\n PlayerTurn();\n };\n \"===\"->PrintLine();\n }\n while(<>@quit);\n }\n\n method\u00a0: ComputerTurn() ~ Nil {\n input\u00a0:= Int->Random(1, 3);\n \n \"Computer choose: {$input}\"->PrintLine();\n @computer_total += input;\n\n if(@computer_total = 21) {\n \"Computer Wins!\"->PrintLine();\n @quit\u00a0:= true;\n }\n else if(@computer_total > 21) {\n \"Computer Loses.\"->PrintLine();\n @quit\u00a0:= true;\n }\n else {\n \"Computer total is {$@computer_total}.\"->PrintLine();\n };\n }\n\n method\u00a0: PlayerTurn() ~ Nil {\n input\u00a0:= GetInput();\n\n if(input = -1) {\n \"Quit\"->PrintLine();\n @quit\u00a0:= true;\n }\n else if(input = 0) {\n \"Invalid Input!\"->PrintLine();\n }\n else {\n @player_total += input;\n };\n\n if(@player_total = 21) {\n \"Player Wins!\"->PrintLine();\n @quit\u00a0:= true;\n }\n else if(@player_total > 21) {\n \"Player Loses.\"->PrintLine();\n @quit\u00a0:= true;\n }\n else {\n \"Player total is {$@player_total}.\"->PrintLine();\n };\n }\n\n function\u00a0: GetInput() ~ Int {\n \"Choosing a number beween 1-3: \"->Print();\n\n input\u00a0:= System.IO.Console->ReadString();\n if(input->Size() = 1) {\n if(input->Get(0) = 'q') {\n return -1;\n };\n\n return input->ToInt();\n };\n\n return 0;\n }\n}", "safe": true }, { "filename": "21 game_59.txt", "content": "program Game21;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n System.SysUtils,\n System.StrUtils, // for IfThen\n Winapi.Windows; // for ClearScreen\n\nconst\n HARD_MODE = True;\n\nvar\n computerPlayer: string = 'Computer';\n humanPlayer: string = 'Player 1';\n\n // for change color\n ConOut: THandle;\n BufInfo: TConsoleScreenBufferInfo;\n\nprocedure ClearScreen;\nvar\n stdout: THandle;\n csbi: TConsoleScreenBufferInfo;\n ConsoleSize: DWORD;\n NumWritten: DWORD;\n Origin: TCoord;\nbegin\n stdout := GetStdHandle(STD_OUTPUT_HANDLE);\n Win32Check(stdout <> INVALID_HANDLE_VALUE);\n Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));\n ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;\n Origin.X := 0;\n Origin.Y := 0;\n Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin, NumWritten));\n Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize,\n Origin, NumWritten));\n Win32Check(SetConsoleCursorPosition(stdout, Origin));\nend;\n\nprocedure ResetColor;\nbegin\n SetConsoleTextAttribute(ConOut, BufInfo.wAttributes);\nend;\n\nprocedure ChangeColor(color: Word);\nbegin\n ConOut := TTextRec(Output).Handle;\n GetConsoleScreenBufferInfo(ConOut, BufInfo);\n SetConsoleTextAttribute(TTextRec(Output).Handle, color);\nend;\n\nfunction SwapPlayer(currentPlayer: string): string;\nbegin\n Result := IfThen(currentPlayer = humanPlayer, computerPlayer, humanPlayer);\nend;\n\nfunction RandomPlayerSelect(): string;\nbegin\n Result := IfThen(Random() < 0.5, computerPlayer, humanPlayer);\nend;\n\nfunction CheckIfCanWin(total: Integer): Boolean;\nbegin\n result := (total >= 18);\nend;\n\nfunction CheckIfCanLose(total: Integer; var choose: Integer; hardMode: Boolean =\n False): Boolean;\nvar\n range: Integer;\nbegin\n range := 17 - total;\n Result := false;\n if (range > 0) and (range < 4) then\n begin\n Result := true;\n if hardMode then\n choose := range\n else\n choose := Random(range - 1) + 1;\n end;\nend;\n\nfunction CompMove(total: Integer): Integer;\nbegin\n if (CheckIfCanWin(total)) then\n begin\n exit(21 - total);\n end;\n\n if CheckIfCanLose(total, Result, HARD_MODE) then\n exit;\n\n Result := Random(3) + 1;\nend;\n\nfunction HumanMove: Integer;\nvar\n choice: string;\nbegin\n repeat\n Writeln('Choose from numbers: 1, 2, 3');\n Readln(choice);\n until TryStrToInt(choice, Result) and (Result in [1..3]);\nend;\n\nprocedure PlayGame();\nvar\n playAnother: Boolean;\n total, final_, roundChoice, compWins, humanWins: Integer;\n choice, currentPlayer: string;\nbegin\n playAnother := True;\n total := 0;\n final_ := 21;\n roundChoice := 0;\n Randomize;\n currentPlayer := RandomPLayerSelect();\n compWins := 0;\n humanWins := 0;\n\n while (playAnother) do\n begin\n ClearScreen;\n ChangeColor(FOREGROUND_INTENSITY or FOREGROUND_GREEN);\n Writeln(total);\n ResetColor;\n Writeln('');\n\n Writeln('Now playing: ' + currentPlayer);\n if currentPlayer = computerPlayer then\n roundChoice := CompMove(total)\n else\n roundChoice := HumanMove;\n inc(total, roundChoice);\n\n if (total = final_) then\n begin\n if (currentPlayer = computerPlayer) then\n begin\n inc(compWins);\n end\n else\n begin\n inc(humanWins);\n end;\n\n ClearScreen;\n Writeln('Winner: ' + currentPlayer);\n Writeln('Comp wins: ', compWins, '. Human wins: ', humanWins, #10);\n Writeln('Do you wan to play another round? y/n');\n\n readln(choice);\n\n if choice = 'y' then\n begin\n total := 0;\n ClearScreen;\n end\n else if choice = 'n' then\n playAnother := false\n else\n begin\n Writeln('Invalid choice! Choose from y or n');\n Continue;\n end;\n end\n else if total > 21 then\n begin\n Writeln('Not the right time to play this game\u00a0:)');\n break;\n end;\n\n currentPlayer := SwapPlayer(currentPlayer);\n end;\n\nend;\n\nconst\n WELLCOME_MSG: array[0..5] of string = ('Welcome to 21 game'#10,\n '21 is a two player game.', 'The game is played by choosing a number.',\n '1, 2, or 3 to be added a total sum.'#10,\n 'The game is won by the player reaches exactly 21.'#10, 'Press ENTER to start!'#10);\n\nvar\n i: Integer;\n\nbegin\n try\n for i := 0 to High(WELLCOME_MSG) do\n Writeln(WELLCOME_MSG[i]);\n ResetColor;\n Readln; // Wait press enter\n\n PlayGame();\n except\n on E: Exception do\n Writeln(E.ClassName, ': ', E.Message);\n end;\nend.\n", "safe": true }, { "filename": "21 game_6.txt", "content": "The first move is human move.\nThe running total is 0\nEnter your choice (1,2, 3 or type (q)uit to exit): 4\ninvalid choice.\n Enter your choice (1,2, 3 or type (q)uit to exit): 1\nRaspberry choice if 1\nThe running total is 2\nEnter your choice (1,2, 3 or type (q)uit to exit): 3\nRaspberry choice if 2\nThe running total is 7\nEnter your choice (1,2, 3 or type (q)uit to exit): 1\nRaspberry choice if 1\nThe running total is 9\nEnter your choice (1,2, 3 or type (q)uit to exit): 2\nRaspberry choice if 2\nThe running total is 13\nEnter your choice (1,2, 3 or type (q)uit to exit): 3\nRaspberry choice if 1\nThe running total is 17\nEnter your choice (1,2, 3 or type (q)uit to exit): 1\nRaspberry choice if 3\nYou lost.\n\nNew game (y/n)\u00a0?\ny\nThe first move is Raspberry pi.\n", "safe": true }, { "filename": "21 game_60.txt", "content": "print <<'HERE';\nThe 21 game. Each player chooses to add 1, 2, or 3 to a running total.\nThe player whose turn it is when the total reaches 21 wins. Enter q to quit.\nHERE\n\nmy $total = 0;\n\nwhile () {\n print \"Running total is: $total\\n\";\n my ($me,$comp);\n while () {\n print 'What number do you play> ';\n $me = <>; chomp $me;\n last if $me =~ /^[123]$/;\n insult($me);\n }\n $total += $me;\n win('Human') if $total >= 21;\n print \"Computer plays: \" . ($comp = 1+int(rand(3))) . \"\\n\";\n $total += $comp;\n win('Computer') if $total >= 21;\n}\n\nsub win {\n my($player) = @_;\n print \"$player wins.\\n\";\n exit;\n}\n\nsub insult {\n my($g) = @_;\n exit if $g =~ /q/i;\n my @insults = ('Yo mama', 'Jeez', 'Ummmm', 'Grow up');\n my $i = $insults[1+int rand($#insults)];\n print \"$i, $g is not an integer between 1 and 3...\\n\"\n}\n", "safe": true }, { "filename": "21 game_61.txt", "content": "The 21 game. Each player chooses to add 1, 2, or 3 to a running total.\nThe player whose turn it is when the total reaches 21 wins. Enter q to quit.\nRunning total is: 0\nWhat number do you play> 3\nComputer plays: 3\nRunning total is: 6\nWhat number do you play> 3\nComputer plays: 3\nRunning total is: 12\nWhat number do you play> 3\nComputer plays: 2\nRunning total is: 17\nWhat number do you play> 1\nComputer plays: 1\nRunning total is: 19\nWhat number do you play> 2\nHuman wins.", "safe": true }, { "filename": "21 game_62.txt", "content": "--\n-- demo\\rosetta\\21_Game.exw\n-- ========================\n--\nwith javascript_semantics -- DEV NORMALIZESIZE, CANFOCUS, \"You\" not checked, VALUE_HANDLE.\n -- The radio_texts simply don't do anything at all in p2js.\nconstant title = \"21 Game\",\n help_text = \"\"\"\nPlay by choosing 1, 2, or 3 to add to the running total (initially 0).\n\nThe first player to reach 21 wins.\n\nIf the computer goes first you cannot win.\n\nIf you leave your opponent on 18, 19, or 20, they will play {3,2,1} and win.\nIf you leave your opponent on 17, simply match their play {1,2,3} with {3,2,1} and win.\nIf you leave your opponent on 14, 15, or 16, they'll leave you on 17 and win.\nSo the aim is 21 (doh), and before that 17, 13, 9, 5, and 1. Anything else loses.\n\"\"\",\n radio_texts = {\"You\",\"Computer\",\"Random\"},\n button_text = {\"one\",\"two\",\"three\",\"concede\",\"new game\",\"quit\"}\ninteger total = 0\n\ninclude pGUI.e\nIhandle dlg, vbox, frame, radios, playstate\nsequence radioset, buttons\n\nfunction show_help()\n IupMessage(title,help_text)\n return IUP_IGNORE -- (don't open browser help!)\nend function\n\nfunction play(integer n)\n if n!=0 then\n if n=6 then return IUP_CLOSE end if\n string title\n if n>3 then\n -- concede or new_game\n total = 0\n title = iff(n=4?\"(conceded) \":\"\")\n title &= \"Total is 0\"\n Ihandle r = IupGetAttributePtr(radios,\"VALUE_HANDLE\")\n n = find(r,radioset)\n if n=2 or (n=3 and rand(2)=1) then\n title &= \",\" -- trigger a computer move\n end if\n IupSetInt(buttons[1..3],\"ACTIVE\",true)\n else\n -- n = 1..3\n title = sprintf(\"Total is %d\",total)\n if total=21 -- (from key_cb)\n or total+n>21 then -- (invalid)\n return IUP_IGNORE\n end if\n total += n\n title &= sprintf(\", you play %d (-> %d),\",{n,total})\n if total=21 then title &= \" you win\" end if\n end if\n if find(',',title) and total!=21 then\n -- computer move\n sequence moves = {1,rand(3),3,2}\n n = moves[mod(total,4)+1]\n total += n\n title &= sprintf(\" computer plays %d (-> %d)\",{n,total})\n if total=21 then\n title &= \", computer wins\"\n elsif mod(total,4)=1 then\n title &= \", (you've already lost)\"\n end if\n end if \n if total=21 then\n title &= \" GAME OVER\"\n IupSetInt(buttons[1..4],\"ACTIVE\",false)\n else\n if total>18 then\n IupSetInt(buttons[22-total..3],\"ACTIVE\",false)\n end if\n IupSetInt(buttons[4],\"ACTIVE\",total!=0)\n end if \n IupSetFocus(dlg) -- (stops inactive button beeping)\n IupSetStrAttribute(playstate,\"TITLE\",title)\n end if\n return IUP_IGNORE\nend function\n\nfunction button_cb(Ihandle ih)\n string title = IupGetAttribute(ih,\"TITLE\")\n return play(find(title,button_text))\nend function\nconstant cb_button = Icallback(\"button_cb\")\n\nfunction key_cb(Ihandle /*dlg*/, atom c)\n if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)\n if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)\n if c=K_F1 then return show_help() end if\n return play(find(upper(c),\"123CNQ\"))\nend function\n\nIupOpen()\nplaystate = IupLabel(\"\",\"EXPAND=HORIZONTAL, PADDING=10x10\")\nradioset = apply(true,IupToggle,{radio_texts,{\"RIGHTBUTTON=YES, CANFOCUS=NO\"}})\nbuttons = apply(true,IupButton,{button_text,cb_button,{\"PADDING=5x5\"}})\nradios = IupRadio(IupHbox(radioset,\"GAP=45\"))\nframe = IupHbox({IupLabel(`First Player:`),radios},\"NORMALIZESIZE=VERTICAL\")\nvbox = IupVbox({frame,playstate,IupHbox(buttons,\"GAP=10\")},\"MARGIN=20x10\")\ndlg = IupDialog(vbox,`TITLE=\"%s\", MINSIZE=540x200`,{title})\nIupShow(dlg)\nIupSetCallback({dlg,buttons},\"KEY_CB\",Icallback(\"key_cb\"))\nIupSetAttributeHandle(NULL,\"PARENTDIALOG\",dlg)\n{} = play(find(\"new game\",button_text))\nif platform()!=JS then\n IupMainLoop()\n IupClose()\nend if\n", "safe": true }, { "filename": "21 game_63.txt", "content": "\n\n\n\n \n \n \n \n \n \n \n \n \n 21 Game\n \n \n \n\n \n\n\n\n\n

\n 21 Game in PHP 7\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\n GOAL ? 'disabled' : '';\n\n echo <<< END\n

\n The first player is $first.\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 $message\n

\n END\n ?>\n\n\n", "safe": true }, { "filename": "21 game_64.txt", "content": "import util.\n\nmain =>\n N = 0,\n Level = prompt(\"Level of play (1=dumb, 3=smart)\"),\n Algo = choosewisely,\n if Level == \"1\" then\n Algo\u00a0:= choosefoolishly\n elseif Level == \"2\" then\n Algo\u00a0:= choosesemiwisely\n elseif Level\u00a0!= \"3\" then\n println(\"Bad choice syntax--default to smart choice\")\n end,\n Whofirst = prompt(\"Does computer go first? (y or n)\"),\n if Whofirst[1] == 'y' || Whofirst[1] == 'Y' then\n N\u00a0:= apply(Algo, N)\n end,\n while (N < 21)\n N\u00a0:= playermove(N),\n if N == 21 then\n println(\"Player wins! Game over, gg!\"),\n halt\n end,\n N\u00a0:= apply(Algo,N)\n end.\n \ntrytowin(N) =>\n if 21 - N < 4 then \n printf(\"Computer chooses %w and wins. GG!\\n\", 21 - N),\n halt\n end.\n\nchoosewisely(N) = NextN =>\n trytowin(N),\n Targets = [1, 5, 9, 13, 17, 21],\n once ((member(Target, Targets), Target > N)),\n Bestmove = Target - N,\n if Bestmove > 3 then\n printf(\"Looks like I could lose. Choosing a 1, total now %w.\\n\", N + 1),\n NextN = N+1\n else \n printf(\"On a roll, choosing a %w, total now %w.\\n\", Bestmove, N + Bestmove),\n NextN = N + Bestmove\n end.\n \nchoosefoolishly(N) = NextN =>\n trytowin(N),\n Move = random() mod 3 + 1,\n printf(\"Here goes, choosing %w, total now %w.\", Move, N+Move),\n NextN = N+Move.\n \nchoosesemiwisely(N) = NextN =>\n trytowin(N),\n if frand() > 0.75 then\n NextN = choosefoolishly(N)\n else\n NextN = choosewisely(N)\n end.\n \nprompt(S) = Input =>\n printf(S ++ \": => \"),\n Input = strip(read_line()).\n \nplayermove(N) = NextN =>\n Rang = cond(N > 19, \"1 is all\", cond(N > 18, \"1 or 2\", \"1, 2 or 3\")),\n Prompt = to_fstring(\"Your choice (%s), 0 to exit\", Rang),\n Nstr = prompt(Prompt),\n if Nstr == \"0\" then\n halt\n elseif Nstr == \"1\" then\n NextN = N+1\n elseif Nstr == \"2\" && N < 20 then\n NextN = N + 2\n elseif Nstr == \"3\" && N < 19 then\n NextN = N + 3\n else\n NextN = playermove(N)\n end.", "safe": true }, { "filename": "21 game_65.txt", "content": "from random import randint\ndef start():\n\tgame_count=0\n\tprint(\"Enter q to quit at any time.\\nThe computer will choose first.\\nRunning total is now {}\".format(game_count))\n\troundno=1\n\twhile game_count<21:\n\t\tprint(\"\\nROUND {}: \\n\".format(roundno))\n\t\tt = select_count(game_count)\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, commiserations, the computer has won!\")\n\t\t\treturn 0\n\t\tt = request_count()\n\t\tif not t:\n\t\t\tprint('OK,quitting the game')\n\t\t\treturn -1\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, congratulations, you've won!\")\n\t\t\treturn 1\n\t\troundno+=1\n\ndef select_count(game_count):\n\t'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''\n\tif game_count<18:\n\t\tt= randint(1,3)\n\telse:\n\t\tt = 21-game_count\n\tprint(\"The computer chooses {}\".format(t))\n\treturn t\n\ndef request_count():\n\t'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''\n\tt=\"\"\n\twhile True:\n\t\ttry:\n\t\t\tt = raw_input('Your choice 1 to 3\u00a0:')\n\t\t\tif int(t) in [1,2,3]:\n\t\t\t\treturn int(t)\n\t\t\telse:\n\t\t\t\tprint(\"Out of range, try again\")\n\t\texcept:\n\t\t\tif t==\"q\":\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tprint(\"Invalid Entry, try again\")\n\nc=0\nm=0\nr=True\nwhile r:\n\to = start()\n\tif o==-1:\n\t\tbreak\n\telse:\n\t\tc+=1 if o==0 else 0\n\t\tm+=1 if o==1 else 0\n\tprint(\"Computer wins {0} game, human wins {1} games\".format(c,m))\n\tt = raw_input(\"Another game?(press y to continue):\")\n\tr = (t==\"y\")\n", "safe": true }, { "filename": "21 game_66.txt", "content": "Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now 0\n\nROUND 1: \n\nThe computer chooses 1\nRunning total is now 1\n\nYour choice 1 to 3 :4\nOut of range, try again\nYour choice 1 to 3 :w\nInvalid Entry, try again\nYour choice 1 to 3 :3\nRunning total is now 4\n\n\nROUND 2: \n\nThe computer chooses 1\nRunning total is now 5\n\nYour choice 1 to 3 :2\nRunning total is now 7\n\n\nROUND 3: \n\nThe computer chooses 3\nRunning total is now 10\n\nYour choice 1 to 3 :3\nRunning total is now 13\n\n\nROUND 4: \n\nThe computer chooses 1\nRunning total is now 14\n\nYour choice 1 to 3 :2\nRunning total is now 16\n\n\nROUND 5: \n\nThe computer chooses 1\nRunning total is now 17\n\nYour choice 1 to 3 :1\nRunning total is now 18\n\n\nROUND 6: \n\nThe computer chooses 3\nRunning total is now 21\n\nSo, commiserations, the computer has won!\nComputer wins 1 game, human wins 0 games\nAnother game?(press y to continue):y\nEnter q to quit at any time.\nThe computer will choose first.\nRunning total is now 0\n\nROUND 1: \n\nThe computer chooses 1\nRunning total is now 1\n\nYour choice 1 to 3 :3\nRunning total is now 4\n\n\nROUND 2: \n\nThe computer chooses 3\nRunning total is now 7\n\nYour choice 1 to 3 :3\nRunning total is now 10\n\n\nROUND 3: \n\nThe computer chooses 3\nRunning total is now 13\n\nYour choice 1 to 3 :5\nOut of range, try again\nYour choice 1 to 3 :3\nRunning total is now 16\n\n\nROUND 4: \n\nThe computer chooses 2\nRunning total is now 18\n\nYour choice 1 to 3 :3\nRunning total is now 21\n\nSo, congratulations, you've won!\nComputer wins 1 game, human wins 1 games\nAnother game?(press y to continue):y\nEnter q to quit at any time.\nThe computer will choose first.\nRunning total is now 0\n\nROUND 1: \n\nThe computer chooses 3\nRunning total is now 3\n\nYour choice 1 to 3 :4\nOut of range, try again\nYour choice 1 to 3 :3\nRunning total is now 6\n\n\nROUND 2: \n\nThe computer chooses 3\nRunning total is now 9\n\nYour choice 1 to 3 :q\nOK,quitting the game\n", "safe": true }, { "filename": "21 game_67.txt", "content": "''' Python 3.6.5 code using Tkinter graphical user interface.\n Starting player chosen randomly. ''' \nfrom tkinter import *\nfrom tkinter import messagebox\nimport random\n\n# ************************************************\n\nclass Game:\n def __init__(self, gw):\n self.window = gw\n self.won = 0\n self.lost = 0\n self.score = 0\n self.puter_turn = None\n self.var123 = IntVar()\n self.varsub = IntVar()\n\n # top frame:\n self.top_fr = Frame(gw,\n width=600,\n height=100,\n bg='dodger blue')\n self.top_fr.pack(fill=X)\n\n self.hdg = Label(self.top_fr,\n text=' 21 Game ',\n font='arial 22 bold',\n fg='navy',\n bg='lemon chiffon')\n self.hdg.place(relx=0.5, rely=0.5,\n anchor=CENTER)\n\n self.play_btn = Button(self.top_fr,\n text='Play\\nGame',\n bd=5,\n bg='navy',\n fg='lemon chiffon',\n font='arial 12 bold',\n command=self.play_game)\n self.play_btn.place(relx=0.92, rely=0.5,\n anchor=E)\n\n self.quit_btn = Button(self.top_fr,\n text='Quit\\nGame',\n bd=5,\n bg='navy',\n fg='lemon chiffon',\n font='arial 12 bold',\n command=self.quit_game)\n self.quit_btn.place(relx=0.07, rely=0.5,\n anchor=W)\n\n # bottom frame:\n self.btm_fr = Frame(gw,\n width=600,\n height=500,\n bg='lemon chiffon')\n self.btm_fr.pack(fill=X)\n\n self.msg = Label(self.btm_fr,\n text=\"(Click 'Play' or 'Quit')\",\n font='arial 16 bold',\n fg='navy',\n bg='lemon chiffon')\n self.msg.place(relx=0.5, rely=0.1,\n anchor=CENTER)\n\n self.hdg = Label(self.btm_fr,\n text=\"Scoreboard\",\n font='arial 16 bold',\n fg='navy',\n bg='lemon chiffon')\n self.hdg.place(relx=0.5, rely=0.2,\n anchor=CENTER)\n\n self.score_msg = Label(self.btm_fr,\n text=\"0\",\n font='arial 16 bold',\n fg='navy',\n bg='dodger blue',\n width=8)\n \n self.score_msg.place(relx=0.5, rely=0.27,\n anchor=CENTER)\n\n self.ch_fr = LabelFrame(self.btm_fr,\n text='Choose a number',\n bg='dodger blue',\n fg='navy',\n bd=8,\n relief=RIDGE,\n font='arial 16 bold')\n self.ch_fr.place(relx=0.5, rely=0.5,\n anchor=CENTER)\n\n self.radio1 = Radiobutton(self.ch_fr,\n text='1',\n state='disabled',\n font='arial 16 bold',\n fg='navy',\n bg='dodger blue',\n variable=self.var123,\n value=1)\n self.radio1.pack()\n\n self.radio2 = Radiobutton(self.ch_fr,\n text='2',\n state='disabled',\n font='arial 16 bold',\n fg='navy', \n bg='dodger blue',\n variable=self.var123,\n value=2)\n self.radio2.pack()\n\n self.radio3 = Radiobutton(self.ch_fr,\n text='3',\n state='disabled',\n font='arial 16 bold ',\n fg='navy', \n bg='dodger blue',\n variable=self.var123,\n value=3)\n self.radio3.pack()\n\n self.submit_btn = Button(self.btm_fr,\n text='SUBMIT',\n state='disabled',\n bd=5,\n bg='navy',\n fg='lemon chiffon',\n font='arial 12 bold',\n command=self.submit)\n self.submit_btn.place(relx=0.5, rely=0.75,\n anchor=CENTER)\n\n self.won_lbl = Label(self.btm_fr,\n text=\"Won: 0\",\n font='arial 16 bold',\n fg='navy',\n bg='lemon chiffon')\n self.won_lbl.place(relx=0.85, rely=0.88,\n anchor=W)\n\n self.lost_lbl = Label(self.btm_fr,\n text=\"Lost: 0\",\n font='arial 16 bold',\n fg='navy',\n bg='lemon chiffon')\n self.lost_lbl.place(relx=0.85, rely=0.93,\n anchor=W)\n\n # play one game: \n def play_game(self):\n self.play_btn.config(state='disabled')\n # pick who goes first randomly:\n self.puter_turn = random.choice([True, False])\n self.score = 0\n self.score_msg.config(text=self.score)\n if not self.puter_turn:\n m = 'your turn'\n self.msg.config(text=m)\n # alternate turns until 21 is reached:\n while self.score != 21:\n if self.puter_turn:\n self.puter_plays()\n else:\n self.user_plays()\n self.puter_turn = not self.puter_turn\n self.play_btn.config(state='normal')\n return\n\n # computer picks a number:\n def puter_plays(self):\n if self.score == 20:\n x = 1\n elif self.score == 19:\n x = random.choice([1, 2])\n else:\n x = random.choice([1, 2, 3])\n self.score += x\n self.score_msg.config(text=self.score)\n if self.score == 21:\n m = 'Computer won!'\n self.lost += 1\n self.lost_lbl.config(text='Lost: ' + str(self.lost))\n else:\n m = 'Computer chose ' + str(x) + ', your turn'\n self.msg.config(text=m)\n return\n\n # user picks a number:\n def user_plays(self):\n self.set_user_state('normal')\n while True:\n # wait for submit button to be pressed:\n self.submit_btn.wait_variable(self.varsub)\n x = self.var123.get()\n if x + self.score > 21:\n m = 'Score cannot exceed 21, try again'\n messagebox.showerror('Error', m)\n elif x not in (1,2,3):\n m = 'No selection made'\n messagebox.showerror('Error', m)\n else:\n break\n self.score += x\n if self.score == 21:\n m = 'You won!'\n self.msg.config(text=m)\n self.score_msg.config(text=self.score)\n self.won += 1\n self.won_lbl.config(text='Won: ' + str(self.won))\n # reset and disable radio buttons: \n self.var123.set(0) \n self.set_user_state('disabled') \n return\n\n # set radio buttons to 'disabled' or 'normal':\n def set_user_state(self, state):\n self.radio1.config(state=state)\n self.radio2.config(state=state)\n self.radio3.config(state=state)\n self.submit_btn.config(state=state)\n return\n \n \n def quit_game(self):\n self.window.destroy()\n\n # indicate that submit button was pressed:\n def submit(self):\n self.varsub.set(0)\n\n# ************************************************\n\nroot = Tk()\nroot.title('21 Game')\nroot.geometry('600x600+100+50')\nroot.resizable(False, False)\ng = Game(root)\nroot.mainloop()\n", "safe": true }, { "filename": "21 game_68.txt", "content": " [ say\n \"Who goes first: Computer, Player\"\n say \" or Random?\" cr\n [ $ \"Enter C, P or R: \" input\n dup size 1\u00a0!= iff drop again\n 0 peek\n dup char C = iff [ drop 0 ] done\n dup char P = iff [ drop 1 ] done\n char R = iff [ 2 random ] done\n again ]\n cr\n dup iff [ say \"You go first.\" ]\n else [ say \"I will go first.\" ]\n cr ] is chooseplayer ( --> n )\n\n forward is player ( n --> n x )\n\n [ [ dup 17 > iff 1 done\n 4 over 4 mod\n dup 0 = if [ drop 3 ]\n - ]\n dup say \"Computer chooses \" echo\n say \".\" cr\n + ' player ] is computer ( n --> n x )\n\n [ say \"Choose 1 2 or 3 (running \"\n $ \"total must not exceed 21, Q to quit): \" input\n dup $ \"Q\" = iff [ drop 21 999 ] done\n trim reverse trim reverse\n $->n not iff drop again\n dup 1 4 within not iff drop again\n 2dup + 21 > iff drop again\n + ' computer ] resolves player ( n --> n x )\n\n [ say \"The player who makes 21 loses.\" cr\n 0 chooseplayer\n iff [ ' player ] else [ ' computer ]\n [ say \"Running total is \"\n over echo say \".\" cr cr\n do\n over 21 = until ]\n cr\n dup 999 = iff\n [ drop 2drop say \"Quitter!\" ] done\n ' computer = iff\n [ say \"The computer won!\" ]\n else [ say \"You won! Well done!\" ]\n drop ] is play ( --> )", "safe": true }, { "filename": "21 game_69.txt", "content": "/O> play\n... \nThe player who makes 21 loses.\nWho goes first: Computer, Player or Random?\nEnter C, P or R: C\n\nI will go first.\nRunning total is 0.\n\nComputer chooses 1.\nRunning total is 1.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): Q\n\nQuitter!\nStack empty.\n\n/O> play\n... \nThe player who makes 21 loses.\nWho goes first: Computer, Player or Random?\nEnter C, P or R: R\n\nYou go first.\nRunning total is 0.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 2\nRunning total is 2.\n\nComputer chooses 2.\nRunning total is 4.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 3\nRunning total is 7.\n\nComputer chooses 1.\nRunning total is 8.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 1\nRunning total is 9.\n\nComputer chooses 3.\nRunning total is 12.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 4\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 1\nRunning total is 13.\n\nComputer chooses 3.\nRunning total is 16.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 3\nRunning total is 19.\n\nComputer chooses 1.\nRunning total is 20.\n\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 2\nChoose 1 2 or 3 (running total must not exceed 21, Q to quit): 1\n\nThe computer won!\nStack empty.\n\n/O> ", "safe": true }, { "filename": "21 game_7.txt", "content": "print \"-----------------------------\"\nprint \" Welcome to 21 Game\"\nprint \"-----------------------------\"\n\nplayers: [\"A\" \"B\"]\ncurrentPlayer: sample players\nnextPlayer: first players -- currentPlayer\nrunningTotal: new 0\nnum: 0\n\ngetNum: function [][\n result: strip input \"Enter a number (1,2,3) / x to exit: \"\n if result=\"x\" -> exit\n return result\n]\n\nloop.forever @[currentPlayer nextPlayer] 'plays [\n print [\"Running total:\" runningTotal]\n print [\"Player\" plays \"turn\"]\n\n num: getNum\n\n while [or? [not? numeric? num][not? contains? 1..3 to :integer num]][\n num: getNum\n ]\n\n runningTotal: runningTotal + to :integer num\n\n print \"\"\n\n if runningTotal=21 [\n print [\"Running total is 21. Player\" plays \"won!\"]\n exit\n ]\n]\n", "safe": true }, { "filename": "21 game_70.txt", "content": "game21<-function(first = c(\"player\",\"ai\",\"random\"),sleep=.5){\n state = 0\n finished = F\n turn = 1\n if(length(first)==1 && startsWith(tolower(first),\"r\")){\n first = rbinom(1,1,.5)\n }else{\n first = (length(first)>1 || startsWith(tolower(first),\"p\"))\n }\n while(!finished){\n if(turn>1 || first){\n cat(\"The total is now\",state,\"\\n\");Sys.sleep(sleep)\n while(T){\n player.move = readline(prompt = \"Enter move: \")\n if((player.move==\"1\"||player.move==\"2\"||player.move==\"3\") && state+as.numeric(player.move)<=21){\n player.move = as.numeric(player.move)\n state = state + player.move\n break\n }else if(tolower(player.move)==\"exit\"|tolower(player.move)==\"quit\"|tolower(player.move)==\"end\"){\n cat(\"Goodbye.\\n\")\n finished = T\n break\n }else{\n cat(\"Error: invaid entry.\\n\")\n }\n }\n }\n if(state == 21){\n cat(\"You win!\\n\")\n finished = T\n }\n if(!finished){\n cat(\"The total is now\",state,\"\\n\");Sys.sleep(sleep)\n while(T){\n ai.move = sample(1:3,1)\n if(state+ai.move<=21){\n break\n }\n }\n state = state + ai.move\n cat(\"The AI chooses\",ai.move,\"\\n\");Sys.sleep(sleep)\n if(state == 21){\n cat(\"The AI wins!\\n\")\n finished = T\n }\n }\n turn = turn + 1\n }\n}\n", "safe": true }, { "filename": "21 game_71.txt", "content": "game21()\n", "safe": true }, { "filename": "21 game_72.txt", "content": "The total is now 0 \nEnter move: 3\nThe total is now 3 \nThe AI chooses 2 \nThe total is now 5 \nEnter move: 3\nThe total is now 8 \nThe AI chooses 3 \nThe total is now 11 \nEnter move: 3\nThe total is now 14 \nThe AI chooses 2 \nThe total is now 16 \nEnter move: 1\nThe total is now 17 \nThe AI chooses 3 \nThe total is now 20 \nEnter move: 1\nThe total is now 21 \nYou win!", "safe": true }, { "filename": "21 game_73.txt", "content": "game21(first = \"ai\")\n", "safe": true }, { "filename": "21 game_74.txt", "content": "The total is now 0 \nThe AI chooses 2 \nThe total is now 2\nEnter move: quit\nGoodbye.\n", "safe": true }, { "filename": "21 game_75.txt", "content": "#lang racket\n\n(define limit 21)\n(define max-resp 3)\n\n(define (get-resp)\n (let loop ()\n (match (read-line)\n [(app (conjoin string? string->number) n)\n #:when (and (exact-integer? n) (<= 1 n max-resp))\n n]\n [\"q\" (exit)]\n [n (printf \"~a is not in range 1 and ~a\\n\" n max-resp)\n (loop)])))\n\n(define (win human?) (printf \"~a wins\\n\" (if human? \"Human\" \"Computer\")))\n\n(printf \"The ~a game. Each player chooses to add a number\nin range 1 and ~a to a running total.\nThe player whose turn it is when the total reaches exactly ~a wins.\nEnter q to quit.\\n\\n\" limit max-resp limit)\n\n(let loop ([total 0] [human-turn? (= 0 (random 2))])\n (define new-total\n (+ total\n (cond\n [human-turn? (printf \"Running total is: ~a\\n\" total)\n (printf \"Your turn:\\n\")\n (get-resp)]\n [else (define resp (random 1 (add1 max-resp)))\n (printf \"Computer plays: ~a\\n\" resp)\n resp])))\n (cond\n [(= new-total limit) (win human-turn?)]\n [(> new-total limit) (win (not human-turn?))]\n [else (loop new-total (not human-turn?))]))\n", "safe": true }, { "filename": "21 game_76.txt", "content": "The 21 game. Each player chooses to add an integer\nin range 1 and 3 to a running total.\nThe player whose turn it is when the total reaches exactly 21 wins.\nEnter q to quit.\n\nRunning total is: 0\nYour turn:\n1\nComputer plays: 3\nRunning total is: 4\nYour turn:\nfoo\nfoo is not an integer in range 1 and 3\nYour turn:\nbar\nbar is not an integer in range 1 and 3\nYour turn:\n3\nComputer plays: 1\nRunning total is: 8\nYour turn:\n1\nComputer plays: 1\nRunning total is: 10\nYour turn:\n1\nComputer plays: 2\nRunning total is: 13\nYour turn:\n1\nComputer plays: 3\nRunning total is: 17\nYour turn:\n1\nComputer plays: 2\nRunning total is: 20\nYour turn:\n1\nHuman wins\n", "safe": true }, { "filename": "21 game_77.txt", "content": "say qq :to 'HERE';\n The 21 game. Each player chooses to add 1, 2, or 3 to a running total.\n The player whose turn it is when the total reaches 21 wins. Enter q to quit.\n HERE\n\nmy $total = 0;\nloop {\n say \"Running total is: $total\";\n my ($me,$comp);\n loop {\n $me = prompt 'What number do you play> ';\n last if $me ~~ /^<[123]>$/;\n insult $me;\n }\n $total += $me;\n win('Human') if $total >= 21;\n say \"Computer plays: { $comp = (1,2,3).roll }\\n\";\n $total += $comp;\n win('Computer') if $total >= 21;\n}\n\nsub win ($player) {\n say \"$player wins.\";\n exit;\n}\n\nsub insult ($g) {\n exit if $g eq 'q';\n print ('Yo mama,', 'Jeez,', 'Ummmm,', 'Grow up,', 'Did you even READ the instructions?').roll;\n say \" $g is not an integer between 1 & 3...\"\n}\n", "safe": true }, { "filename": "21 game_78.txt", "content": "The 21 game. Each player chooses to add 1, 2, or 3 to a running total.\nThe player whose turn it is when the total reaches 21 wins. Enter q to quit.\n\nRunning total is: 0\nWhat number do you play> 5\nDid you even READ the instructions? 5 is not an integer between 1 & 3...\nWhat number do you play> g\nYo mama, g is not an integer between 1 & 3...\nWhat number do you play> 12\nJeez, 12 is not an integer between 1 & 3...\nWhat number do you play> 3\nComputer plays: 2\n\nRunning total is: 5\nWhat number do you play> 3\nComputer plays: 3\n\nRunning total is: 11\nWhat number do you play> 1\nComputer plays: 1\n\nRunning total is: 13\nWhat number do you play> 3\nComputer plays: 2\n\nRunning total is: 18\nWhat number do you play> 3\nHuman wins.", "safe": true }, { "filename": "21 game_79.txt", "content": "/*REXX program plays the 21 game with a human, each player chooses 1, 2, or 3 which */\n/*\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 is added to the current sum, the first player to reach 21 exactly wins.*/\nsep= copies('\u2500', 8); sep2= \" \"copies('\u2550', 8)\" \" /*construct an eye\u2500catching msg fences.*/\nsay sep 'Playing the 21 game.' /*tell what's happening here at the zoo*/\n$=0; goal= 21 /*the sum [or running total] (so far).*/\n do j=1 while $1 then call ser \"Number can't be zero: \" x\n if x>3 then call ser \"Number is too large (>3): \" x\n if bad then iterate /*Had an error? Then get another number*/\n x= x/1; if $+x>goal then call ser \"Number will cause the sum to exceed \" goal': ' x\n end /*until*/; return\n", "safe": true }, { "filename": "21 game_8.txt", "content": "-----------------------------\n Welcome to 21 Game\n-----------------------------\nRunning total: 0 \nPlayer B turn \nEnter a number (1,2,3) / x to exit: 1\n\nRunning total: 1 \nPlayer A turn \nEnter a number (1,2,3) / x to exit: 2\n\nRunning total: 3 \nPlayer B turn \nEnter a number (1,2,3) / x to exit: 1\n\nRunning total: 4 \nPlayer A turn \nEnter a number (1,2,3) / x to exit: 3\n\nRunning total: 7 \nPlayer B turn \nEnter a number (1,2,3) / x to exit: 4\nEnter a number (1,2,3) / x to exit: 2\n\nRunning total: 9 \nPlayer A turn \nEnter a number (1,2,3) / x to exit: 3\n\nRunning total: 12 \nPlayer B turn \nEnter a number (1,2,3) / x to exit: 1\n\nRunning total: 13 \nPlayer A turn \nEnter a number (1,2,3) / x to exit: 2\n\nRunning total: 15 \nPlayer B turn \nEnter a number (1,2,3) / x to exit: 3\n\nRunning total: 18 \nPlayer A turn \nEnter a number (1,2,3) / x to exit: 3\n\nRunning total is 21. Player A won!", "safe": true }, { "filename": "21 game_80.txt", "content": "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Playing the 21 game.\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a number from 0 \u2500\u2500\u2500\u25ba 3 (or Quit):\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [A value of 0 (zero) means you want the computer to go first.]\n3 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 3 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer chooses 2 as its choice.\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 5 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a number from 1 \u2500\u2500\u2500\u25ba 3 (or Quit):\n3 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 8 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer chooses 1 as its choice.\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 9 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a number from 1 \u2500\u2500\u2500\u25ba 3 (or Quit):\n3 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 12 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer chooses 1 as its choice.\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 13 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a number from 1 \u2500\u2500\u2500\u25ba 3 (or Quit):\n3 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 16 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer chooses 1 as its choice.\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 17 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Please enter a number from 1 \u2500\u2500\u2500\u25ba 3 (or Quit):\n1 \u25c4\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0 user input\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 18 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer chooses 3 as its choice.\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The game total is now \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 21 \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 The computer has won the 21 game.\n", "safe": true }, { "filename": "21 game_81.txt", "content": "# Project\u00a0: 21 Game\n\nload \"guilib.ring\"\n\nlimit = 21\nposold = 0\nbutton = list(limit)\nmynum = list(3)\nyournum = list(3)\n\nnew qapp \n {\n win1 = new qwidget() {\n setwindowtitle(\"21 Game\")\n setgeometry(100,100,1000,600)\n label1 = new qlabel(win1) {\n setgeometry(10,10,1000,600)\n settext(\"\")\n }\n\n label2 = new qlabel(win1) {\n setgeometry(240,50,120,40)\n setAlignment(Qt_AlignHCenter)\n setFont(new qFont(\"Verdana\",12,100,0))\n settext(\"my number:\")\n }\n\n label3 = new qlabel(win1) {\n setgeometry(640,50,120,40)\n setAlignment(Qt_AlignHCenter)\n setFont(new qFont(\"Verdana\",12,100,0))\n settext(\"your number:\")\n }\n\n for p = 1 to 3\n mynum[p] = new qpushbutton(win1) {\n setgeometry(200+p*40,100,40,40)\n setstylesheet(\"background-color:orange\")\n settext(string(p))\n setclickevent(\"choose(\" + string(p) + \",1)\")\n }\n next\n\n for p = 1 to 3\n yournum[p] = new qpushbutton(win1) {\n setgeometry(600+p*40,100,40,40)\n setstylesheet(\"background-color:white\")\n settext(string(p))\n setclickevent(\"choose(\" + string(p) + \",2)\")\n }\n next\n\n for n = 1 to limit\n button[n] = new qpushbutton(win1) {\n setgeometry(40+n*40,190,40,40)\n settext(string(n))\n }\n next\n show()\n }\n exec()\n }\n\nfunc choose(ch,ym)\n pos = posold + ch\n if pos > limit\n msg = \"You must choose number from 1 to \" + string(limit - posold)\n msgBox(msg)\n for n = 1 to 3\n mynum[n].setenabled(false)\n yournum[n].setenabled(false)\n next\n return\n ok\n for n = posold+1 to pos\n if ym = 1\n button[n] { setstylesheet(\"background-color:orange\") }\n else\n button[n] { setstylesheet(\"background-color:white\") }\n ok\n next\n posold = pos\n if ym = 1\n for n = 1 to 3\n mynum[n].setenabled(false)\n yournum[n].setenabled(true)\n next\n else\n for n = 1 to 3\n mynum[n].setenabled(true)\n yournum[n].setenabled(false)\n next\n ok\n if pos = 21\n if ym = 1\n msgBox(\"I won!\")\n else\n msgBox(\"You won!\")\n ok\n ok\n\nfunc msgBox(text) {\n\tm = new qMessageBox(win1) {\n\t setWindowTitle(\"21 Game\")\n\t setText(text)\n\t show()\n\t }\n }", "safe": true }, { "filename": "21 game_82.txt", "content": "# 21 Game - an example in Ruby for Rosetta Code.\n\nGOAL = 21\nMIN_MOVE = 1\nMAX_MOVE = 3\n\nDESCRIPTION = \"\n*** Welcome to the 21 Game! ***\n21 is a two player game.\nEach player chooses to add 1, 2 or 3 to a running total.\nThe player whose turn it is when the total reaches 21 will win the game.\nThe running total starts at zero.\n\nThe players start the game in turn.\nEnter q to quit at any time.\n\"\n\n#\n# Returns the best move to play.\n#\ndef best_move(total)\n move = rand(1..3)\n MIN_MOVE.upto(MAX_MOVE) do |i|\n move = i if (total + i - 1) % (MAX_MOVE + 1) == 0\n end\n MIN_MOVE.upto(MAX_MOVE) do |i|\n move = i if total + i == GOAL\n end\n move\nend\n\n#\n# Gets the move of the player.\n#\ndef get_move\n print \"Your choice between #{MIN_MOVE} and #{MAX_MOVE}: \"\n answer = gets\n move = answer.to_i\n until move.between?(MIN_MOVE, MAX_MOVE)\n exit if answer.chomp == 'q'\n print 'Invalid choice. Try again: '\n answer = gets\n move = answer.to_i\n end\n move\nend\n\n#\n# Asks the player to restart a game and returns the answer.\n#\ndef restart?\n print 'Do you want to restart (y/n)? '\n restart = gets.chomp\n until ['y', 'n'].include?(restart)\n print 'Your answer is not a valid choice. Try again: '\n restart = gets.chomp\n end\n restart == 'y'\nend\n\n#\n# Run a game. The +player+ argument is the player that starts:\n# * 1 for human\n# * 0 for computer\n#\ndef game(player)\n total = round = 0\n while total < GOAL\n round += 1\n puts \"--- ROUND #{round} ---\\n\\n\"\n player = (player + 1) % 2\n if player == 0\n move = best_move(total)\n puts \"The computer chooses #{move}.\"\n else\n move = get_move\n end\n total += move\n puts \"Running total is now #{total}.\\n\\n\"\n end\n if player == 0\n puts 'Sorry, the computer has won!'\n return false\n end\n puts 'Well done, you have won!'\n true\nend\n\n# MAIN\nputs DESCRIPTION\nrun = true\ncomputer_wins = human_wins = 0\ngames_counter = player = 1\nwhile run\n puts \"\\n=== START GAME #{games_counter} ===\"\n player = (player + 1) % 2\n if game(player)\n human_wins += 1\n else\n computer_wins += 1\n end\n puts \"\\nComputer wins #{computer_wins} games, you wins #{human_wins} game.\"\n games_counter += 1\n run = restart?\nend\nputs 'Good bye!'\n", "safe": true }, { "filename": "21 game_83.txt", "content": "use rand::Rng;\nuse std::io;\n\n#[derive(Clone)]\nenum PlayerType {\n Human,\n Computer,\n}\n\n#[derive(Clone)]\nstruct Player {\n name: String,\n wins: u32, // holds wins\n level: u32, // difficulty level of Computer\n player_type: PlayerType, \n}\n\ntrait Choose {\n fn choose(&self, game: &Game) -> u8;\n}\n\nimpl Player {\n fn new(name: &str, player_type: PlayerType, level: u32) -> Player {\n Player {\n name: String::from(name),\n wins: 0,\n level,\n player_type,\n }\n }\n fn get_name(&self) -> &str {\n &self.name[..]\n }\n fn get_level(&self) -> u32 {\n self.level\n }\n fn add_win(&mut self) {\n self.wins += 1\n }\n fn level_up(&mut self) {\n self.level += 1\n }\n}\n\nimpl Choose for Player {\n fn choose(&self, game: &Game) -> u8 {\n match self.player_type {\n PlayerType::Human => loop {\n let max_choice = game.max_choice();\n match max_choice {\n 1 => println!(\"Enter a number 1 to win (or quit):\"),\n _ => println!(\"Enter a number between 1 and {} (or quit):\", max_choice)\n }\n let mut guess = String::new();\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n if guess.trim() == \"quit\" {\n return 0\n }\n let guess: u8 = match guess.trim().parse() {\n Ok(num) if num >= 1 && num <= max_choice => num,\n Ok(_) => continue,\n Err(_) => continue,\n };\n return guess;\n },\n PlayerType::Computer => match self.level {\n 5 => match game.get_total() {\n total if total == 20 => 1,\n total if total == 19 => 2,\n total if total == 18 => 3,\n _ => 1,\n },\n 4 => match game.get_total() {\n total if total == 20 => 1,\n total if total == 19 => 2,\n total if total == 18 => 3,\n _ => rand::thread_rng().gen_range(1, 3),\n },\n 3 => match game.get_total() {\n total if total == 20 => 1,\n total if total == 19 => 2,\n total if total == 18 => 3,\n _ => rand::thread_rng().gen_range(1, 4),\n },\n 2 => match game.get_total() {\n total if total == 20 => 1,\n total if total == 19 => 2,\n _ => rand::thread_rng().gen_range(1, 3),\n },\n 1 => 1,\n _ => match game.get_total() {\n total if total == 20 => 1,\n total if total == 19 => 2,\n total if total == 18 => 3,\n _ => match game.get_remaining() % 4 {\n 0 => rand::thread_rng().gen_range(1, 4),\n _ => game.get_remaining() % 4,\n },\n },\n },\n }\n }\n}\n\nstruct Game {\n players: Vec,\n turn: u8, \n total: u8, \n start: u8, // determines which player goes first\n}\n\nimpl Game {\n fn init(players: &Vec) -> Game {\n Game {\n players: players.to_vec(),\n turn: 1,\n total: 0,\n start: rand::thread_rng().gen_range(0, 2),\n }\n }\n fn play(&mut self) -> &Player {\n loop {\n println!(\n \"Total now {} (remaining: {})\",\n self.get_total(),\n self.get_remaining()\n );\n {\n let player = self.whose_turn();\n println!(\"Turn: {} ({} turn)\", self.get_turn(), player.get_name());\n let choice = player.choose(&self);\n if choice == 0 {\n self.next_turn();\n break; // quit\n }\n println!(\"{} choose {}\", player.get_name(), choice);\n self.add_total(choice)\n }\n if self.get_total() >= 21 {\n break;\n }\n println!(\"\");\n self.next_turn();\n }\n self.whose_turn()\n }\n fn add_total(&mut self, choice: u8) {\n self.total += choice;\n }\n fn next_turn(&mut self) {\n self.turn += 1;\n }\n fn whose_turn(&self) -> &Player {\n let index: usize = ((self.turn + self.start) % 2).into();\n &self.players[index]\n }\n fn get_total(&self) -> u8 {\n self.total\n }\n fn get_remaining(&self) -> u8 {\n 21 - self.total\n }\n fn max_choice(&self) -> u8 {\n match self.get_remaining() {\n 1 => 1,\n 2 => 2,\n _ => 3\n }\n }\n fn get_turn(&self) -> u8 {\n self.turn\n }\n}\n\nfn main() {\n let mut game_count = 0;\n let mut players = vec![\n Player::new(\"human\", PlayerType::Human, 0),\n Player::new(\"computer\", PlayerType::Computer, 1),\n ];\n println!(\"21 Game\");\n println!(\"Press enter key to start\");\n {\n let _ = io::stdin().read_line(&mut String::new());\n }\n loop {\n game_count += 1;\n let mut game = Game::init(&players);\n let winner = game.play();\n {\n let mut index = 0;\n while index < players.len() {\n if players[index].get_name() == winner.get_name() {\n players[index].add_win();\n }\n index += 1\n }\n }\n println!(\"\\n{} won game {}\\n\", winner.get_name(), game_count);\n // limit game count\n if game_count >= 10000 {\n break;\n }\n // ask player if they want to keep on playing\n println!(\"Press enter key to play again (or quit):\");\n let mut reply = String::new();\n io::stdin()\n .read_line(&mut reply)\n .expect(\"Failed to read line\");\n if reply.trim() == \"quit\" {\n break;\n }\n // level up computer\n if winner.get_name() != \"computer\" {\n println!(\"Computer leveling up ...\");\n players[1].level_up();\n println!(\"Computer now level {}!\", players[1].get_level());\n println!(\"Beware!\\n\");\n }\n }\n println!(\"player: {} win: {}\", players[0].get_name(), players[0].wins);\n println!(\"player: {} win: {}\", players[1].get_name(), players[1].wins);\n}\n", "safe": true }, { "filename": "21 game_84.txt", "content": "object Game21 {\n\n import scala.collection.mutable.ListBuffer\n import scala.util.Random\n\n val N = 21 // the same game would also work for N other than 21...\n\n val RND = new Random() // singular random number generator; add a seed number, if you want reproducibility\n\n /** tuple: name and a play function: (rest: remaining number, last: value of opponent's last move) => new move\n */\n type Player = (String, (Int,Int) => Int)\n\n // indeed, the following could also be written using a class and instances, I've choosen a\n // more functional and math way (using tuples)...\n val playerRandom:Player = (\"RandomRobot\", { (rest, last) =>\n if (rest <= 3) rest\n else 1 + RND.nextInt(3)\n })\n val playerBest:Player = (\"BestRobot\", { (rest, last) =>\n val i = rest % 4\n if (i > 0) i else 1 + RND.nextInt(3)\n })\n val playerHuman:Player = (\"YOU\", { (rest, last) =>\n println(\"Rest: \"+rest)\n println(\"Last: \"+last)\n var in = \"\"\n while (in!=\"1\" && in!=\"2\" && in!=\"3\") {\n in = scala.io.StdIn.readLine(\"Your move (1,2,3,q)> \").trim\n if (\"q\" == in)\n throw new Exception(\"q => quit\")\n }\n in.toInt\n })\n\n /** Execute a whole game. NOTE that we're counting DOWN from N to 0!\n * @param players\n * @return list of all moves\n */\n def play(players:Seq[Player]):Seq[Int] = {\n require(players.size == 2)\n var last = -1\n var rest = N\n var p = 0 // player 0 always starts\n val l = ListBuffer[Int]() // list of all moves\n while (rest > 0) {\n last = players(p)._2(rest,last)\n require(1<=last && last<=3,\"Player must always play 1,2,3: \"+last)\n l += last\n rest -= last\n p = 1 - p // other player's turn\n }\n l.toSeq\n }\n\n /** Evaluate a whole game.\n * @param game list of moves of one game\n * @param rest mainly for recursion\n * @return evaluation, for each move a tuple: (rest, what was played, whether this player won in the end)\n */\n def evaluate(game:Seq[Int],rest:Int=N):Seq[(Int,Int,Boolean)] = {\n if (game.size == 0) Seq()\n else Seq((rest,game.head,game.size%2 == 1)) ++ evaluate(game.tail,rest - game.head)\n }\n\n def main(args: Array[String]): Unit = {\n // here you can put whatever player combination you like\n val players = Seq(playerRandom,playerRandom) // random robot vs random robot\n //val players = Seq(playerRandom,playerBest) // random robot vs best robot\n //val players = Seq(playerHuman,playerBest) // You vs best robot\n var p0won = 0\n val n = 1000 // number of games to play\n var m = 0 // games actually played (a human player might quit before n)\n try {\n (1 to n).foreach { i =>\n val g = play(players)\n require(g.sum == N) // some validity checks\n val e = evaluate(g)\n require(e.size == g.size && e.last._3 && e(0)._3 != e(1)._3) // some validity checks\n if (e(0)._3) p0won += 1\n m += 1\n println(i + \": \" + players(0)._1 + \" \" + (if (e(0)._3) \"won\" else \"lost\") + \" against \" + players(1)._1 + \". \" + g + \" => \" + e)\n }\n } catch {\n case t:Throwable => println(t.getMessage)\n }\n println(\"Player0: \"+players(0)._1)\n println(\"Player1: \"+players(1)._1)\n println(f\"Player0 won ${p0won} times out of ${m}, or ${p0won * 100.0 / m}%%\")\n }\n}\n", "safe": true }, { "filename": "21 game_85.txt", "content": "dim @p(4) \n\npush 1, 1, 3, 2\nfor i = 3 to 0 step -1\u00a0: @p(i) = pop()\u00a0: next\na = 0\u00a0: t = rnd(2)\n \ndo while s < 21\n t = 1 - t\n print using \"The sum is _#\"; s\n if t = 1 then\n print \"It is your turn.\"\n do \n while (a < 1) + (a > 3) + (a+s > 21)\n input \"How many would you like to add? \", a\n loop\n else\n print \"It is the computer's turn.\"\n a = @p(s\u00a0% 4)\n print using \"The computer adds #.\"; a\n endif\n\n print\n s = s + a\n a = 0\nloop\n \nif t = 1 then\n print \"Congratulations. You win.\"\nelse\n print \"Bad luck. The computer wins.\"\nendif\n", "safe": true }, { "filename": "21 game_86.txt", "content": "' Game 21 in VB.NET - an example for Rosetta Code\n\nClass MainWindow\n Private Const GOAL As Integer = 21\n Private total As Integer = 0\n Private random As New Random\n\n Private Sub Update(box As TextBox, player As String, move As Integer)\n total = total + move\n box.Text = move\n boxTotal.Text = total\n If total + 1 > GOAL Then button1.IsEnabled = False\n If total + 2 > GOAL Then button2.IsEnabled = False\n If total + 3 > GOAL Then button3.IsEnabled = False\n If total = GOAL Then\n winner.Content = $\"The winner is {player}.\"\n End If\n End Sub\n\n Private Sub Ai()\n Dim move As Integer = 1\n For i = 1 To 3\n If (total + i - 1) Mod 4 = 0 Then move = i\n Next i\n For i = 1 To 3\n If total + i = GOAL Then move = i\n Next i\n Update(boxAI, \"AI\", move)\n End Sub\n\n Private Sub Choice(sender As Object, e As RoutedEventArgs) _\n Handles button1.Click, button2.Click, button3.Click\n Update(boxHuman, \"human\", sender.Content)\n If total < GOAL Then Ai()\n End Sub\n\n ' StartGame method handles both OnLoad (WM_INIT?) event \n ' as well as the restart of the game after user press the 'restart' button.\n '\n Private Sub StartGame(sender As Object, e As RoutedEventArgs) Handles restart.Click\n\n total = 0\n\n boxAI.Text = \"\"\n boxHuman.Text = \"\"\n boxTotal.Text = \"\"\n 'first.Content = \"\" ' It is not necessary, see below.\n winner.Content = \"\"\n\n button1.IsEnabled = True\n button2.IsEnabled = True\n button3.IsEnabled = True\n\n ' The random.Next(2) return pseudorandomly either 0 or 1. Generally\n ' random.Next(n) Return a value from 0 (inclusive) To n - 1 (inclusive).\n '\n If random.Next(2) = 0 Then\n first.Content = \"First player is AI player.\"\n Ai()\n Else\n first.Content = \"First player is human player.\"\n End If\n End Sub\nEnd Class\n", "safe": true }, { "filename": "21 game_87.txt", "content": "\n \n \n Game 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total.\n The game is won by the player whose chosen number causes the running total to reach exactly 21.\n The running total starts at zero.\n \n