"}}},{"rowIdx":78111,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game/Solve"},"task_name":{"kind":"string","value":"24 game/Solve"},"task_description":{"kind":"string","value":"task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\n\n\nRelated task\n\n Arithmetic Evaluator\n\n"},"language_url":{"kind":"string","value":"#Factor"},"language_name":{"kind":"string","value":"Factor"},"code":{"kind":"string","value":"USING: continuations grouping io kernel math math.combinatorics\nprettyprint quotations random sequences sequences.deep ;\nIN: rosetta-code.24-game\n \n: 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ;\n \n: expressions ( digits -- exprs )\n all-permutations [ [ + - * / ] 3 selections\n [ append ] with map ] map flatten 7 group ;\n \n: 24= ( exprs -- )\n >quotation dup call( -- x ) 24 = [ . ] [ drop ] if ;\n \n: 24-game ( -- )\n 4digits dup \"The numbers: \" write . \"The solutions: \"\n print expressions [ [ 24= ] [ 2drop ] recover ] each ;\n \n24-game"}}},{"rowIdx":78112,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_game"},"task_name":{"kind":"string","value":"15 puzzle game"},"task_description":{"kind":"string","value":" \n\n\nTask\n\nImplement the Fifteen Puzzle Game.\n\n\n\nThe 15-puzzle is also known as:\n\n Fifteen Puzzle\n Gem Puzzle\n Boss Puzzle\n Game of Fifteen\n Mystic Square\n 14-15 Puzzle\n and some others.\n\n\nRelated Tasks\n\n 15 Puzzle Solver\n 16 Puzzle Game\n\n"},"language_url":{"kind":"string","value":"#11l"},"language_name":{"kind":"string","value":"11l"},"code":{"kind":"string","value":"T Puzzle\n position = 0\n [Int = String] items\n \n F main_frame()\n V& d = .items\n print(‘+-----+-----+-----+-----+’)\n print(‘|#.|#.|#.|#.|’.format(d[1], d[2], d[3], d[4]))\n print(‘+-----+-----+-----+-----+’)\n print(‘|#.|#.|#.|#.|’.format(d[5], d[6], d[7], d[8]))\n print(‘+-----+-----+-----+-----+’)\n print(‘|#.|#.|#.|#.|’.format(d[9], d[10], d[11], d[12]))\n print(‘+-----+-----+-----+-----+’)\n print(‘|#.|#.|#.|#.|’.format(d[13], d[14], d[15], d[16]))\n print(‘+-----+-----+-----+-----+’)\n \n F format(=ch)\n ch = ch.trim(‘ ’)\n I ch.len == 1\n R ‘ ’ch‘ ’\n E I ch.len == 2\n R ‘ ’ch‘ ’\n E\n assert(ch.empty)\n R ‘ ’\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 == ‘ 16 ’\n .items[a] = ‘ ’\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(‘ ’)))\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 != ‘ ’\n I a == Int(b.trim(‘ ’))\n flag = 1B\n E\n flag = 0B\n R flag\n \nV g = Puzzle()\ng.build_board(Int(input(\"Enter the difficulty : 0 1 2\\n2 => highest 0 => lowest\\n\")))\ng.main_frame()\nprint(‘Enter 0 to exit’)\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(‘ ’)))\n print(i.trim(‘ ’)\" \\t\", end' ‘’)\n print()\n V x = Int(input())\n I x == 0\n L.break\n E I x !C lst1\n print(‘Wrong move’)\n E\n g.change(x)\n g.main_frame()\n I g.game_over()\n print(‘You WON’)\n L.break"}}},{"rowIdx":78113,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/2048"},"task_name":{"kind":"string","value":"2048"},"task_description":{"kind":"string","value":"Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\n\n\nRules of the game\n\n The rules are that on each turn the player must choose a direction (up, down, left or right).\n All tiles move as far as possible in that direction, some move more than others. \n Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers. \n A move is valid when at least one tile can be moved, if only by combination. \n A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one). \n Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.\n To win, the player must create a tile with the number 2048. \n The player loses if no valid moves are possible.\n\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\n\n\nRequirements\n\n \"Non-greedy\" movement. \n The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n That is to say, that moving the tile row of:\n [2][2][2][2] \n\n to the right should result in: \n ......[4][4] \n\n and not:\n .........[8] \n\n \"Move direction priority\". \n If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n For example, moving the tile row of:\n ...[2][2][2] \n\n to the right should result in:\n ......[2][4] \n\n and not:\n ......[4][2] \n\n\n\n Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.\n Check for a win condition.\n Check for a lose condition.\n\n"},"language_url":{"kind":"string","value":"#ARM_Assembly"},"language_name":{"kind":"string","value":"ARM Assembly"},"code":{"kind":"string","value":" \n/* ARM assembly Raspberry PI */\n/* program 2048.s */ \n \n/* REMARK 1 : 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.equ STDIN, 0 @ Linux input console\n.equ READ, 3 @ Linux syscall\n.equ SIZE, 4 \n.equ TOTAL, 2048\n.equ BUFFERSIZE, 80\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/*******************************************/\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\nszMessOK: .asciz \"Bravo !! You win. \\n\"\nszMessNotOK: .asciz \"You lost !! \\n\"\nszMessNewGame: .asciz \"New game (y/n) ? \\n\"\nszMessErreur: .asciz \"Error detected.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n//szMessMovePos: .asciz \"\\033[00;00H\"\nszMess0: .asciz \" \"\nszMess2: .asciz \" 2 \"\nszMess4: .asciz \" 4 \"\nszMess8: .asciz \" 8 \"\nszMess16: .asciz \" 16 \"\nszMess32: .asciz \" 32 \"\nszMess64: .asciz \" 64 \"\nszMess128: .asciz \" 128 \"\nszMess256: .asciz \" 256 \"\nszMess512: .asciz \" 512 \"\nszMess1024: .asciz \" 1024 \"\nszMess2048: .asciz \" 2048 \"\nszClear1: .byte 0x1B \n .byte 'c' @ other console clear\n .byte 0\n \nszLineH: .asciz \"-----------------------------\\n\"\nszLineV: .asciz \"|\"\nszLineVT: .asciz \"| | | | |\\n\"\n.align 4\niGraine: .int 123456\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nsZoneConv: .skip 24\nsBuffer: .skip BUFFERSIZE\niTbCase: .skip 4 * SIZE * SIZE\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 \n1: @ begin game loop\n ldr r0,iAdrszClear1\n bl affichageMess\n bl razTable\n2:\n bl addDigit \n cmp r0,#-1\n beq 5f @ end game\n bl displayGame\n3:\n bl readKey\n cmp r0,#-1\n beq 100f @ error or control-c\n bl keyMove\n cmp r0,#0\n beq 3b @ no change -> loop\n cmp r0,#2 @ last addition = 2048 ?\n beq 4f\n cmp r0,#-1 @ quit ?\n bne 2b @ loop\n \n b 10f\n4: @ last addition = 2048 \n ldr r0,iAdrszMessOK\n bl affichageMess\n b 10f\n5: @ display message no solution\n ldr r0,iAdrszMessNotOK\n bl affichageMess\n \n10: @ display new game ?\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszMessNewGame\n bl affichageMess\n bl readKey\n ldr r0,iAdriTouche\n ldrb r0,[r0]\n cmp r0,#'y'\n beq 1b\n cmp r0,#'Y'\n beq 1b\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\niAdrszMessNotOK: .int szMessNotOK\niAdrszMessOK: .int szMessOK\niAdrszMessNewGame: .int szMessNewGame\niAdrsZoneConv: .int sZoneConv\niAdrszClear1: .int szClear1\n/******************************************************************/\n/* raz table cases */ \n/******************************************************************/\nrazTable:\n push {r0-r2,lr} @ save registers\n ldr r1,iAdriTbCase\n mov r0,#0\n mov r2,#0\n1:\n str r0,[r1,r2,lsl #2]\n add r2,r2,#1\n cmp r2,#SIZE * SIZE\n blt 1b\n100:\n pop {r0-r2,lr} @ restaur registers \n bx lr @return\n/******************************************************************/\n/* key move */ \n/******************************************************************/\n/* r0 contains key value */\nkeyMove:\n push {r1,lr} @ save registers\n cmp r0,#0x42 @ down arrow \n bne 1f\n bl moveDown\n b 100f\n1:\n cmp r0,#0x41 @ high arrow\n bne 2f\n bl moveUp\n b 100f\n2:\n cmp r0,#0x43 @ right arrow\n bne 3f\n bl moveRight\n b 100f\n3:\n cmp r0,#0x44 @ left arrow\n bne 4f\n bl moveLeft\n b 100f\n4:\n ldr r0,iAdriTouche\n ldrb r0,[r0]\n cmp r0,#'q' @ quit game\n bne 5f\n mov r0,#-1\n b 100f\n5:\n cmp r0,#'Q' @ quit game\n bne 100f\n mov r0,#-1\n b 100f\n \n100:\n pop {r1,lr} @ restaur registers \n bx lr @return\n/******************************************************************/\n/* move left */ \n/******************************************************************/\n/* r0 return -1 if ok */\nmoveLeft:\n push {r1-r10,lr} @ save registers\n ldr r1,iAdriTbCase\n mov r0,#0 @ top move Ok\n mov r2,#0 @ line indice\n1:\n mov r6,#0 @ counter empty case\n mov r7,#0 @ first digit\n mov r10,#0 @ last digit to add\n mov r3,#0 @ column indice\n2:\n lsl r5,r2,#2 @ change this if size <> 4\n add r5,r5,r3 @ compute table indice\n ldr r4,[r1,r5,lsl #2]\n cmp r4,#0\n addeq r6,r6,#1 @ positions vides\n beq 5f\n cmp r6,#0\n beq 3f @ no empty left case\n mov r8,#0\n str r8,[r1,r5,lsl #2] @ raz digit\n sub r5,r5,r6\n str r4,[r1,r5,lsl #2] @ and store to left empty position\n mov r0,#1 @ move Ok\n //sub r6,r6,#1\n3:\n cmp r7,#0 @ first digit\n beq 4f\n cmp r10,r4 @ prec digit have to add \n beq 4f\n sub r8,r5,#1 @ prec digit \n ldr r9,[r1,r8,lsl #2]\n cmp r4,r9 @ equal ?\n bne 4f\n mov r10,r4 @ save digit \n add r4,r4,r9 @ yes -> add\n str r4,[r1,r8,lsl #2]\n cmp r4,#TOTAL\n moveq r0,#2\n beq 100f\n mov r4,#0\n str r4,[r1,r5,lsl #2]\n add r6,r6,#1 @ empty case + 1\n mov r0,#1 @ move Ok\n4:\n add r7,r7,#1 @ no first digit\n \n5: @ and loop\n add r3,r3,#1\n cmp r3,#SIZE\n blt 2b\n add r2,r2,#1\n cmp r2,#SIZE\n blt 1b\n100:\n pop {r1-r12,lr}\n bx lr @ return \n/******************************************************************/\n/* move right */ \n/******************************************************************/\n/* r0 return -1 if ok */\nmoveRight:\n push {r1-r5,lr} @ save registers\n ldr r1,iAdriTbCase\n mov r0,#0\n mov r2,#0\n1:\n mov r6,#0\n mov r7,#0\n mov r10,#0\n mov r3,#SIZE-1\n2:\n lsl r5,r2,#2 @ change this if size <> 4\n add r5,r5,r3\n ldr r4,[r1,r5,lsl #2]\n cmp r4,#0\n addeq r6,r6,#1 @ positions vides\n beq 5f\n \n cmp r6,#0\n beq 3f @ no empty right case\n mov r0,#0\n str r0,[r1,r5,lsl #2] @ raz digit\n add r5,r5,r6\n str r4,[r1,r5,lsl #2] @ and store to right empty position\n mov r0,#1\n3:\n cmp r7,#0 @ first digit\n beq 4f\n add r8,r5,#1 @ next digit \n ldr r9,[r1,r8,lsl #2]\n cmp r4,r9 @ equal ?\n bne 4f\n cmp r10,r4\n beq 4f\n mov r10,r4\n add r4,r4,r9 @ yes -> add\n str r4,[r1,r8,lsl #2]\n cmp r4,#TOTAL\n moveq r0,#2\n beq 100f\n mov r4,#0\n str r4,[r1,r5,lsl #2]\n add r6,r6,#1 @ empty case + 1\n mov r0,#1\n4:\n add r7,r7,#1 @ no first digit\n \n5: @ and loop\n sub r3,r3,#1\n cmp r3,#0\n bge 2b\n add r2,r2,#1\n cmp r2,#SIZE\n blt 1b\n \n100:\n pop {r1-r5,lr}\n bx lr @ return \n/******************************************************************/\n/* move down */ \n/******************************************************************/\n/* r0 return -1 if ok */\nmoveDown:\n push {r1-r5,lr} @ save registers\n ldr r1,iAdriTbCase\n mov r0,#0\n mov r3,#0\n1:\n mov r6,#0\n mov r7,#0\n mov r10,#0\n mov r2,#SIZE-1\n2:\n lsl r5,r2,#2 @ change this if size <> 4\n add r5,r5,r3\n ldr r4,[r1,r5,lsl #2]\n cmp r4,#0\n addeq r6,r6,#1 @ positions vides\n beq 5f\n cmp r6,#0\n beq 3f @ no empty right case\n mov r0,#0\n str r0,[r1,r5,lsl #2] @ raz digit\n lsl r0,r6,#2\n add r5,r5,r0\n str r4,[r1,r5,lsl #2] @ and store to right empty position\n mov r0,#1\n3:\n cmp r7,#0 @ first digit\n beq 4f\n add r8,r5,#SIZE @ down digit \n ldr r9,[r1,r8,lsl #2]\n cmp r4,r9 @ equal ?\n bne 4f\n cmp r10,r4\n beq 4f\n mov r10,r4\n add r4,r4,r9 @ yes -> add\n str r4,[r1,r8,lsl #2]\n cmp r4,#TOTAL\n moveq r0,#2\n beq 100f\n mov r4,#0\n str r4,[r1,r5,lsl #2]\n add r6,r6,#1 @ empty case + 1\n mov r0,#1\n4:\n add r7,r7,#1 @ no first digit\n \n5: @ and loop\n sub r2,r2,#1\n cmp r2,#0\n bge 2b\n add r3,r3,#1\n cmp r3,#SIZE\n blt 1b\n \n100:\n pop {r1-r5,lr}\n bx lr @ return \n/******************************************************************/\n/* move up */ \n/******************************************************************/\n/* r0 return -1 if ok */\nmoveUp:\n push {r1-r5,lr} @ save registers\n ldr r1,iAdriTbCase\n mov r0,#0\n mov r3,#0\n1:\n mov r6,#0\n mov r7,#0\n mov r10,#0\n mov r2,#0\n2:\n lsl r5,r2,#2 @ change this if size <> 4\n add r5,r5,r3\n ldr r4,[r1,r5,lsl #2]\n cmp r4,#0\n addeq r6,r6,#1 @ positions vides\n beq 5f\n cmp r6,#0\n beq 3f @ no empty right case\n mov r0,#0\n str r0,[r1,r5,lsl #2] @ raz digit\n lsl r0,r6,#2\n sub r5,r5,r0\n str r4,[r1,r5,lsl #2] @ and store to right empty position\n mov r0,#1\n3:\n cmp r7,#0 @ first digit\n beq 4f\n sub r8,r5,#SIZE @ up digit \n ldr r9,[r1,r8,lsl #2]\n cmp r4,r9 @ equal ?\n bne 4f\n cmp r10,r4\n beq 4f\n mov r10,r4\n add r4,r4,r9 @ yes -> add\n str r4,[r1,r8,lsl #2]\n cmp r4,#TOTAL\n moveq r0,#2\n beq 100f\n mov r4,#0\n str r4,[r1,r5,lsl #2]\n add r6,r6,#1 @ empty case + 1\n mov r0,#1\n4:\n add r7,r7,#1 @ no first digit\n \n5: @ and loop\n add r2,r2,#1\n cmp r2,#SIZE\n blt 2b\n add r3,r3,#1\n cmp r3,#SIZE\n blt 1b\n \n100:\n pop {r1-r5,lr}\n bx lr @ return \n/******************************************************************/\n/* add new digit on game */ \n/******************************************************************/\n/* r0 return -1 if ok */\naddDigit:\n push {r1-r5,lr} @ save registers\n sub sp,#4 * SIZE*SIZE\n mov fp,sp\n \n mov r0,#100\n bl genereraleas\n cmp r0,#10\n movlt r5,#4\n movge r5,#2\n ldr r1,iAdriTbCase\n mov r3,#0\n mov r4,#0\n1: \n ldr r2,[r1,r3,lsl #2]\n cmp r2,#0\n bne 2f\n str r3,[fp,r4,lsl #2]\n add r4,r4,#1\n2:\n add r3,r3,#1\n cmp r3,#SIZE*SIZE\n blt 1b\n cmp r4,#0 @ no empty case\n moveq r0,#-1\n beq 100f\n cmp r4,#1 \n bne 3f\n ldr r2,[fp] @ one case\n str r5,[r1,r2,lsl #2]\n mov r0,#0\n b 100f\n3: @ multiple case\n sub r0,r4,#1\n bl genereraleas\n ldr r2,[fp,r0,lsl #2]\n str r5,[r1,r2,lsl #2]\n mov r0,#0\n \n100:\n add sp,#4* (SIZE*SIZE) @ stack alignement\n pop {r1-r5,lr}\n bx lr @ return \niAdriTbCase: .int iTbCase\n/******************************************************************/\n/* display game */ \n/******************************************************************/\ndisplayGame:\n push {r1-r3,lr} @ save registers\n ldr r0,iAdrszClear1\n bl affichageMess\n ldr r0,iAdrszLineH\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n ldr r1,iAdriTbCase\n mov r2,#0\n1:\n ldr r0,[r1,r2,lsl #2]\n bl digitString\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n add r2,r2,#1\n cmp r2,#SIZE\n blt 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineH\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n2:\n ldr r0,[r1,r2,lsl #2]\n bl digitString\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n add r2,r2,#1\n cmp r2,#SIZE*2\n blt 2b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineH\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n3:\n ldr r0,[r1,r2,lsl #2]\n bl digitString\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n add r2,r2,#1\n cmp r2,#SIZE*3\n blt 3b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineH\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n4:\n ldr r0,[r1,r2,lsl #2]\n bl digitString\n bl affichageMess\n ldr r0,iAdrszLineV\n bl affichageMess\n add r2,r2,#1\n cmp r2,#SIZE*4\n blt 4b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszLineVT\n bl affichageMess\n ldr r0,iAdrszLineH\n bl affichageMess\n \n100:\n pop {r1-r3,lr}\n bx lr @ return \niAdrszLineH: .int szLineH\niAdrszLineV: .int szLineV\niAdrszLineVT: .int szLineVT\n//iAdrszMessMovePos: .int szMessMovePos\n/******************************************************************/\n/* digits string */ \n/******************************************************************/\n/* r0 contains number */\n/* r0 return address string */\ndigitString:\n push {r1,lr} @ save registers\n cmp r0,#0\n bne 1f\n ldr r0,iAdrszMess0\n b 100f\n1:\n cmp r0,#2\n bne 2f\n ldr r0,iAdrszMess2\n b 100f\n2:\n cmp r0,#4\n bne 3f\n ldr r0,iAdrszMess4\n b 100f\n3:\n cmp r0,#8\n bne 4f\n ldr r0,iAdrszMess8\n b 100f\n4:\n cmp r0,#16\n bne 5f\n ldr r0,iAdrszMess16\n b 100f\n5:\n cmp r0,#32\n bne 6f\n ldr r0,iAdrszMess32\n b 100f\n6:\n cmp r0,#64\n bne 7f\n ldr r0,iAdrszMess64\n b 100f\n7:\n cmp r0,#128\n bne 8f\n ldr r0,iAdrszMess128\n b 100f\n8:\n cmp r0,#256\n bne 9f\n ldr r0,iAdrszMess256\n b 100f\n9:\n cmp r0,#512\n bne 10f\n ldr r0,iAdrszMess512\n b 100f\n10:\n cmp r0,#1024\n bne 11f\n ldr r0,iAdrszMess1024\n b 100f\n11:\n cmp r0,#2048\n bne 12f\n ldr r0,iAdrszMess2048\n b 100f\n12:\n ldr r1,iAdrszMessErreur @ error message\n bl displayError\n100:\n pop {r1,lr}\n bx lr @ return \niAdrszMess0: .int szMess0\niAdrszMess2: .int szMess2\niAdrszMess4: .int szMess4\niAdrszMess8: .int szMess8\niAdrszMess16: .int szMess16\niAdrszMess32: .int szMess32\niAdrszMess64: .int szMess64\niAdrszMess128: .int szMess128\niAdrszMess256: .int szMess256\niAdrszMess512: .int szMess512\niAdrszMess1024: .int szMess1024\niAdrszMess2048: .int szMess2048\n \n//iAdrsBuffer: .int sBuffer\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,iNbDep2\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 add r1,r0,#1 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ résult = 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/* read touch */\n/***************************************************/\nreadKey:\n push {r1-r7,lr}\n mov r5,#0\n ldr r1,iAdriTouche @ buffer address\n str r5,[r1] @ raz 4 bytes iTouche\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 ?\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 ?\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 ?\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 ?\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 ?\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,#BUFFERSIZE @ buffer size\n mov r7,#READ @ read key\n svc #0\n cmp r0,#0 @ error ?\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 @ no 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 : .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/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n "}}},{"rowIdx":78114,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle"},"task_name":{"kind":"string","value":"4-rings or 4-squares puzzle"},"task_description":{"kind":"string","value":"4-rings or 4-squares puzzle\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nReplace a, b, c, d, e, f, and\n g with the decimal\ndigits LOW ───► HIGH\n\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\nShow all output here.\n\n\n\n Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n Show only the number of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n\nRelated task\n\n Solve the no connection puzzle\n\n"},"language_url":{"kind":"string","value":"#Prolog"},"language_name":{"kind":"string","value":"Prolog"},"code":{"kind":"string","value":" \n:- use_module(library(clpfd)).\n \n% main predicate\nmy_sum(Min, Max, Top, LL):-\n L = [A,B,C,D,E,F,G],\n L ins Min..Max,\n ( Top == 0\n -> all_distinct(L)\n ; true),\n R #= A+B,\n R #= B+C+D,\n R #= D+E+F,\n R #= F+G,\n setof(L, labeling([ff], L), LL).\n \n \nmy_sum_1(Min, Max) :-\n my_sum(Min, Max, 0, LL),\n maplist(writeln, LL).\n \nmy_sum_2(Min, Max, Len) :-\n my_sum(Min, Max, 1, LL),\n length(LL, Len).\n "}}},{"rowIdx":78115,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_solver"},"task_name":{"kind":"string","value":"15 puzzle solver"},"task_description":{"kind":"string","value":"Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.\n\nFor this task you will be using the following puzzle:\n\n\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on.\n\nThere are two solutions, of fifty-two moves:\n\nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd\n\nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\n\nExtra credit.\nSolve the following problem:\n\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n\n\nRelated Task\n\n 15 puzzle game\n A* search algorithm\n\n"},"language_url":{"kind":"string","value":"#Common_Lisp"},"language_name":{"kind":"string","value":"Common Lisp"},"code":{"kind":"string","value":";;; Using a priority queue for the A* search\n(eval-when (:load-toplevel :compile-toplevel :execute)\n (ql:quickload \"pileup\"))\n \n;; * The package definition\n(defpackage :15-solver\n (:use :common-lisp :pileup)\n (:export \"15-puzzle-solver\" \"*initial-state*\" \"*goal-state*\"))\n(in-package :15-solver)\n \n;; * Data types\n(defstruct (posn (:constructor posn))\n \"A posn is a pair struct containing two integer for the row/col indices.\"\n (row 0 :type fixnum)\n (col 0 :type fixnum))\n \n(defstruct (state (:constructor state))\n \"A state contains a vector and a posn describing the position of the empty slot.\"\n (matrix '#(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0) :type simple-vector)\n (empty-slot (posn :row 3 :col 3) :type posn))\n \n(defparameter directions '(up down left right)\n \"The possible directions shifting the empty slot.\")\n \n(defstruct (node (:constructor node))\n \"A node contains a state, a reference to the previous node, a g value (actual\ncosts until this node, and a f value (g value + heuristics).\"\n (state (state) :type state)\n (prev nil)\n (cost 0 :type fixnum)\n (f-value 0 :type fixnum))\n \n;; * Some constants\n(defparameter *side-size* 4 \"The size of the puzzle.\")\n \n(defvar *initial-state*\n (state :matrix #(15 14 1 6\n 9 11 4 12\n 0 10 7 3\n 13 8 5 2)\n :empty-slot (posn :row 2 :col 0)))\n \n(defvar *initial-state-2*\n (state :matrix #( 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1)\n :empty-slot (posn :row 0 :col 0)))\n \n(defvar *goal-state*\n (state :matrix #( 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 0)\n :empty-slot (posn :row 3 :col 3)))\n \n;; * The functions\n \n;; ** Accessing the elements of the puzzle\n(defun matrix-ref (matrix row col)\n \"Matrices are simple vectors, abstracted by following functions.\"\n (svref matrix (+ (* row *side-size*) col)))\n \n(defun (setf matrix-ref) (val matrix row col)\n (setf (svref matrix (+ (* row *side-size*) col)) val))\n \n;; ** The final predicate\n(defun target-state-p (state goal-state)\n \"Returns T if STATE is the goal state.\"\n (equalp state goal-state))\n \n(defun valid-movement-p (direction empty-slot)\n \"Returns T if direction is allowed for the current empty slot position.\"\n (case direction\n (up (< (posn-row empty-slot) (1- *side-size*)))\n (down (> (posn-row empty-slot) 0))\n (left (< (posn-col empty-slot) (1- *side-size*)))\n (right (> (posn-col empty-slot) 0))))\n \n;; ** Pretty print the state\n(defun print-state (state)\n \"Helper function to pretty-print a state.\"\n (format t \" ====================~%\")\n (loop\n with matrix = (state-matrix state)\n for i from 0 below *side-size*\n do\n (loop\n for j from 0 below *side-size*\n do (format t \"| ~2,D \" (matrix-ref matrix i j)))\n (format t \" |~%\"))\n (format t \" ====================~%\"))\n \n;; ** Move the empty slot\n(defun move (state direction)\n \"Returns a new state after moving STATE's empty-slot in DIRECTION assuming a\n valid direction.\"\n (let* ((matrix (copy-seq (state-matrix state)))\n (empty-slot (state-empty-slot state))\n (r (posn-row empty-slot))\n (c (posn-col empty-slot))\n (new-empty-slot\n (ccase direction\n (up (setf (matrix-ref matrix r c) (matrix-ref matrix (1+ r) c)\n (matrix-ref matrix (1+ r) c) 0)\n (posn :row (1+ r) :col c))\n (down (setf (matrix-ref matrix r c) (matrix-ref matrix (1- r) c)\n (matrix-ref matrix (1- r) c) 0)\n (posn :row (1- r) :col c))\n (left (setf (matrix-ref matrix r c) (matrix-ref matrix r (1+ c))\n (matrix-ref matrix r (1+ c)) 0)\n (posn :row r :col (1+ c)))\n (right (setf (matrix-ref matrix r c) (matrix-ref matrix r (1- c))\n (matrix-ref matrix r (1- c)) 0)\n (posn :row r :col (1- c))))))\n (state :matrix matrix :empty-slot new-empty-slot)))\n \n;; ** The heuristics\n(defun l1-distance (posn0 posn1)\n \"Returns the L1 distance between two positions.\"\n (+ (abs (- (posn-row posn0) (posn-row posn1)))\n (abs (- (posn-col posn0) (posn-col posn1)))))\n \n(defun element-cost (val current-posn)\n \"Returns the L1 distance between the current position and the goal-position\nfor VAL.\"\n (if (zerop val)\n (l1-distance current-posn (posn :row 3 :col 3))\n (multiple-value-bind (target-row target-col)\n (floor (1- val) *side-size*)\n (l1-distance current-posn (posn :row target-row :col target-col)))))\n \n(defun distance-to-goal (state)\n \"Returns the L1 distance from STATE to the goal state.\"\n (loop\n with matrix = (state-matrix state)\n with sum = 0\n for i below *side-size*\n do (loop\n for j below *side-size*\n for val = (matrix-ref matrix i j)\n for cost = (element-cost val (posn :row i :col j))\n unless (zerop val)\n do (incf sum cost))\n finally (return sum)))\n \n(defun out-of-order-values (list)\n \"Returns the number of values out of order.\"\n (flet ((count-values (list)\n (loop\n with a = (first list)\n with rest = (rest list)\n for b in rest\n when (> b a)\n count b)))\n (loop\n for candidates = list then (rest candidates)\n while candidates\n summing (count-values candidates) into result\n finally (return (* 2 result)))))\n \n(defun row-conflicts (row state0 state1)\n \"Returns the number of conflicts in the given row, i.e. value in the right row\n but in the wrong order. For each conflicted pair add 2 to the value, but a\n maximum of 6 to avoid over-estimation.\"\n (let* ((goal-row (loop\n with matrix1 = (state-matrix state1)\n for j below *side-size*\n collect (matrix-ref matrix1 row j)))\n (in-goal-row (loop\n with matrix0 = (state-matrix state0)\n for j below *side-size*\n for val = (matrix-ref matrix0 row j)\n when (member val goal-row)\n collect val)))\n (min 6 (out-of-order-values\n ;; 0 does not lead to a linear conflict\n (remove 0 (nreverse in-goal-row))))))\n \n(defun col-conflicts (col state0 state1)\n \"Returns the number of conflicts in the given column, i.e. value in the right\n row but in the wrong order. For each conflicted pair add 2 to the value, but a\n maximum of 6 to avoid over-estimation.\"\n (let* ((goal-col (loop\n with matrix1 = (state-matrix state1)\n for i below *side-size*\n collect (matrix-ref matrix1 i col)))\n (in-goal-col (loop\n with matrix0 = (state-matrix state0)\n for i below *side-size*\n for val = (matrix-ref matrix0 i col)\n when (member val goal-col)\n collect val)))\n (min 6 (out-of-order-values\n ;; 0 does not lead to a linear conflict\n (remove 0 (nreverse in-goal-col))))))\n \n(defun linear-conflicts (state0 state1)\n \"Returns the linear conflicts for state1 with respect to state0.\"\n (loop\n for i below *side-size*\n for row-conflicts = (row-conflicts i state0 state1)\n for col-conflicts = (col-conflicts i state0 state1)\n summing row-conflicts into all-row-conflicts\n summing col-conflicts into all-col-conflicts\n finally (return (+ all-row-conflicts all-col-conflicts))))\n \n(defun state-heuristics (state)\n \"Using the L1 distance and the number of linear conflicts as heuristics.\"\n (+ (distance-to-goal state)\n (linear-conflicts state *goal-state*)))\n \n;; ** Generate the next possible states. \n(defun next-state-dir-pairs (current-node)\n \"Returns a list of pairs containing the next states and the direction for the\n movement of the empty slot.\"\n (let* ((state (node-state current-node))\n (empty-slot (state-empty-slot state))\n (valid-movements (remove-if-not (lambda (dir) (valid-movement-p dir empty-slot))\n directions)))\n (map 'list (lambda (dir) (cons (move state dir) dir)) valid-movements)))\n \n;; ** Searching the shortest paths and reconstructing the movements\n(defun reconstruct-movements (leaf-node)\n \"Traverse all nodes until the initial state and return a list of symbols\ndescribing the path.\"\n (labels ((posn-diff (p0 p1)\n ;; Compute a pair describing the last move\n (posn :row (- (posn-row p1) (posn-row p0))\n :col (- (posn-col p1) (posn-col p0))))\n (find-movement (prev-state state)\n ;; Describe the last movement of the empty slot with R, L, U or D.\n (let* ((prev-empty-slot (state-empty-slot prev-state))\n (this-empty-slot (state-empty-slot state))\n (delta (posn-diff prev-empty-slot this-empty-slot)))\n (cond ((equalp delta (posn :row 1 :col 0)) 'u)\n ((equalp delta (posn :row -1 :col 0)) 'd)\n ((equalp delta (posn :row 0 :col 1)) 'l)\n ((equalp delta (posn :row 0 :col -1)) 'r))))\n (iter (node path)\n (if (or (not node) (not (node-prev node)))\n path\n (iter (node-prev node)\n (cons (find-movement (node-state node)\n (node-state (node-prev node)))\n path)))))\n (iter leaf-node '())))\n \n(defun A* (initial-state\n &key (goal-state *goal-state*) (heuristics #'state-heuristics)\n (information 0))\n \"An A* search for the shortest path to *GOAL-STATE*\"\n (let ((visited (make-hash-table :test #'equalp))) ; All states visited so far\n ;; Some internal helper functions\n (flet ((pick-next-node (queue)\n ;; Get the next node from the queue\n (heap-pop queue))\n (expand-node (node queue)\n ;; Expand the next possible nodes from node and add them to the\n ;; queue if not already visited.\n (loop\n with costs = (node-cost node)\n with successors = (next-state-dir-pairs node)\n for (state . dir) in successors\n for succ-cost = (1+ costs)\n for f-value = (+ succ-cost (funcall heuristics state))\n ;; Check if this state was already looked at\n unless (gethash state visited)\n do\n ;; Insert the next node into the queue\n (heap-insert\n (node :state state :prev node :cost succ-cost\n :f-value f-value)\n queue))))\n \n ;; The actual A* search\n (loop\n ;; The priority queue\n with queue = (make-heap #'<= :name \"queue\" :size 1000 :key #'node-f-value)\n with initial-state-cost = (funcall heuristics initial-state)\n initially (heap-insert (node :state initial-state :prev nil :cost 0\n :f-value initial-state-cost)\n queue)\n for counter from 1\n for current-node = (pick-next-node queue)\n for current-state = (node-state current-node)\n ;; Output some information each counter or nothing if information\n ;; equals 0.\n when (and (not (zerop information)) \n (zerop (mod counter information))) \n do (format t \"~Dth State, heap size: ~D, current costs: ~D~%\"\n counter (heap-count queue)\n (node-cost current-node))\n \n ;; If the target is not reached continue\n until (target-state-p current-state goal-state)\n do\n ;; Add the current state to the hash of visited states\n (setf (gethash current-state visited) t)\n ;; Expand the current node and continue\n (expand-node current-node queue)\n finally (return (values (reconstruct-movements current-node) counter))))))\n \n;; ** Pretty print the path\n(defun print-path (path)\n \"Prints the directions of PATH and its length.\"\n (format t \"~{~A~} ~D moves~%\" path (length path)))\n \n;; ** Get some timing information\n(defmacro timing (&body forms)\n \"Return both how much real time was spend in body and its result\"\n (let ((start (gensym))\n\t(end (gensym))\n\t(result (gensym)))\n `(let* ((,start (get-internal-real-time))\n\t (,result (progn ,@forms))\n\t (,end (get-internal-real-time)))\n (values ,result (/ (- ,end ,start) internal-time-units-per-second)))))\n \n;; ** The main function\n(defun 15-puzzle-solver (initial-state &key (goal-state *goal-state*))\n \"Solves a given and valid 15 puzzle and returns the shortest path to reach the\n goal state.\"\n (print-state initial-state)\n (multiple-value-bind (result time)\n (timing (multiple-value-bind (path steps)\n (a* initial-state :goal-state goal-state)\n (print-path path)\n steps))\n (format t \"Found the shortest path in ~D steps and ~3,2F seconds~%\" result time)) \n (print-state goal-state))\n "}}},{"rowIdx":78116,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/99_bottles_of_beer"},"task_name":{"kind":"string","value":"99 bottles of beer"},"task_description":{"kind":"string","value":"Task\n\nDisplay the complete lyrics for the song: 99 Bottles of Beer on the Wall.\n\n\n\nThe beer song\n\nThe lyrics follow this form:\n\n\n 99 bottles of beer on the wall\n\n 99 bottles of beer\n\n Take one down, pass it around\n\n 98 bottles of beer on the wall\n\n\n 98 bottles of beer on the wall\n\n 98 bottles of beer\n\n Take one down, pass it around\n\n 97 bottles of beer on the wall\n\n... and so on, until reaching 0 (zero).\n\nGrammatical support for 1 bottle of beer is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n\nSee also\n \n http://99-bottles-of-beer.net/\n Category:99_Bottles_of_Beer\n Category:Programming language families\n Wikipedia 99 bottles of beer\n\n"},"language_url":{"kind":"string","value":"#AmigaE"},"language_name":{"kind":"string","value":"AmigaE"},"code":{"kind":"string","value":"PROC main()\n DEF t: PTR TO CHAR,\n s: PTR TO CHAR,\n u: PTR TO CHAR, i, x\n t := 'Take one down, pass it around\\n'\n s := '\\d bottle\\s of beer\\s\\n'\n u := ' on the wall'\n FOR i := 99 TO 0 STEP -1\n ForAll({x}, [u, NIL], `WriteF(s, i, IF i <> 1 THEN 's' ELSE NIL,\n x))\n IF i > 0 THEN WriteF(t)\n ENDFOR\nENDPROC"}}},{"rowIdx":78117,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game"},"task_name":{"kind":"string","value":"24 game"},"task_description":{"kind":"string","value":"The 24 Game tests one's mental arithmetic.\n\n\n\nTask\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to 24.\n\n Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n Division should use floating point or rational arithmetic, etc, to preserve remainders.\n Brackets are allowed, if using an infix expression evaluator.\n Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n The order of the digits when given does not have to be preserved.\n\n\nNotes\n The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\nRelated tasks\n 24 game/Solve\n\n\nReference\n The 24 Game on h2g2.\n\n"},"language_url":{"kind":"string","value":"#D"},"language_name":{"kind":"string","value":"D"},"code":{"kind":"string","value":"import std.stdio, std.random, std.math, std.algorithm, std.range,\n std.typetuple;\n \nvoid main() {\n void op(char c)() {\n if (stack.length < 2)\n throw new Exception(\"Wrong expression.\");\n stack[$ - 2] = mixin(\"stack[$ - 2]\" ~ c ~ \"stack[$ - 1]\");\n stack.popBack();\n }\n \n const problem = iota(4).map!(_ => uniform(1, 10))().array();\n writeln(\"Make 24 with the digits: \", problem);\n \n double[] stack;\n int[] digits;\n foreach (const char c; readln())\n switch (c) {\n case ' ', '\\t', '\\n': break;\n case '1': .. case '9':\n stack ~= c - '0';\n digits ~= c - '0';\n break;\n foreach (o; TypeTuple!('+', '-', '*', '/')) {\n case o: op!o(); break;\n }\n break;\n default: throw new Exception(\"Wrong char: \" ~ c);\n }\n \n if (!digits.sort().equal(problem.dup.sort()))\n throw new Exception(\"Not using the given digits.\");\n if (stack.length != 1)\n throw new Exception(\"Wrong expression.\");\n writeln(\"Result: \", stack[0]);\n writeln(abs(stack[0] - 24) < 0.001 ? \"Good job!\" : \"Try again.\");\n}"}}},{"rowIdx":78118,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/9_billion_names_of_God_the_integer"},"task_name":{"kind":"string","value":"9 billion names of God the integer"},"task_description":{"kind":"string","value":"This task is a variation of the short story by Arthur C. Clarke.\n\n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a “name”:\n\nThe integer 1 has 1 name “1”.\nThe integer 2 has 2 names “1+1”, and “2”.\nThe integer 3 has 3 names “1+1+1”, “2+1”, and “3”.\nThe integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.\nThe integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.\n\n\nTask\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\nWhere row \n\n\n\nn\n\n\n{\\displaystyle n}\n\n corresponds to integer \n\n\n\nn\n\n\n{\\displaystyle n}\n\n, and each column \n\n\n\nC\n\n\n{\\displaystyle C}\n\n in row \n\n\n\nm\n\n\n{\\displaystyle m}\n\n from left to right corresponds to the number of names beginning with \n\n\n\nC\n\n\n{\\displaystyle C}\n\n.\n\nA function \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n should return the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row.\n\nDemonstrate this function by displaying: \n\n\n\nG\n(\n23\n)\n\n\n{\\displaystyle G(23)}\n\n, \n\n\n\nG\n(\n123\n)\n\n\n{\\displaystyle G(123)}\n\n, \n\n\n\nG\n(\n1234\n)\n\n\n{\\displaystyle G(1234)}\n\n, and \n\n\n\nG\n(\n12345\n)\n\n\n{\\displaystyle G(12345)}\n\n.\n\nOptionally note that the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n is the integer partition function.\n\nDemonstrate this is equivalent to \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n by displaying: \n\n\n\nP\n(\n23\n)\n\n\n{\\displaystyle P(23)}\n\n, \n\n\n\nP\n(\n123\n)\n\n\n{\\displaystyle P(123)}\n\n, \n\n\n\nP\n(\n1234\n)\n\n\n{\\displaystyle P(1234)}\n\n, and \n\n\n\nP\n(\n12345\n)\n\n\n{\\displaystyle P(12345)}\n\n.\n\n\n\nExtra credit\nIf your environment is able, plot \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n against \n\n\n\nn\n\n\n{\\displaystyle n}\n\n for \n\n\n\nn\n=\n1\n…\n999\n\n\n{\\displaystyle n=1\\ldots 999}\n\n.\n\nRelated tasks\n Partition function P\n\n"},"language_url":{"kind":"string","value":"#Wren"},"language_name":{"kind":"string","value":"Wren"},"code":{"kind":"string","value":"import \"/big\" for BigInt\nimport \"/fmt\" for Fmt\n \nvar cache = [[BigInt.one]]\nvar cumu = Fn.new { |n|\n if (cache.count <= n) {\n (cache.count..n).each { |l|\n var r = [BigInt.zero]\n (1..l).each { |x|\n var min = l - x\n if (x < min) min = x\n r.add(r[-1] + cache[l - x][min])\n }\n cache.add(r)\n }\n }\n return cache[n]\n}\n \nvar row = Fn.new { |n|\n var r = cumu.call(n)\n return (0...n).map { |i| r[i+1] - r[i] }.toList\n}\n \nSystem.print(\"Rows:\")\n(1..25).each { |i|\n Fmt.print(\"$2d: $s\", i, row.call(i))\n}\n \nSystem.print(\"\\nSums:\")\n[23, 123, 1234, 12345].each { |i|\n Fmt.print(\"$5s: $s\", i, cumu.call(i)[-1])\n}"}}},{"rowIdx":78119,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/A%2BB"},"task_name":{"kind":"string","value":"A+B"},"task_description":{"kind":"string","value":"A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, A and B.\n\nTheir sum needs to be calculated.\n\n\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n \n\n\n\n(\n−\n1000\n≤\nA\n,\nB\n≤\n+\n1000\n)\n\n\n{\\displaystyle (-1000\\leq A,B\\leq +1000)}\n\n\n\n\nOutput data\n\nThe required output is one integer: the sum of A and B.\n\n\n\nExample\n\n\n\n input \n\n output \n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n"},"language_url":{"kind":"string","value":"#C.2B.2B"},"language_name":{"kind":"string","value":"C++"},"code":{"kind":"string","value":"// Standard input-output streams\n#include \nusing namespace std;\nint main()\n{\n int a, b;\n cin >> a >> b;\n cout << a + b << endl;\n}"}}},{"rowIdx":78120,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Ackermann_function"},"task_name":{"kind":"string","value":"Ackermann function"},"task_description":{"kind":"string","value":"The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.\n\n\n\nThe Ackermann function is usually defined as follows:\n\n\n\n\n\n\n\nA\n(\nm\n,\nn\n)\n=\n\n\n{\n\n\n\nn\n+\n1\n\n\n\nif \n\nm\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\n1\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\nA\n(\nm\n,\nn\n−\n1\n)\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n>\n0.\n\n\n\n\n\n\n\n\n{\\displaystyle A(m,n)={\\begin{cases}n+1&{\\mbox{if }}m=0\\\\A(m-1,1)&{\\mbox{if }}m>0{\\mbox{ and }}n=0\\\\A(m-1,A(m,n-1))&{\\mbox{if }}m>0{\\mbox{ and }}n>0.\\end{cases}}}\n\n\n\n\n\n\nIts arguments are never negative and it always terminates.\n\n\n\nTask\n\nWrite a function which returns the value of \n\n\n\nA\n(\nm\n,\nn\n)\n\n\n{\\displaystyle A(m,n)}\n\n. Arbitrary precision is preferred (since the function grows so quickly), but not required.\n\n\n\nSee also\n\n Conway chained arrow notation for the Ackermann function.\n\n"},"language_url":{"kind":"string","value":"#TSE_SAL"},"language_name":{"kind":"string","value":"TSE SAL"},"code":{"kind":"string","value":"// library: math: get: ackermann: recursive 1.0.0.0.5 (filenamemacro=getmaare.s) [kn, ri, tu, 27-12-2011 14:46:59]\nINTEGER PROC FNMathGetAckermannRecursiveI( INTEGER mI, INTEGER nI )\n IF ( mI == 0 )\n RETURN( nI + 1 )\n ENDIF\n IF ( nI == 0 )\n RETURN( FNMathGetAckermannRecursiveI( mI - 1, 1 ) )\n ENDIF\n RETURN( FNMathGetAckermannRecursiveI( mI - 1, FNMathGetAckermannRecursiveI( mI, nI - 1 ) ) )\nEND\n \nPROC Main()\nSTRING s1[255] = \"2\"\nSTRING s2[255] = \"3\"\nIF ( NOT ( Ask( \"math: get: ackermann: recursive: m = \", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF\nIF ( NOT ( Ask( \"math: get: ackermann: recursive: n = \", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF\n Message( FNMathGetAckermannRecursiveI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 9\nEND"}}},{"rowIdx":78121,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/ABC_problem"},"task_name":{"kind":"string","value":"ABC problem"},"task_description":{"kind":"string","value":"ABC problem\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nYou are given a collection of ABC blocks (maybe like the ones you had when you were a kid).\n\nThere are twenty blocks with two letters on each block.\n\nA complete alphabet is guaranteed amongst all sides of the blocks.\n\nThe sample collection of blocks:\n\n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n\nTask\n\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.\n\n\n\nThe rules are simple:\n\n Once a letter on a block is used that block cannot be used again\n The function should be case-insensitive\n Show the output on this page for the following 7 words in the following example\n\n\nExample\n\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n"},"language_url":{"kind":"string","value":"#Factor"},"language_name":{"kind":"string","value":"Factor"},"code":{"kind":"string","value":"USING: assocs combinators.short-circuit formatting grouping io\nkernel math math.statistics qw sequences sets unicode ;\nIN: rosetta-code.abc-problem\n \n! === CONSTANTS ================================================\n \nCONSTANT: blocks qw{\n BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\n}\n \nCONSTANT: input qw{ A BARK BOOK TREAT COMMON SQUAD CONFUSE }\n \n! === PROGRAM LOGIC ============================================\n \n: pare ( str -- seq )\n [ blocks ] dip [ intersects? ] curry filter ;\n \n: enough-blocks? ( str -- ? ) dup pare [ length ] bi@ <= ;\n \n: enough-letters? ( str -- ? )\n [ blocks concat ] dip dup [ within ] dip\n [ histogram values ] bi@ [ - ] 2map [ neg? ] any? not ;\n \n: can-make-word? ( str -- ? )\n >upper { [ enough-blocks? ] [ enough-letters? ] } 1&& ;\n \n! === OUTPUT ===================================================\n \n: show-blocks ( -- )\n \"Available blocks:\" print blocks [ 1 cut \"(%s %s)\" sprintf ]\n map 5 group [ [ write bl ] each nl ] each nl ;\n \n: header ( -- )\n \"Word\" \"Can make word from blocks?\" \"%-7s %s\\n\" printf\n \"======= ==========================\" print ;\n \n: result ( str -- )\n dup can-make-word? \"Yes\" \"No\" ? \"%-7s %s\\n\" printf ;\n \n! === MAIN =====================================================\n \n: abc-problem ( -- )\n show-blocks header input [ result ] each ;\n \nMAIN: abc-problem"}}},{"rowIdx":78122,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/100_prisoners"},"task_name":{"kind":"string","value":"100 prisoners"},"task_description":{"kind":"string","value":"\n\nThe Problem\n\n 100 prisoners are individually numbered 1 to 100\n A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n Prisoners start outside the room\n They can decide some strategy before any enter the room.\n Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n A prisoner can open no more than 50 drawers.\n A prisoner tries to find his own number.\n A prisoner finding his own number is then held apart from the others.\n If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. \n\n\nThe task\n\n Simulate several thousand instances of the game where the prisoners randomly open drawers\n Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n First opening the drawer whose outside number is his prisoner number.\n If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n\n\nReferences\n\n The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n wp:100 prisoners problem\n 100 Prisoners Escape Puzzle DataGenetics.\n Random permutation statistics#One hundred prisoners on Wikipedia.\n\n"},"language_url":{"kind":"string","value":"#Cowgol"},"language_name":{"kind":"string","value":"Cowgol"},"code":{"kind":"string","value":"include \"cowgol.coh\";\ninclude \"argv.coh\";\n \n# Parameters\nconst Drawers := 100; # Amount of drawers (and prisoners)\nconst Attempts := 50; # Amount of attempts a prisoner may make\nconst Simulations := 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 := r.x + 1;\n r.a := r.a ^ r.c ^ r.x;\n r.b := r.b + r.a;\n r.c := r.c + (r.b >> 1) ^ r.a;\n byte := r.c;\nend sub;\n \nsub RandomUpTo(r: [RNG], limit: uint8): (rslt: uint8) is\n var x: uint8 := 1;\n while x < limit loop\n x := x << 1;\n end loop;\n x := x - 1;\n \n loop\n rslt := 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 := 0;\n while x < Drawers loop\n drawers[x] := x;\n x := x + 1;\n end loop;\n \n x := 0;\n while x < Drawers - 1 loop\n var y := x + RandomUpTo(r, Drawers-x);\n var t := drawers[x];\n drawers[x] := drawers[y];\n drawers[y] := t;\n x := 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 := 0;\n var triesLeft: uint8 := Attempts;\n while triesLeft != 0 loop\n var d := RandomUpTo(r, Drawers); # grab a random drawer\n if opened[d] != 0 then\n continue; # Ignore it if a drawer was already open\n else\n triesLeft := triesLeft - 1;\n opened[d] := 1;\n if drawers[d] == p then # found it!\n success := 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 := p;\n var triesLeft: uint8 := Attempts;\n success := 0;\n while triesLeft != 0 loop\n current := drawers[current];\n if current == p then\n success := 1;\n return;\n end if;\n triesLeft := 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 := 0;\n success := 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 := 0;\n return;\n end if;\n p := 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 := 0;\n while n > 0 loop\n successes := successes + Simulate(s, r) as NSim;\n n := 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 := 0;\nArgvInit();\nvar arg := ArgvNext();\nif arg != 0 as [uint8] then\n (rng.state, arg) := AToI(arg);\nend if;\n \nsub RunAndPrint(name: [uint8], strat: Strategy) is\n print(name);\n print(\" strategy: \");\n var succ := 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);"}}},{"rowIdx":78123,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Abundant_odd_numbers"},"task_name":{"kind":"string","value":"Abundant odd numbers"},"task_description":{"kind":"string","value":"An Abundant number is a number n for which the sum of divisors σ(n) > 2n,\n\nor, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.\n\n\n\nE.G.\n\n12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);\n\n or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).\n\n\n\nAbundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.\n\nTo make things more interesting, this task is specifically about finding odd abundant numbers.\n\n\n\nTask\nFind and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\nFind and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\nFind and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\nReferences\n\n OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n"},"language_url":{"kind":"string","value":"#Swift"},"language_name":{"kind":"string","value":"Swift"},"code":{"kind":"string","value":"extension BinaryInteger {\n @inlinable\n public func factors(sorted: Bool = true) -> [Self] {\n let maxN = Self(Double(self).squareRoot())\n var res = Set()\n \n for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {\n res.insert(factor)\n res.insert(self / factor)\n }\n \n return sorted ? res.sorted() : Array(res)\n }\n}\n \n@inlinable\npublic func isAbundant(n: T) -> (Bool, [T]) {\n let divs = n.factors().dropLast()\n \n return (divs.reduce(0, +) > n, Array(divs))\n}\n \nlet oddAbundant = (0...).lazy.filter({ $0 & 1 == 1 }).map({ ($0, isAbundant(n: $0)) }).filter({ $1.0 })\n \nfor (n, (_, factors)) in oddAbundant.prefix(25) {\n print(\"n: \\(n); sigma: \\(factors.reduce(0, +))\")\n}\n \nlet (bigA, (_, bigFactors)) =\n (1_000_000_000...)\n .lazy\n .filter({ $0 & 1 == 1 })\n .map({ ($0, isAbundant(n: $0)) })\n .first(where: { $1.0 })!\n \nprint(\"first odd abundant number over 1 billion: \\(bigA), sigma: \\(bigFactors.reduce(0, +))\")"}}},{"rowIdx":78124,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/21_game"},"task_name":{"kind":"string","value":"21 game"},"task_description":{"kind":"string","value":"21 game\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n21 is a two player game, the game is played by choosing\na number (1, 2, or 3) to be added to the running total.\n\nThe game is won by the player whose chosen number causes the running total\nto reach exactly 21.\n\nThe running total starts at zero.\nOne player will be the computer.\n\nPlayers alternate supplying a number to be added to the running total.\n\n\n\nTask\n\nWrite a computer program that will:\n\n do the prompting (or provide a button menu), \n check for errors and display appropriate error messages, \n do the additions (add a chosen number to the running total), \n display the running total, \n provide a mechanism for the player to quit/exit/halt/stop/close the program,\n issue a notification when there is a winner, and\n determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n"},"language_url":{"kind":"string","value":"#Picat"},"language_name":{"kind":"string","value":"Picat"},"code":{"kind":"string","value":"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 := choosefoolishly\n elseif Level == \"2\" then\n Algo := choosesemiwisely\n elseif Level != \"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 := apply(Algo, N)\n end,\n while (N < 21)\n N := playermove(N),\n if N == 21 then\n println(\"Player wins! Game over, gg!\"),\n halt\n end,\n N := 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.\n "}}},{"rowIdx":78125,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game/Solve"},"task_name":{"kind":"string","value":"24 game/Solve"},"task_description":{"kind":"string","value":"task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\n\n\nRelated task\n\n Arithmetic Evaluator\n\n"},"language_url":{"kind":"string","value":"#Fortran"},"language_name":{"kind":"string","value":"Fortran"},"code":{"kind":"string","value":"program solve_24\n use helpers\n implicit none\n real :: vector(4), reals(4), p, q, r, s\n integer :: numbers(4), n, i, j, k, a, b, c, d\n character, parameter :: ops(4) = (/ '+', '-', '*', '/' /)\n logical :: last\n real,parameter :: eps = epsilon(1.0)\n \n do n=1,12\n call random_number(vector)\n reals = 9 * vector + 1\n numbers = int(reals)\n call Insertion_Sort(numbers)\n \n permutations: do\n a = numbers(1); b = numbers(2); c = numbers(3); d = numbers(4)\n reals = real(numbers)\n p = reals(1); q = reals(2); r = reals(3); s = reals(4)\n ! combinations of operators:\n do i=1,4\n do j=1,4\n do k=1,4\n if ( abs(op(op(op(p,i,q),j,r),k,s)-24.0) < eps ) then\n write (*,*) numbers, ' : ', '((',a,ops(i),b,')',ops(j),c,')',ops(k),d\n exit permutations\n else if ( abs(op(op(p,i,op(q,j,r)),k,s)-24.0) < eps ) then\n write (*,*) numbers, ' : ', '(',a,ops(i),'(',b,ops(j),c,'))',ops(k),d\n exit permutations\n else if ( abs(op(p,i,op(op(q,j,r),k,s))-24.0) < eps ) then\n write (*,*) numbers, ' : ', a,ops(i),'((',b,ops(j),c,')',ops(k),d,')'\n exit permutations\n else if ( abs(op(p,i,op(q,j,op(r,k,s)))-24.0) < eps ) then\n write (*,*) numbers, ' : ', a,ops(i),'(',b,ops(j),'(',c,ops(k),d,'))'\n exit permutations\n else if ( abs(op(op(p,i,q),j,op(r,k,s))-24.0) < eps ) then\n write (*,*) numbers, ' : ', '(',a,ops(i),b,')',ops(j),'(',c,ops(k),d,')'\n exit permutations\n end if\n end do\n end do\n end do\n call nextpermutation(numbers,last) \n if ( last ) then\n write (*,*) numbers, ' : no solution.'\n exit permutations\n end if\n end do permutations\n \n end do\n \ncontains\n \n pure real function op(x,c,y)\n integer, intent(in) :: c\n real, intent(in) :: x,y\n select case ( ops(c) )\n case ('+')\n op = x+y\n case ('-')\n op = x-y\n case ('*')\n op = x*y\n case ('/')\n op = x/y\n end select\n end function op\n \nend program solve_24"}}},{"rowIdx":78126,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_game"},"task_name":{"kind":"string","value":"15 puzzle game"},"task_description":{"kind":"string","value":" \n\n\nTask\n\nImplement the Fifteen Puzzle Game.\n\n\n\nThe 15-puzzle is also known as:\n\n Fifteen Puzzle\n Gem Puzzle\n Boss Puzzle\n Game of Fifteen\n Mystic Square\n 14-15 Puzzle\n and some others.\n\n\nRelated Tasks\n\n 15 Puzzle Solver\n 16 Puzzle Game\n\n"},"language_url":{"kind":"string","value":"#68000_Assembly"},"language_name":{"kind":"string","value":"68000 Assembly"},"code":{"kind":"string","value":";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 \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 \n\tmove.w (VDP_ctrl),D0\t ;C00004 read VDP status (interrupt acknowledge?)\n\tmove.l #$00008000,d5\t ;VDP Reg command (%8rvv)\n \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 \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 \n\tmove.l #$C01E0000,d0\t;Color 15 (Font)\n\tmove.l d0,VDP_Ctrl\n\tmove.w #%0000000011101110,VDP_data\n \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 \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 \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 \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 \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 \n \n\tclr.b Cursor_X\t\t;Clear Cursor XY\n\tclr.b Cursor_Y\n \n\t;Turn on screen\n\tmove.w\t#$8144,(VDP_Ctrl);C00004 reg 1 = 0x44 unblank display\n \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 \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 \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 \n \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 \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 \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 \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 \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 \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 \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 \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 \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 \n\tor.l #$FFFFF000,d0\t;Set unused bits to 1\n \n \n \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 \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 \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 \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 \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 \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 \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 \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"}}},{"rowIdx":78127,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/2048"},"task_name":{"kind":"string","value":"2048"},"task_description":{"kind":"string","value":"Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\n\n\nRules of the game\n\n The rules are that on each turn the player must choose a direction (up, down, left or right).\n All tiles move as far as possible in that direction, some move more than others. \n Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers. \n A move is valid when at least one tile can be moved, if only by combination. \n A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one). \n Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.\n To win, the player must create a tile with the number 2048. \n The player loses if no valid moves are possible.\n\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\n\n\nRequirements\n\n \"Non-greedy\" movement. \n The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n That is to say, that moving the tile row of:\n [2][2][2][2] \n\n to the right should result in: \n ......[4][4] \n\n and not:\n .........[8] \n\n \"Move direction priority\". \n If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n For example, moving the tile row of:\n ...[2][2][2] \n\n to the right should result in:\n ......[2][4] \n\n and not:\n ......[4][2] \n\n\n\n Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.\n Check for a win condition.\n Check for a lose condition.\n\n"},"language_url":{"kind":"string","value":"#AutoHotkey"},"language_name":{"kind":"string","value":"AutoHotkey"},"code":{"kind":"string","value":"Grid := [], s := 16, w := h := S * 4.5\nGui, font, s%s%\nGui, add, text, y1\nloop, 4\n{\n\trow := A_Index\n\tloop, 4\n\t{\n\t\tcol := A_Index\n\t\tif col = 1\n\t\t\tGui, add, button, v%row%_%col% xs y+1 w%w% h%h% -TabStop, % Grid[row,col] := 0\n\t\telse\n\t\t\tGui, add, button, v%row%_%col% x+1 yp w%w% h%h% -TabStop, % Grid[row,col] := 0\n\t}\n}\nGui, show,, 2048\n;------------------------------\n \nStart:\nfor row, obj in Grid\n\tfor col, val in obj\n\t\tGrid[row,col] := 0\n \nGrid[1,1]:=2\nShowGrid()\nreturn\n \n;------------------------------\nGuiClose:\nExitApp\nreturn\n;------------------------------\n#IfWinActive, 2048\n;------------------------------\nup::\nmove := false\nloop, 4\n{\n\tcol := A_Index\n\tLoop, 3\n\t{\n\t\trow := A_Index\n\t\tif Grid[row, col] && (Grid[row, col] = Grid[row+1, col])\n\t\t\tGrid[row, col] *=2\t, Grid[row+1, col] := 0, move := true\n\t}\n}\n \nloop, 4\n{\n\trow := A_Index\n\tloop, 4\n\t{\n\t\tcol := A_Index\n\t\tloop, 4\n\t\t\tif !Grid[row, col]\n\t\t\t\tloop, 3\n\t\t\t\t\tif !Grid[row, col] && Grid[row+A_Index, col]\n\t\t\t\t\t{\n\t\t\t\t\t\tGrid[row, col] := Grid[row+A_Index, col]\t, Grid[row+A_Index, col] := 0, move := true\n\t\t\t\t\t\tif (Grid[row, col] = Grid[row-1, col])\n\t\t\t\t\t\t\tGrid[row-1, col] *=2\t, Grid[row, col] := 0, move := true\n\t\t\t\t\t}\n\t}\n}\ngosub, AddNew\nreturn\n;------------------------------\nDown::\nmove := false\nloop, 4\n{\n\tcol := A_Index\n\tLoop, 3\n\t{\n\t\trow := 5-A_Index\n\t\tif Grid[row, col] && (Grid[row, col] = Grid[row-1, col])\n\t\t\tGrid[row, col] *=2\t, Grid[row-1, col] := 0, move := true\n\t}\n}\n \nloop, 4\n{\n\trow := 5-A_Index\n\tloop, 4\n\t{\n\t\tcol := A_Index\n\t\tloop, 4\n\t\t\tif !Grid[row, col]\n\t\t\t\tloop, 3\n\t\t\t\t\tif !Grid[row, col] && Grid[row-A_Index, col]\n\t\t\t\t\t{\n\t\t\t\t\t\tGrid[row, col] := Grid[row-A_Index, col]\t, Grid[row-A_Index, col] := 0, move := true\n\t\t\t\t\t\tif (Grid[row, col] = Grid[row+1, col])\n\t\t\t\t\t\t\tGrid[row+1, col] *=2\t, Grid[row, col] := 0, move := true\n\t\t\t\t\t}\n\t}\n}\ngosub, AddNew\nreturn\n;------------------------------\nLeft::\nmove := false\nloop, 4\n{\n\trow := A_Index\n\tLoop, 3\n\t{\n\t\tcol := A_Index\n\t\tif Grid[row, col] && (Grid[row, col] = Grid[row, col+1])\n\t\t\tGrid[row, col] *=2\t, Grid[row, col+1] := 0, move := true\n\t}\n}\n \nloop, 4\n{\n\tcol := A_Index\n\tloop, 4\n\t{\n\t\trow := A_Index\n\t\tloop, 4\n\t\t\tif !Grid[row, col]\n\t\t\t\tloop, 3\n\t\t\t\t\tif !Grid[row, col] && Grid[row, col+A_Index]\n\t\t\t\t\t{\n\t\t\t\t\t\tGrid[row, col] := Grid[row, col+A_Index]\t, Grid[row, col+A_Index] := 0, move := true\n\t\t\t\t\t\tif (Grid[row, col] = Grid[row, col-1])\n\t\t\t\t\t\t\tGrid[row, col-1] *=2\t, Grid[row, col] := 0, move := true\n\t\t\t\t\t}\n \n\t}\n}\ngosub, AddNew\nreturn\n;------------------------------\nRight::\nmove := false\nloop, 4\n{\n\trow := A_Index\n\tLoop, 3\n\t{\n\t\tcol := 5-A_Index\n\t\tif Grid[row, col] && (Grid[row, col] = Grid[row, col-1])\n\t\t\tGrid[row, col] *=2\t, Grid[row, col-1] := 0, move := true\n\t}\n}\n \nloop, 4\n{\n\tcol := 5-A_Index\n\tloop, 4\n\t{\n\t\trow := A_Index\n\t\tloop, 4\n\t\t\tif !Grid[row, col]\n\t\t\t\tloop, 3\n\t\t\t\t\tif !Grid[row, col] && Grid[row, col-A_Index]\n\t\t\t\t\t{\n\t\t\t\t\t\tGrid[row, col] := Grid[row, col-A_Index]\t, Grid[row, col-A_Index] := 0, move := true\n\t\t\t\t\t\tif (Grid[row, col] = Grid[row, col+1])\n\t\t\t\t\t\t\tGrid[row, col+1] *=2\t, Grid[row, col] := 0, move := true\n\t\t\t\t\t}\n\t}\n}\ngosub, AddNew\nreturn\n \n;------------------------------\n#IfWinActive\n;------------------------------\nAddNew:\nif EndOfGame()\n{\n\tMsgBox Done `nPress OK to retry\n\tgoto start\n}\nreturn\n \n;------------------------------\nEndOfGame(){\n\tglobal\n\tif Move\n\t\tAddRandom()\n\tShowGrid()\n\tfor row, obj in Grid\n\t\tfor col, val in obj\n\t\t\tif !grid[row,col]\n\t\t\t\treturn 0\n \n\tfor row, obj in Grid\n\t\tfor col, val in obj\n\t\t\tif (grid[row,col] = grid[row+1,col]) || (grid[row,col] = grid[row-1,col]) || (grid[row,col] = grid[row,col+1]) || (grid[row,col] = grid[row,col-1])\n\t\t\t\treturn 0\n\treturn 1\n}\n \n;------------------------------\nShowGrid(){\n\tglobal Grid\n\tfor row, obj in Grid\n\t\tfor col, val in obj\n\t\t{\n\t\t\tGuiControl,, %row%_%col%, %val%\n\t\t\tif val\n\t\t\t\tGuiControl, Show, %row%_%col%\n\t\t\telse\n\t\t\t\tGuiControl, Hide, %row%_%col%\n\t\t}\n}\n \n;------------------------------\nAddRandom(){\n\tglobal Grid\n\tShowGrid()\n\tSleep, 200\n\tfor row, obj in Grid\n\t\tfor col, val in obj\n\t\t\tif !grid[row,col]\n\t\t\t\tlist .= (list?\"`n\":\"\") row \",\" col\n\tSort, list, random\n\tRnd := StrSplit(list, \"`n\").1\n\tGrid[StrSplit(rnd, \",\").1, StrSplit(rnd, \",\").2] := 2\n}\n;------------------------------"}}},{"rowIdx":78128,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle"},"task_name":{"kind":"string","value":"4-rings or 4-squares puzzle"},"task_description":{"kind":"string","value":"4-rings or 4-squares puzzle\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nReplace a, b, c, d, e, f, and\n g with the decimal\ndigits LOW ───► HIGH\n\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\nShow all output here.\n\n\n\n Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n Show only the number of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n\nRelated task\n\n Solve the no connection puzzle\n\n"},"language_url":{"kind":"string","value":"#Python"},"language_name":{"kind":"string","value":"Python"},"code":{"kind":"string","value":"import itertools\n \ndef all_equal(a,b,c,d,e,f,g):\n return a+b == b+c+d == d+e+f == f+g\n \ndef foursquares(lo,hi,unique,show):\n solutions = 0\n if unique:\n uorn = \"unique\"\n citer = itertools.combinations(range(lo,hi+1),7)\n else:\n uorn = \"non-unique\"\n citer = itertools.combinations_with_replacement(range(lo,hi+1),7)\n \n for c in citer:\n for p in set(itertools.permutations(c)):\n if all_equal(*p):\n solutions += 1\n if show:\n print str(p)[1:-1]\n \n print str(solutions)+\" \"+uorn+\" solutions in \"+str(lo)+\" to \"+str(hi)\n print"}}},{"rowIdx":78129,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_solver"},"task_name":{"kind":"string","value":"15 puzzle solver"},"task_description":{"kind":"string","value":"Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.\n\nFor this task you will be using the following puzzle:\n\n\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on.\n\nThere are two solutions, of fifty-two moves:\n\nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd\n\nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\n\nExtra credit.\nSolve the following problem:\n\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n\n\nRelated Task\n\n 15 puzzle game\n A* search algorithm\n\n"},"language_url":{"kind":"string","value":"#F.23"},"language_name":{"kind":"string","value":"F#"},"code":{"kind":"string","value":" \n// A Naive 15 puzzle solver using no memory. Nigel Galloway: October 6th., 2017\nlet Nr,Nc = [|3;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3|],[|3;0;1;2;3;0;1;2;3;0;1;2;3;0;1;2|]\ntype G= |N |I |G |E |L \ntype N={i:uint64;g:G list;e:int;l:int}\nlet fN n=let g=(11-n.e)*4 in let a=n.i&&&(15UL<<>>g)]<=n.e/4 then 0 else 1)}\nlet fI i=let g=(19-i.e)*4 in let a=i.i&&&(15UL<<>>16);g=I::i.g;e=i.e-4;l=i.l+(if Nr.[int(a>>>g)]>=i.e/4 then 0 else 1)}\nlet fG g=let l=(14-g.e)*4 in let a=g.i&&&(15UL<<>>l)]<=g.e%4 then 0 else 1)}\nlet fE e=let l=(16-e.e)*4 in let a=e.i&&&(15UL<<>>4) ;g=E::e.g;e=e.e-1;l=e.l+(if Nc.[int(a>>>l)]>=e.e%4 then 0 else 1)}\nlet fL=let l=[|[I;E];[I;G;E];[I;G;E];[I;G];[N;I;E];[N;I;G;E];[N;I;G;E];[N;I;G];[N;I;E];[N;I;G;E];[N;I;G;E];[N;I;G];[N;E];[N;G;E];[N;G;E];[N;G];|]\n (fun n g->List.except [g] l.[n] |> List.map(fun n->match n with N->fI |I->fN |G->fE |E->fG))\nlet solve n g l=let rec solve n=match n with // n is board, g is pos of 0, l is max depth\n |n when n.i =0x123456789abcdef0UL->Some(n.g)\n |n when n.l>l ->None\n |g->let rec fN=function h::t->match solve h with None->fN t |n->n\n |_->None\n fN (fL g.e (List.head n.g)|>List.map(fun n->n g))\n solve {i=n;g=[L];e=g;l=0}\n let n = Seq.collect fN n\n "}}},{"rowIdx":78130,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/99_bottles_of_beer"},"task_name":{"kind":"string","value":"99 bottles of beer"},"task_description":{"kind":"string","value":"Task\n\nDisplay the complete lyrics for the song: 99 Bottles of Beer on the Wall.\n\n\n\nThe beer song\n\nThe lyrics follow this form:\n\n\n 99 bottles of beer on the wall\n\n 99 bottles of beer\n\n Take one down, pass it around\n\n 98 bottles of beer on the wall\n\n\n 98 bottles of beer on the wall\n\n 98 bottles of beer\n\n Take one down, pass it around\n\n 97 bottles of beer on the wall\n\n... and so on, until reaching 0 (zero).\n\nGrammatical support for 1 bottle of beer is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n\nSee also\n \n http://99-bottles-of-beer.net/\n Category:99_Bottles_of_Beer\n Category:Programming language families\n Wikipedia 99 bottles of beer\n\n"},"language_url":{"kind":"string","value":"#Apache_Ant"},"language_name":{"kind":"string","value":"Apache Ant"},"code":{"kind":"string","value":"\n\n \n \n \n \n \n \n \n \n \n \t\n \n \n \n \n \n \n \n \n \n \n \n \n \t\n \n \n \n"}}},{"rowIdx":78131,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game"},"task_name":{"kind":"string","value":"24 game"},"task_description":{"kind":"string","value":"The 24 Game tests one's mental arithmetic.\n\n\n\nTask\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to 24.\n\n Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n Division should use floating point or rational arithmetic, etc, to preserve remainders.\n Brackets are allowed, if using an infix expression evaluator.\n Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n The order of the digits when given does not have to be preserved.\n\n\nNotes\n The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\nRelated tasks\n 24 game/Solve\n\n\nReference\n The 24 Game on h2g2.\n\n"},"language_url":{"kind":"string","value":"#EchoLisp"},"language_name":{"kind":"string","value":"EchoLisp"},"code":{"kind":"string","value":" \n(string-delimiter \"\")\n;; check that nums are in expr, and only once\n(define (is-valid? expr sorted: nums)\n (when (equal? 'q expr) (error \"24-game\" \"Thx for playing\"))\n (unless (and \n (list? expr) \n (equal? nums (list-sort < (filter number? (flatten expr)))))\n (writeln \"🎃 Please use\" nums)\n #f))\n \n;; 4 random digits\n(define (gen24)\n (->> (append (range 1 10)(range 1 10)) shuffle (take 4) (list-sort < )))\n \n(define (is-24? num)\n (unless (= 24 num)\n (writeln \"😧 Sorry - Result = \" num)\n #f))\n \n(define (check-24 expr)\n (if (and \n (is-valid? expr nums) \n (is-24? (js-eval (string expr)))) ;; use js evaluator\n \"🍀 🌸 Congrats - (play24) for another one.\"\n (input-expr check-24 (string nums))))\n \n(define nums null)\n(define (play24)\n (set! nums (gen24))\n (writeln \"24-game - Can you combine\" nums \"to get 24 ❓ (q to exit)\")\n (input-expr check-24 (string-append (string nums) \" -> 24 ❓\")))\n "}}},{"rowIdx":78132,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/9_billion_names_of_God_the_integer"},"task_name":{"kind":"string","value":"9 billion names of God the integer"},"task_description":{"kind":"string","value":"This task is a variation of the short story by Arthur C. Clarke.\n\n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a “name”:\n\nThe integer 1 has 1 name “1”.\nThe integer 2 has 2 names “1+1”, and “2”.\nThe integer 3 has 3 names “1+1+1”, “2+1”, and “3”.\nThe integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.\nThe integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.\n\n\nTask\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\nWhere row \n\n\n\nn\n\n\n{\\displaystyle n}\n\n corresponds to integer \n\n\n\nn\n\n\n{\\displaystyle n}\n\n, and each column \n\n\n\nC\n\n\n{\\displaystyle C}\n\n in row \n\n\n\nm\n\n\n{\\displaystyle m}\n\n from left to right corresponds to the number of names beginning with \n\n\n\nC\n\n\n{\\displaystyle C}\n\n.\n\nA function \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n should return the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row.\n\nDemonstrate this function by displaying: \n\n\n\nG\n(\n23\n)\n\n\n{\\displaystyle G(23)}\n\n, \n\n\n\nG\n(\n123\n)\n\n\n{\\displaystyle G(123)}\n\n, \n\n\n\nG\n(\n1234\n)\n\n\n{\\displaystyle G(1234)}\n\n, and \n\n\n\nG\n(\n12345\n)\n\n\n{\\displaystyle G(12345)}\n\n.\n\nOptionally note that the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n is the integer partition function.\n\nDemonstrate this is equivalent to \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n by displaying: \n\n\n\nP\n(\n23\n)\n\n\n{\\displaystyle P(23)}\n\n, \n\n\n\nP\n(\n123\n)\n\n\n{\\displaystyle P(123)}\n\n, \n\n\n\nP\n(\n1234\n)\n\n\n{\\displaystyle P(1234)}\n\n, and \n\n\n\nP\n(\n12345\n)\n\n\n{\\displaystyle P(12345)}\n\n.\n\n\n\nExtra credit\nIf your environment is able, plot \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n against \n\n\n\nn\n\n\n{\\displaystyle n}\n\n for \n\n\n\nn\n=\n1\n…\n999\n\n\n{\\displaystyle n=1\\ldots 999}\n\n.\n\nRelated tasks\n Partition function P\n\n"},"language_url":{"kind":"string","value":"#Yabasic"},"language_name":{"kind":"string","value":"Yabasic"},"code":{"kind":"string","value":"clear screen\n \nSub nine_billion_names(rows)\n local p(rows, rows), i, j, column\n \n p(1, 1) = 1\n \n For i = 2 To rows\n For j = 1 To i\n p(i, j) = p(i - 1, j - 1) + p(i - j, j)\n Next j\n Next i\n For i = 1 To rows\n column = rows * 2 - 2 * i - 2\n For j = 1 To i\n Print at(column + j * 4 + (1 - len(str$(p(i, j)))), i), p(i, j)\n Next j\n Next i\nEnd Sub\n \nnine_billion_names(20)"}}},{"rowIdx":78133,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/9_billion_names_of_God_the_integer"},"task_name":{"kind":"string","value":"9 billion names of God the integer"},"task_description":{"kind":"string","value":"This task is a variation of the short story by Arthur C. Clarke.\n\n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a “name”:\n\nThe integer 1 has 1 name “1”.\nThe integer 2 has 2 names “1+1”, and “2”.\nThe integer 3 has 3 names “1+1+1”, “2+1”, and “3”.\nThe integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.\nThe integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.\n\n\nTask\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\nWhere row \n\n\n\nn\n\n\n{\\displaystyle n}\n\n corresponds to integer \n\n\n\nn\n\n\n{\\displaystyle n}\n\n, and each column \n\n\n\nC\n\n\n{\\displaystyle C}\n\n in row \n\n\n\nm\n\n\n{\\displaystyle m}\n\n from left to right corresponds to the number of names beginning with \n\n\n\nC\n\n\n{\\displaystyle C}\n\n.\n\nA function \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n should return the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row.\n\nDemonstrate this function by displaying: \n\n\n\nG\n(\n23\n)\n\n\n{\\displaystyle G(23)}\n\n, \n\n\n\nG\n(\n123\n)\n\n\n{\\displaystyle G(123)}\n\n, \n\n\n\nG\n(\n1234\n)\n\n\n{\\displaystyle G(1234)}\n\n, and \n\n\n\nG\n(\n12345\n)\n\n\n{\\displaystyle G(12345)}\n\n.\n\nOptionally note that the sum of the \n\n\n\nn\n\n\n{\\displaystyle n}\n\n-th row \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n is the integer partition function.\n\nDemonstrate this is equivalent to \n\n\n\nG\n(\nn\n)\n\n\n{\\displaystyle G(n)}\n\n by displaying: \n\n\n\nP\n(\n23\n)\n\n\n{\\displaystyle P(23)}\n\n, \n\n\n\nP\n(\n123\n)\n\n\n{\\displaystyle P(123)}\n\n, \n\n\n\nP\n(\n1234\n)\n\n\n{\\displaystyle P(1234)}\n\n, and \n\n\n\nP\n(\n12345\n)\n\n\n{\\displaystyle P(12345)}\n\n.\n\n\n\nExtra credit\nIf your environment is able, plot \n\n\n\nP\n(\nn\n)\n\n\n{\\displaystyle P(n)}\n\n against \n\n\n\nn\n\n\n{\\displaystyle n}\n\n for \n\n\n\nn\n=\n1\n…\n999\n\n\n{\\displaystyle n=1\\ldots 999}\n\n.\n\nRelated tasks\n Partition function P\n\n"},"language_url":{"kind":"string","value":"#zkl"},"language_name":{"kind":"string","value":"zkl"},"code":{"kind":"string","value":"var [const] BN=Import.lib(\"zklBigNum\");\n \nconst N=0d100_000;\np:=List.createLong(N+1,BN.fp(0),True); // (0,0,...) all different\n \nfcn calc(n,p){\n p[n].set(0); // reset array for each run\n foreach k in ([1..n]){\n d:=n - k *(3*k - 1)/2;\n do(2){\n if (d<0) break(2);\n\t if (k.isOdd) p[n].add(p[d]);\n\t else p[n].sub(p[d]);\n\t d-=k;\n }\n }\n}"}}},{"rowIdx":78134,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/A%2BB"},"task_name":{"kind":"string","value":"A+B"},"task_description":{"kind":"string","value":"A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, A and B.\n\nTheir sum needs to be calculated.\n\n\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n \n\n\n\n(\n−\n1000\n≤\nA\n,\nB\n≤\n+\n1000\n)\n\n\n{\\displaystyle (-1000\\leq A,B\\leq +1000)}\n\n\n\n\nOutput data\n\nThe required output is one integer: the sum of A and B.\n\n\n\nExample\n\n\n\n input \n\n output \n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n"},"language_url":{"kind":"string","value":"#Ceylon"},"language_name":{"kind":"string","value":"Ceylon"},"code":{"kind":"string","value":"shared void run() {\n \n print(\"please enter two numbers for me to add\");\n value input = process.readLine();\n if (exists input) {\n value tokens = input.split().map(Integer.parse);\n if (tokens.any((element) => element is ParseException)) {\n print(\"numbers only, please\");\n return;\n }\n value numbers = tokens.narrow();\n if (numbers.size != 2) {\n print(\"two numbers, please\");\n }\n else if (!numbers.every((Integer element) => -1k <= element <= 1k)) {\n print(\"only numbers between -1000 and 1000, please\");\n }\n else if (exists a = numbers.first, exists b = numbers.last) {\n print(a + b);\n }\n else {\n print(\"something went wrong\");\n }\n }\n}"}}},{"rowIdx":78135,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Ackermann_function"},"task_name":{"kind":"string","value":"Ackermann function"},"task_description":{"kind":"string","value":"The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.\n\n\n\nThe Ackermann function is usually defined as follows:\n\n\n\n\n\n\n\nA\n(\nm\n,\nn\n)\n=\n\n\n{\n\n\n\nn\n+\n1\n\n\n\nif \n\nm\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\n1\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\nA\n(\nm\n,\nn\n−\n1\n)\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n>\n0.\n\n\n\n\n\n\n\n\n{\\displaystyle A(m,n)={\\begin{cases}n+1&{\\mbox{if }}m=0\\\\A(m-1,1)&{\\mbox{if }}m>0{\\mbox{ and }}n=0\\\\A(m-1,A(m,n-1))&{\\mbox{if }}m>0{\\mbox{ and }}n>0.\\end{cases}}}\n\n\n\n\n\n\nIts arguments are never negative and it always terminates.\n\n\n\nTask\n\nWrite a function which returns the value of \n\n\n\nA\n(\nm\n,\nn\n)\n\n\n{\\displaystyle A(m,n)}\n\n. Arbitrary precision is preferred (since the function grows so quickly), but not required.\n\n\n\nSee also\n\n Conway chained arrow notation for the Ackermann function.\n\n"},"language_url":{"kind":"string","value":"#TXR"},"language_name":{"kind":"string","value":"TXR"},"code":{"kind":"string","value":"(defmacro defmemofun (name (. args) . body)\n (let ((hash (gensym \"hash-\"))\n (argl (gensym \"args-\"))\n (hent (gensym \"hent-\"))\n (uniq (copy-str \"uniq\")))\n ^(let ((,hash (hash :equal-based)))\n (defun ,name (,*args)\n (let* ((,argl (list ,*args))\n (,hent (inhash ,hash ,argl ,uniq)))\n (if (eq (cdr ,hent) ,uniq)\n (set (cdr ,hent) (block ,name (progn ,*body)))\n (cdr ,hent)))))))\n \n(defmemofun ack (m n)\n (cond\n ((= m 0) (+ n 1))\n ((= n 0) (ack (- m 1) 1))\n (t (ack (- m 1) (ack m (- n 1))))))\n \n(each ((i (range 0 3)))\n (each ((j (range 0 4)))\n (format t \"ack(~a, ~a) = ~a\\n\" i j (ack i j))))"}}},{"rowIdx":78136,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/ABC_problem"},"task_name":{"kind":"string","value":"ABC problem"},"task_description":{"kind":"string","value":"ABC problem\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nYou are given a collection of ABC blocks (maybe like the ones you had when you were a kid).\n\nThere are twenty blocks with two letters on each block.\n\nA complete alphabet is guaranteed amongst all sides of the blocks.\n\nThe sample collection of blocks:\n\n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n\nTask\n\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.\n\n\n\nThe rules are simple:\n\n Once a letter on a block is used that block cannot be used again\n The function should be case-insensitive\n Show the output on this page for the following 7 words in the following example\n\n\nExample\n\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n"},"language_url":{"kind":"string","value":"#FBSL"},"language_name":{"kind":"string","value":"FBSL"},"code":{"kind":"string","value":" \n#APPTYPE CONSOLE\nSUB MAIN()\n\tBlockCheck(\"A\")\n\tBlockCheck(\"BARK\")\n\tBlockCheck(\"BooK\")\n\tBlockCheck(\"TrEaT\")\n\tBlockCheck(\"comMON\")\n\tBlockCheck(\"sQuAd\")\n\tBlockCheck(\"Confuse\")\n\tpause\nEND SUB\n \nFUNCTION BlockCheck(str)\n\tPRINT str \" \" iif( Blockable( str ), \"can\", \"cannot\" ) \" be spelled with blocks.\"\nEND FUNCTION\n \nFUNCTION Blockable(str AS STRING)\n\tDIM blocks AS STRING = \"BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM\"\n\tDIM C AS STRING = \"\"\n\tDIM POS AS INTEGER = 0\n \n\tFOR DIM I = 1 TO LEN(str)\n\t\tC = str{i}\n\t\tPOS = INSTR(BLOCKS, C, 0, 1) 'case insensitive\n\t\tIF POS > 0 THEN\n\t\t\t'if the pos is odd, it's the first of the pair\n\t\t\tIF POS MOD 2 = 1 THEN\n\t\t\t\t'so clear the first and the second\n\t\t\t\tPOKE(@blocks + POS - 1,\" \")\n\t\t\t\tPOKE(@blocks + POS,\" \")\n\t\t\t'otherwise, it's the last of the pair\t\n\t\t\tELSE\n\t\t\t\t'clear the second and the first\n\t\t\t\tPOKE(@blocks + POS - 1,\" \")\n\t\t\t\tPOKE(@blocks + POS - 2,\" \")\n\t\t\tEND IF\n\t\tELSE\n\t\t'not found, so can't be spelled\n\t\tRETURN FALSE\n\t\tEND IF\n\tNEXT\n\t'got thru to here, so can be spelled\n\tRETURN TRUE\nEND FUNCTION\n "}}},{"rowIdx":78137,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/100_prisoners"},"task_name":{"kind":"string","value":"100 prisoners"},"task_description":{"kind":"string","value":"\n\nThe Problem\n\n 100 prisoners are individually numbered 1 to 100\n A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n Prisoners start outside the room\n They can decide some strategy before any enter the room.\n Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n A prisoner can open no more than 50 drawers.\n A prisoner tries to find his own number.\n A prisoner finding his own number is then held apart from the others.\n If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. \n\n\nThe task\n\n Simulate several thousand instances of the game where the prisoners randomly open drawers\n Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n First opening the drawer whose outside number is his prisoner number.\n If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n\n\nReferences\n\n The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n wp:100 prisoners problem\n 100 Prisoners Escape Puzzle DataGenetics.\n Random permutation statistics#One hundred prisoners on Wikipedia.\n\n"},"language_url":{"kind":"string","value":"#Crystal"},"language_name":{"kind":"string","value":"Crystal"},"code":{"kind":"string","value":"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 : %11.4f %%\" % (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 %%\" % (res.fdiv(N) * 100)"}}},{"rowIdx":78138,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Abundant_odd_numbers"},"task_name":{"kind":"string","value":"Abundant odd numbers"},"task_description":{"kind":"string","value":"An Abundant number is a number n for which the sum of divisors σ(n) > 2n,\n\nor, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.\n\n\n\nE.G.\n\n12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);\n\n or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).\n\n\n\nAbundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.\n\nTo make things more interesting, this task is specifically about finding odd abundant numbers.\n\n\n\nTask\nFind and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\nFind and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\nFind and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\nReferences\n\n OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n"},"language_url":{"kind":"string","value":"#Visual_Basic_.NET"},"language_name":{"kind":"string","value":"Visual Basic .NET"},"code":{"kind":"string","value":"Module AbundantOddNumbers\n ' find some abundant odd numbers - numbers where the sum of the proper\n ' divisors is bigger than the number\n ' itself\n \n ' returns the sum of the proper divisors of n\n Private Function divisorSum(n As Integer) As Integer\n Dim sum As Integer = 1\n For d As Integer = 2 To Math.Round(Math.Sqrt(n))\n If n Mod d = 0 Then\n sum += d\n Dim otherD As Integer = n \\ d\n IF otherD <> d Then\n sum += otherD\n End If\n End If\n Next d\n Return sum\n End Function\n \n ' find numbers required by the task\n Public Sub Main(args() As String)\n ' first 25 odd abundant numbers\n Dim oddNumber As Integer = 1\n Dim aCount As Integer = 0\n Dim dSum As Integer = 0\n Console.Out.WriteLine(\"The first 25 abundant odd numbers:\")\n Do While aCount < 25\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n aCount += 1\n Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & \" proper divisor sum: \" & dSum)\n End If\n oddNumber += 2\n Loop\n ' 1000th odd abundant number\n Do While aCount < 1000\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n aCount += 1\n End If\n oddNumber += 2\n Loop\n Console.Out.WriteLine(\"1000th abundant odd number:\")\n Console.Out.WriteLine(\" \" & (oddNumber - 2) & \" proper divisor sum: \" & dSum)\n ' first odd abundant number > one billion\n oddNumber = 1000000001\n Dim found As Boolean = False\n Do While Not found\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n found = True\n Console.Out.WriteLine(\"First abundant odd number > 1 000 000 000:\")\n Console.Out.WriteLine(\" \" & oddNumber & \" proper divisor sum: \" & dSum)\n End If\n oddNumber += 2\n Loop\n End Sub\nEnd Module"}}},{"rowIdx":78139,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/21_game"},"task_name":{"kind":"string","value":"21 game"},"task_description":{"kind":"string","value":"21 game\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n21 is a two player game, the game is played by choosing\na number (1, 2, or 3) to be added to the running total.\n\nThe game is won by the player whose chosen number causes the running total\nto reach exactly 21.\n\nThe running total starts at zero.\nOne player will be the computer.\n\nPlayers alternate supplying a number to be added to the running total.\n\n\n\nTask\n\nWrite a computer program that will:\n\n do the prompting (or provide a button menu), \n check for errors and display appropriate error messages, \n do the additions (add a chosen number to the running total), \n display the running total, \n provide a mechanism for the player to quit/exit/halt/stop/close the program,\n issue a notification when there is a winner, and\n determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n"},"language_url":{"kind":"string","value":"#Python"},"language_name":{"kind":"string","value":"Python"},"code":{"kind":"string","value":" \nfrom random import randint\ndef start():\n\tgame_count=0\n\tprint(\"Enter q to quit at any time.\\nThe computer will choose first.\\nRunning total is now {}\".format(game_count))\n\troundno=1\n\twhile game_count<21:\n\t\tprint(\"\\nROUND {}: \\n\".format(roundno))\n\t\tt = select_count(game_count)\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, commiserations, the computer has won!\")\n\t\t\treturn 0\n\t\tt = request_count()\n\t\tif not t:\n\t\t\tprint('OK,quitting the game')\n\t\t\treturn -1\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, congratulations, you've won!\")\n\t\t\treturn 1\n\t\troundno+=1\n \ndef select_count(game_count):\n\t'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''\n\tif game_count<18:\n\t\tt= randint(1,3)\n\telse:\n\t\tt = 21-game_count\n\tprint(\"The computer chooses {}\".format(t))\n\treturn t\n \ndef request_count():\n\t'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''\n\tt=\"\"\n\twhile True:\n\t\ttry:\n\t\t\tt = raw_input('Your choice 1 to 3 :')\n\t\t\tif int(t) in [1,2,3]:\n\t\t\t\treturn int(t)\n\t\t\telse:\n\t\t\t\tprint(\"Out of range, try again\")\n\t\texcept:\n\t\t\tif t==\"q\":\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tprint(\"Invalid Entry, try again\")\n \nc=0\nm=0\nr=True\nwhile r:\n\to = start()\n\tif o==-1:\n\t\tbreak\n\telse:\n\t\tc+=1 if o==0 else 0\n\t\tm+=1 if o==1 else 0\n\tprint(\"Computer wins {0} game, human wins {1} games\".format(c,m))\n\tt = raw_input(\"Another game?(press y to continue):\")\n\tr = (t==\"y\")"}}},{"rowIdx":78140,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game/Solve"},"task_name":{"kind":"string","value":"24 game/Solve"},"task_description":{"kind":"string","value":"task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\n\n\nRelated task\n\n Arithmetic Evaluator\n\n"},"language_url":{"kind":"string","value":"#GAP"},"language_name":{"kind":"string","value":"GAP"},"code":{"kind":"string","value":"# Solution in '''RPN'''\ncheck := function(x, y, z)\n\tlocal r, c, s, i, j, k, a, b, p;\n\ti := 0;\n\tj := 0;\n\tk := 0;\n\ts := [ ];\n\tr := \"\";\n\tfor c in z do\n\t\tif c = 'x' then\n\t\t\ti := i + 1;\n\t\t\tk := k + 1;\n\t\t\ts[k] := x[i];\n\t\t\tAppend(r, String(x[i]));\n\t\telse\n\t\t\tj := j + 1;\n\t\t\tb := s[k];\n\t\t\tk := k - 1;\n\t\t\ta := s[k];\n\t\t\tp := y[j];\n\t\t\tr[Size(r) + 1] := p;\n\t\t\tif p = '+' then\n\t\t\t\ta := a + b;\n\t\t\telif p = '-' then\n\t\t\t\ta := a - b;\n\t\t\telif p = '*' then\n\t\t\t\ta := a * b;\n\t\t\telif p = '/' then\n\t\t\t\tif b = 0 then\n\t\t\t\t\tcontinue;\n\t\t\t\telse\n\t\t\t\t\ta := a / b;\n\t\t\t\tfi;\n\t\t\telse\n\t\t\t\treturn fail;\n\t\t\tfi;\n\t\t\ts[k] := a;\n\t\tfi;\n\tod;\n\tif s[1] = 24 then\n\t\treturn r;\n\telse\n\t\treturn fail;\n\tfi;\nend;\n \nPlayer24 := function(digits)\n\tlocal u, v, w, x, y, z, r;\n\tu := PermutationsList(digits);\n\tv := Tuples(\"+-*/\", 3);\n\tw := [\"xx*x*x*\", \"xx*xx**\", \"xxx**x*\", \"xxx*x**\", \"xxxx***\"];\n\tfor x in u do\n\t\tfor y in v do\n\t\t\tfor z in w do\n\t\t\t\tr := check(x, y, z);\n\t\t\t\tif r <> fail then\n\t\t\t\t\treturn r;\n\t\t\t\tfi;\n\t\t\tod;\n\t\tod;\n\tod;\n\treturn fail;\nend;\n \nPlayer24([1,2,7,7]);\n# \"77*1-2/\"\nPlayer24([9,8,7,6]);\n# \"68*97-/\"\nPlayer24([1,1,7,7]);\n# fail\n \n# Solutions with only one distinct digit are found only for 3, 4, 5, 6:\nPlayer24([3,3,3,3]);\n# \"33*3*3-\"\nPlayer24([4,4,4,4]);\n# \"44*4+4+\"\nPlayer24([5,5,5,5]);\n# \"55*55/-\"\nPlayer24([6,6,6,6]);\n# \"66*66+-\"\n \n# A tricky one:\nPlayer24([3,3,8,8]);\n\"8383/-/\""}}},{"rowIdx":78141,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_game"},"task_name":{"kind":"string","value":"15 puzzle game"},"task_description":{"kind":"string","value":" \n\n\nTask\n\nImplement the Fifteen Puzzle Game.\n\n\n\nThe 15-puzzle is also known as:\n\n Fifteen Puzzle\n Gem Puzzle\n Boss Puzzle\n Game of Fifteen\n Mystic Square\n 14-15 Puzzle\n and some others.\n\n\nRelated Tasks\n\n 15 Puzzle Solver\n 16 Puzzle Game\n\n"},"language_url":{"kind":"string","value":"#AArch64_Assembly"},"language_name":{"kind":"string","value":"AArch64 Assembly"},"code":{"kind":"string","value":" \n/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program puzzle15_64.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 NBBOX, 16\n.equ GRAINE, 123456 // change for other game\n.equ NBSHUFFLE, 4 \n.equ KEYSIZE, 8\n \n.equ IOCTL, 0x1D // Linux syscall\n.equ SIGACTION, 0x86 // Linux syscall\n.equ SYSPOLL, 0x16 // Linux syscall\n.equ CREATPOLL, 0x14 // Linux syscall\n.equ CTLPOLL, 0x15 // Linux syscall\n \n.equ TCGETS, 0x5401\n.equ TCSETS, 0x5402\n.equ ICANON, 2\n.equ ECHO, 10\n.equ POLLIN, 1\n.equ EPOLL_CTL_ADD, 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/*******************************************/\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 + 8\nsa_mask:\n .struct sa_mask + 8\nsa_flags:\n .struct sa_flags + 8\nsa_sigaction:\n .struct sa_sigaction + 8\nsa_fin:\n \n/* structure poll see doc linux */\n .struct 0\npoll_event:\n .struct poll_event + 8\npoll_fd: // File Descriptor\n .struct poll_fd + 8 \npoll_fin:\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nsMessResult: .ascii \" \"\nsMessValeur: .fill 11, 1, ' ' // size => 11\nszCarriageReturn: .asciz \"\\n\"\nszMessGameWin: .asciz \"You win in @ move number !!!!\\n\"\nszMessMoveError: .asciz \"Huh... Impossible move !!!!\\n\"\nszMessErreur: .asciz \"Error detected.\\n\"\nszMessErrInitTerm: .asciz \"Error terminal init.\\n\"\nszMessErrInitPoll: .asciz \"Error poll init.\\n\"\nszMessErreurKey: .asciz \"Error read key.\\n\"\nszMessSpaces: .asciz \" \"\nqGraine: .quad GRAINE\nszMessErr: .asciz \"Error code hexa : @ décimal : @ \\n\"\n \nszClear: .byte 0x1B \n .byte 'c' // console clear\n .byte 0\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nsZoneConv: .skip 24\nqCodeError: .skip 8\nibox: .skip 4 * NBBOX // game boxes\nqEnd: .skip 8 // 0 loop 1 = end loop\nqTouche: .skip KEYSIZE // 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\nstSigAction2: .skip sa_fin\nstSigAction3: .skip sa_fin\nstPoll1: .skip poll_fin // area poll structure\nstPoll2: .skip poll_fin\nstevents: .skip 16\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main \nmain: // entry of program \n mov x0,#0\n bl initTerm // terminal init\n cmp x0,0 // error ?\n blt 100f\n bl initPoll // epoll instance init\n cmp x0,0\n blt 99f\n mov x22,x0 // save epfd\n ldr x2,qAdribox\n mov x9,#0 // init counter \n mov x0,0\n1: // loop init boxs\n add x1,x0,#1 // box value\n str w1,[x2,x0, lsl #2] // store value\n add x0,x0,#1 // increment counter\n cmp x0,#NBBOX - 2 // end ?\n ble 1b\n mov x10,#15 // empty box location \n ldr x0,qAdribox\n bl shuffleGame\n2: // loop moves\n ldr x0,qAdribox\n bl displayGame\n3:\n mov x0,x22 // epfd\n bl waitKey\n cmp x0,0\n beq 3b // no ket pressed -> loop\n blt 99f // error ?\n bl readKey // read key \n cmp x0,#-1\n beq 99f // error \n cmp x0,3 // \n beq 5f\n cmp x0,113 // saisie q (quit) ?\n beq 5f\n cmp x0,81 // saisie Q (Quit)?\n beq 5f\n mov x1,x0 // key\n ldr x0,qAdribox\n bl keyMove // analyze key move \n ldr x0,qAdribox\n bl gameOK // end game ?\n cmp x0,#1\n bne 2b // no -> loop\n // win\n mov x0,x9 // move counter\n ldr x1,qAdrsZoneConv\n bl conversion10\n ldr x0,qAdrszMessGameWin\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n5:\n bl restauTerm // terminal restaur\n mov x0, #0 // return code\n b 100f\n99:\n bl restauTerm // terminal restaur\n mov x0,1 // return code error\n b 100f\n100: // standard end of the program \n mov x8, #EXIT // request to exit program\n svc #0 // perform the system call\n \nqAdrsMessValeur: .quad sMessValeur\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrsMessResult: .quad sMessResult\nqAdribox: .quad ibox\nqAdrszMessGameWin: .quad szMessGameWin\nqAdrstevents: .quad stevents\nqAdrszMessErreur: .quad szMessErreur\nqAdrstOldtio: .quad stOldtio\nqAdrstCurtio: .quad stCurtio\nqAdrstSigAction: .quad stSigAction\nqAdrstSigAction1: .quad stSigAction1\nqAdrSIG_IGN: .quad 1\nqAdrqEnd: .quad qEnd\nqAdrqTouche: .quad qTouche\nqAdrszMessErrInitTerm: .quad szMessErrInitTerm\nqAdrszMessErrInitPoll: .quad szMessErrInitPoll\nqAdrszMessErreurKey: .quad szMessErreurKey\n/******************************************************************/\n/* key move */ \n/******************************************************************/\n/* x0 contains boxs address */\n/* x1 contains key value */\n/* x9 move counter */\n/* x10 contains location empty box */\nkeyMove:\n stp x1,lr,[sp,-16]! // save registers\n mov x7,x0\n lsr x1,x1,16 \n cmp x1,#0x42 // down arrow \n bne 1f\n cmp x10,#4 // if x10 < 4 error\n blt 80f\n sub x2,x10,#4 // compute location\n b 90f\n1:\n cmp x1,#0x41 // high arrow\n bne 2f\n cmp x10,#11 // if x10 > 11 error\n bgt 80f\n add x2,x10,#4 // compute location\n b 90f\n2:\n cmp x1,#0x43 // right arrow\n bne 3f\n tst x10,#0b11 // if x10 = 0,4,8,12 error\n beq 80f\n sub x2,x10,#1 // compute location\n b 90f\n3:\n cmp x1,#0x44 // left arrow\n bne 100f\n and x3,x10,#0b11 // error if x10 = 3 7 11 and 15\n cmp x3,#3\n beq 80f\n add x2,x10,#1 // compute location\n b 90f\n \n80: // move error\n ldr x0,qAdrqCodeError\n mov x1,#1\n str x1,[x0]\n b 100f\n90: // white box and move box inversion\n ldr w3,[x7,x2,lsl #2]\n str w3,[x7,x10,lsl #2]\n mov x10,x2\n mov x3,#0\n str w3,[x7,x10,lsl #2]\n add x9,x9,#1 // increment move counter\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrqCodeError: .quad qCodeError\n/******************************************************************/\n/* shuffle game */ \n/******************************************************************/\n/* x0 contains boxs address */\nshuffleGame:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n mov x1,x0\n mov x0,NBSHUFFLE\n bl genereraleas\n lsl x4,x0,#1\n1:\n mov x0,#14\n bl genereraleas\n add x3,x0,#1\n mov x0,#14\n bl genereraleas\n add x5,x0,#1\n ldr w2,[x1,x3,lsl #2]\n ldr w0,[x1,x5,lsl #2]\n str w2,[x1,x5,lsl #2]\n str w0,[x1,x3,lsl #2]\n subs x4,x4,#1\n bgt 1b\n \n100:\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/******************************************************************/\n/* game Ok ? */ \n/******************************************************************/\n/* x0 contains boxs address */\ngameOK:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n mov x2,#0\n ldr w3,[x0,x2,lsl #2]\n add x2,x2,#1\n1:\n ldr w1,[x0,x2,lsl #2]\n cmp w1,w3\n bge 2f\n mov x0,#0 // game not Ok\n b 100f\n2:\n mov x3,x1\n add x2,x2,#1\n cmp x2,#NBBOX -2\n ble 1b\n mov x0,#1 // game Ok\n \n100:\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/******************************************************************/\n/* display game */ \n/******************************************************************/\n/* x0 contains boxs address */\ndisplayGame:\n stp x1,lr,[sp,-16]! // save registers\n // clear screen !\n mov x4,x0\n ldr x0,qAdrszClear\n bl affichageMess \n mov x2,#0\n ldr x1,qAdrsMessValeur\n1:\n ldr w0,[x4,x2,lsl #2]\n cmp w0,#0\n bne 2f\n ldr w0,iSpaces // store spaces\n str w0,[x1]\n b 3f\n2:\n bl conversion10 // call conversion decimal\n cmp x0,1\n beq 21f\n mov x0,0x20\n strh w0,[x1,#2]\n b 3f\n21:\n mov w0,0x2020\n str w0,[x1,#1]\n3:\n ldr x0,qAdrsMessResult\n bl affichageMess // display message\n add x0,x2,#1\n tst x0,#0b11\n bne 4f\n ldr x0,qAdrszCarriageReturn\n bl affichageMess // display message\n4:\n add x2,x2,#1\n cmp x2,#NBBOX - 1\n ble 1b\n ldr x0,qAdrszCarriageReturn\n bl affichageMess // display line return\n ldr x0,qAdrqCodeError // error detected ?\n ldr x1,[x0]\n cmp x1,#0\n beq 100f\n mov x1,#0 // raz error code\n str x1,[x0]\n ldr x0,qAdrszMessMoveError // display error message\n bl affichageMess\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\niSpaces: .int 0x00202020 // spaces\nqAdrszClear: .quad szClear \nqAdrszMessMoveError: .quad szMessMoveError\n \n/***************************************************/\n/* Generation random number */\n/***************************************************/\n/* x0 contains limit */\ngenereraleas:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n ldr x1,qAdrqGraine\n ldr x2,[x1]\n ldr x3,qNbDep1\n mul x2,x3,x2\n ldr x3,qNbDep2\n add x2,x2,x3\n str x2,[x1] // maj de la graine pour l appel suivant \n cmp x0,#0\n beq 100f\n udiv x3,x2,x0\n msub x0,x3,x0,x2 // résult = remainder\n \n100: // end function\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/*****************************************************/\nqAdrqGraine: .quad qGraine\nqNbDep1: .quad 0x0019660d\nqNbDep2: .quad 0x3c6ef35f\n \n/******************************************************************/\n/* traitement du signal */ \n/******************************************************************/\nsighandler:\n stp x0,lr,[sp,-16]! // save registers\n str x1,[sp,-16]! \n ldr x0,qAdrqEnd\n mov x1,#1 // maj zone end\n str x1,[x0]\n ldr x1,[sp],16\n ldp x0,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/***************************************************/\n/* display error message */\n/***************************************************/\n/* x0 contains error code x1 : message address */\ndisplayError:\n stp x2,lr,[sp,-16]! // save registers\n mov x2,x0 // save error code\n mov x0,x1\n bl affichageMess\n mov x0,x2 // error code\n ldr x1,qAdrsZoneConv\n bl conversion16 // conversion hexa\n ldr x0,qAdrszMessErr // display error message\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n mov x3,x0\n mov x0,x2 // error code\n ldr x1,qAdrsZoneConv // result address\n bl conversion10S // conversion decimale\n mov x0,x3\n ldr x1,qAdrsZoneConv\n bl strInsertAtCharInc // insert result at @ character\n bl affichageMess\n100:\n ldp x2,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszMessErr: .quad szMessErr\nqAdrsZoneConv: .quad sZoneConv\n/*********************************/\n/* init terminal state */\n/*********************************/\ninitTerm:\n stp x1,lr,[sp,-16]! // save registers\n /* read terminal state */\n mov x0,STDIN // input console\n mov x1,TCGETS\n ldr x2,qAdrstOldtio\n mov x8,IOCTL // call system Linux\n svc 0 \n cbnz x0,98f // error ?\n \n adr x0,sighandler // adresse routine traitement signal\n ldr x1,qAdrstSigAction // adresse structure sigaction\n str x0,[x1,sa_handler] // maj handler\n mov x0,SIGINT // signal type\n ldr x1,qAdrstSigAction\n mov x2,0\n mov x3,8\n mov x8,SIGACTION // call system\n svc 0 \n \n cmp x0,0 // error ?\n bne 98f\n mov x0,SIGQUIT\n ldr x1,qAdrstSigAction\n mov x2,0 // NULL\n mov x8,SIGACTION // call system \n svc 0 \n cmp x0,0 // error ?\n bne 98f\n mov x0,SIGTERM\n ldr x1,qAdrstSigAction\n mov x2,0 // NULL\n mov x8,SIGACTION // appel systeme \n svc 0 \n cmp x0,0\n bne 98f\n //\n adr x0,qAdrSIG_IGN // address signal igonre function\n ldr x1,qAdrstSigAction1\n str x0,[x1,sa_handler]\n mov x0,SIGTTOU //invalidate other process signal\n ldr x1,qAdrstSigAction1\n mov x2,0 // NULL\n mov x8,SIGACTION // call system \n svc 0 \n cmp x0,0\n bne 98f\n //\n /* read terminal current state */\n mov x0,STDIN\n mov x1,TCGETS\n ldr x2,qAdrstCurtio // address current termio\n mov x8,IOCTL // call systeme \n svc 0 \n cmp x0,0 // error ?\n bne 98f\n mov x2,ICANON | ECHO // no key pressed echo on display\n mvn x2,x2 // and one key \n ldr x1,qAdrstCurtio\n ldr x3,[x1,#term_c_lflag]\n and x3,x2,x2 // add flags \n str x3,[x1,#term_c_lflag] // and store\n mov x0,STDIN // maj terminal current state \n mov x1,TCSETS\n ldr x2,qAdrstCurtio\n mov x8,IOCTL // call system\n svc 0 \n cbz x0,100f\n98: // error display\n ldr x1,qAdrszMessErrInitTerm\n bl displayError\n mov x0,-1\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrstSigAction2: .quad stSigAction2\nqAdrstSigAction3: .quad stSigAction3\n/*********************************/\n/* init instance epool */\n/*********************************/\ninitPoll:\n stp x1,lr,[sp,-16]! // save registers\n ldr x0,qAdrstevents\n mov x1,STDIN // maj structure events\n str x1,[x0,#poll_fd] // maj FD\n mov x1,POLLIN // action code\n str x1,[x0,#poll_event]\n mov x0,0\n mov x8,CREATPOLL // create epoll instance\n svc 0\n cmp x0,0 // error ?\n ble 98f\n mov x10,x0 // return FD epoll instance\n mov x1,EPOLL_CTL_ADD\n mov x2,STDIN // Fd to we want add\n ldr x3,qAdrstevents // structure events address\n mov x8,CTLPOLL // call system control epoll\n svc 0\n cmp x0,0 // error ?\n blt 98f // no\n mov x0,x10 // return FD epoll instance\n b 100f\n98: // error display\n ldr x1,qAdrszMessErrInitPoll // error message\n bl displayError\n mov x0,-1\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/*********************************/\n/* wait key */\n/*********************************/\n/* x0 contains FD poll */\nwaitKey:\n stp x1,lr,[sp,-16]! // save registers\n ldr x11,qAdrqTouche // key address\n str xzr,[x11] // raz key\n1:\n ldr x1,qAdrqEnd // if signal ctrl-c -> end\n ldr x1,[x1]\n cbnz x1,100f\n \n ldr x1,qAdrstevents\n mov x2,12 // size events\n mov x3,1 // timeout = 1 TODO: ??\n mov x4,0\n mov x8,SYSPOLL // call system wait POLL\n svc 0 \n cmp x0,0 // key pressed ?\n bge 100f\n98: // error display\n ldr x1,qAdrszMessErreurKey // error message\n bl displayError\n mov x0,-1\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/*********************************/\n/* read key */\n/*********************************/\n/* x0 returns key value */\nreadKey:\n stp x1,lr,[sp,-16]! // save registers\n mov x0,STDIN // File Descriptor\n ldr x1,qAdrqTouche // buffer address\n mov x2,KEYSIZE // key size\n mov x8,READ // read key\n svc #0\n cmp x0,0 // error ?\n ble 98f\n ldr x2,qAdrqTouche // key address\n ldr x0,[x2]\n b 100f\n98: // error display\n ldr x1,qAdrszMessErreur // error message\n bl displayError\n mov x0,-1\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/*********************************/\n/* restaur terminal state */\n/*********************************/\nrestauTerm:\n stp x1,lr,[sp,-16]! // save registers\n mov x0,STDIN // end then restaur begin state terminal\n mov x1,TCSETS\n ldr x2,qAdrstOldtio\n mov x8,IOCTL // call system \n svc 0\n cbz x0,100f\n ldr x1,qAdrszMessErreur // error message\n bl displayError\n100:\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n \n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n "}}},{"rowIdx":78142,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/2048"},"task_name":{"kind":"string","value":"2048"},"task_description":{"kind":"string","value":"Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\n\n\nRules of the game\n\n The rules are that on each turn the player must choose a direction (up, down, left or right).\n All tiles move as far as possible in that direction, some move more than others. \n Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers. \n A move is valid when at least one tile can be moved, if only by combination. \n A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one). \n Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.\n To win, the player must create a tile with the number 2048. \n The player loses if no valid moves are possible.\n\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\n\n\nRequirements\n\n \"Non-greedy\" movement. \n The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n That is to say, that moving the tile row of:\n [2][2][2][2] \n\n to the right should result in: \n ......[4][4] \n\n and not:\n .........[8] \n\n \"Move direction priority\". \n If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n For example, moving the tile row of:\n ...[2][2][2] \n\n to the right should result in:\n ......[2][4] \n\n and not:\n ......[4][2] \n\n\n\n Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.\n Check for a win condition.\n Check for a lose condition.\n\n"},"language_url":{"kind":"string","value":"#Batch_File"},"language_name":{"kind":"string","value":"Batch File"},"code":{"kind":"string","value":":: 2048 Game Task from RosettaCode\n:: Batch File Implementation v2.0.1\n \n@echo off\nsetlocal enabledelayedexpansion\n\nrem initialization\n:begin_game\nset \"size=4\" %== board size ==%\nset \"score=0\" %== current score ==%\nset \"won=0\" %== boolean for winning ==%\nset \"target=2048\" %== as the game title says ==%\nfor /l %%R in (1,1,%size%) do for /l %%C in (1,1,%size%) do set \"X_%%R_%%C=0\"\n\nrem add two numbers in the board\ncall :addtile\ncall :addtile\n\nrem main game loop\n:main_loop\ncall :display\necho(\necho(Keys: WASD (Slide Movement), N (New game), P (Exit)\n\nrem get keypress trick\nset \"key=\"\nfor /f \"delims=\" %%? in ('xcopy /w \"%~f0\" \"%~f0\" 2^>nul') do if not defined key set \"key=%%?\"\nset \"key=%key:~-1%\"\n \nset \"changed=0\" %== boolean for changed board ==%\nset \"valid_key=0\" %== boolean for pressing WASD ==%\nrem process keypress\nif /i \"!key!\" equ \"W\" (set \"valid_key=1\" & call :slide \"C\" \"1,1,%size%\" \"X\")\nif /i \"!key!\" equ \"A\" (set \"valid_key=1\" & call :slide \"R\" \"1,1,%size%\" \"X\")\nif /i \"!key!\" equ \"S\" (set \"valid_key=1\" & call :slide \"C\" \"%size%,-1,1\" \"X\")\nif /i \"!key!\" equ \"D\" (set \"valid_key=1\" & call :slide \"R\" \"%size%,-1,1\" \"X\")\nif /i \"!key!\" equ \"N\" goto begin_game\nif /i \"!key!\" equ \"P\" exit /b 0\nif \"%valid_key%\" equ \"0\" goto main_loop\n\nrem check if the board changed\nif %changed% neq 0 call :addtile\n\nrem check for win condition\nif %won% equ 1 (\n set \"msg=Nice one... You WON^!^!\"\n goto gameover\n)\n\nrem check for lose condition\nif %blank_count% equ 0 (\n for /l %%R in (1,1,%size%) do for /l %%C in (1,1,%size%) do set \"LX_%%R_%%C=!X_%%R_%%C!\"\n set \"save_changed=%changed%\" & set \"changed=0\" %== save actual changed for test ==%\n call :slide \"C\" \"1,1,%size%\" \"LX\"\n call :slide \"R\" \"1,1,%size%\" \"LX\"\n if !changed! equ 0 (\n set \"msg=No moves are possible... Game Over :(\"\n goto gameover\n ) else set \"changed=!save_changed!\"\n)\ngoto main_loop\n\nrem add number to a random blank tile\n:addtile\nset \"blank_count=0\" %== blank tile counter ==%\nset \"new_tile=\" %== clearing ==%\nrem create pseudo-array blank_tiles\nfor /l %%R in (1,1,%size%) do (\n for /l %%C in (1,1,%size%) do (\n if !X_%%R_%%C! equ 0 (\n set \"blank_tiles[!blank_count!]=X_%%R_%%C\"\n set /a \"blank_count+=1\"\n )\n )\n)\nif %blank_count% equ 0 goto :EOF\nset /a \"pick_tile=%random%%%%blank_count%\"\nset \"new_tile=!blank_tiles[%pick_tile%]!\"\nset /a \"rnd_newnum=%random%%%10\"\nrem 10% chance new number is 4, 90% chance it's 2\nif %rnd_newnum% equ 5 (set \"%new_tile%=4\") else (set \"%new_tile%=2\")\nset /a \"blank_count-=1\" %== to be used for checking lose condition ==%\ngoto :EOF\n\nrem display the board\n:display\ncls\necho(2048 Game in Batch\necho(\nset \"wall=+\"\nfor /l %%C in (1,1,%size%) do set \"wall=!wall!----+\"\nfor /l %%R in (1,1,%size%) do (\n set \"disp_row=|\"\n for /l %%C in (1,1,%size%) do (\n if \"!new_tile!\" equ \"X_%%R_%%C\" (set \"DX_%%R_%%C= +!X_%%R_%%C!\") else (\n set \"DX_%%R_%%C=!X_%%R_%%C!\" \n if !X_%%R_%%C! lss 1000 set \"DX_%%R_%%C= !DX_%%R_%%C!\"\n if !X_%%R_%%C! lss 100 set \"DX_%%R_%%C= !DX_%%R_%%C!\"\n if !X_%%R_%%C! lss 10 set \"DX_%%R_%%C= !DX_%%R_%%C!\"\n if !X_%%R_%%C! equ 0 set \"DX_%%R_%%C= \"\n )\n set \"disp_row=!disp_row!!DX_%%R_%%C!|\"\n )\n echo(%wall%\n echo(!disp_row!\n)\necho(%wall%\necho(\necho(Score: %score%\ngoto :EOF\n\nrem the main slider of numbers in tiles\n:slide\nrem %%A and %%B are used here because sliding direction is variable\nfor /l %%A in (1,1,%size%) do (\n rem first slide: removing blank tiles in the middle\n set \"slide_1=\"\n set \"last_blank=0\" %== boolean if last tile is blank ==%\n for /l %%B in (%~2) do (\n if \"%~1\" equ \"R\" (set \"curr_tilenum=!%~3_%%A_%%B!\"\n ) else if \"%~1\" equ \"C\" (set \"curr_tilenum=!%~3_%%B_%%A!\")\n if !curr_tilenum! equ 0 (set \"last_blank=1\") else (\n set \"slide_1=!slide_1! !curr_tilenum!\"\n if !last_blank! equ 1 set \"changed=1\"\n set \"last_blank=0\"\n )\n )\n rem second slide: addition of numbered tiles\n rem slide_2 would be pseudo-array\n set \"slide_2_count=0\"\n set \"skip=1\" %== boolean for skipping after previous summing ==%\n if \"!slide_1!\" neq \"\" for %%S in (!slide_1! 0) do (\n if !skip! equ 1 (\n set \"prev_tilenum=%%S\" & set \"skip=0\"\n ) else if !skip! equ 0 (\n if %%S equ !prev_tilenum! (\n set /a \"sum=%%S+!prev_tilenum!\"\n if \"%~3\" equ \"X\" set /a \"score+=sum\"\n set \"changed=1\" & set \"skip=1\"\n rem check for winning condition!\n if !sum! equ !target! set \"won=1\"\n ) else (\n set \"sum=!prev_tilenum!\"\n set \"prev_tilenum=%%S\"\n )\n set \"slide_2[!slide_2_count!]=!sum!\"\n set /a \"slide_2_count+=1\"\n )\n )\n rem new values of tiles\n set \"slide_2_run=0\" %== running counter for slide_2 ==%\n for /l %%B in (%~2) do (\n if \"%~1\" equ \"R\" (set \"curr_tile=%~3_%%A_%%B\"\n ) else if \"%~1\" equ \"C\" (set \"curr_tile=%~3_%%B_%%A\")\n for %%? in (\"!slide_2_run!\") do (\n if %%~? lss !slide_2_count! (set \"!curr_tile!=!slide_2[%%~?]!\"\n ) else (set \"!curr_tile!=0\")\n )\n set /a \"slide_2_run+=1\"\n )\n)\ngoto :EOF\n\nrem game over xD\n:gameover\ncall :display\necho(\necho(!msg!\necho(\necho(Press any key to exit . . .\npause>nul\nexit /b 0"}}},{"rowIdx":78143,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle"},"task_name":{"kind":"string","value":"4-rings or 4-squares puzzle"},"task_description":{"kind":"string","value":"4-rings or 4-squares puzzle\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nReplace a, b, c, d, e, f, and\n g with the decimal\ndigits LOW ───► HIGH\n\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\nShow all output here.\n\n\n\n Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n Show only the number of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n\nRelated task\n\n Solve the no connection puzzle\n\n"},"language_url":{"kind":"string","value":"#R"},"language_name":{"kind":"string","value":"R"},"code":{"kind":"string","value":"# 4 rings or 4 squares puzzle\n \nperms <- function (n, r, v = 1:n, repeats.allowed = FALSE) {\n if (repeats.allowed) \n sub <- function(n, r, v) {\n if (r == 1) \n matrix(v, n, 1)\n else if (n == 1) \n matrix(v, 1, r)\n else {\n inner <- Recall(n, r - 1, v)\n cbind(rep(v, rep(nrow(inner), n)), matrix(t(inner), \n ncol = ncol(inner), nrow = nrow(inner) * n, \n byrow = TRUE))\n }\n }\n else sub <- function(n, r, v) {\n if (r == 1) \n matrix(v, n, 1)\n else if (n == 1) \n matrix(v, 1, r)\n else {\n X <- NULL\n for (i in 1:n) X <- rbind(X, cbind(v[i], Recall(n - 1, r - 1, v[-i])))\n X\n }\n }\n X <- sub(n, r, v[1:n])\n \n result <- vector(mode = \"numeric\")\n \n for(i in 1:nrow(X)){\n y <- X[i, ]\n x1 <- y[1] + y[2]\n x2 <- y[2] + y[3] + y[4]\n x3 <- y[4] + y[5] + y[6]\n x4 <- y[6] + y[7]\n if(x1 == x2 & x2 == x3 & x3 == x4) result <- rbind(result, y)\n }\n return(result)\n}\n \nprint_perms <- function(n, r, v = 1:n, repeats.allowed = FALSE, table.out = FALSE) {\n a <- perms(n, r, v, repeats.allowed)\n colnames(a) <- rep(\"\", ncol(a))\n rownames(a) <- rep(\"\", nrow(a)) \n if(!repeats.allowed){\n print(a)\n cat(paste('\\n', nrow(a), 'unique solutions from', min(v), 'to', max(v)))\n } else {\n cat(paste('\\n', nrow(a), 'non-unique solutions from', min(v), 'to', max(v)))\n }\n}\n \nregisterS3method(\"print_perms\", \"data.frame\", print_perms)\n \nprint_perms(7, 7, repeats.allowed = FALSE, table.out = TRUE)\nprint_perms(7, 7, v = 3:9, repeats.allowed = FALSE, table.out = TRUE)\nprint_perms(10, 7, v = 0:9, repeats.allowed = TRUE, table.out = FALSE)\n \n "}}},{"rowIdx":78144,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_solver"},"task_name":{"kind":"string","value":"15 puzzle solver"},"task_description":{"kind":"string","value":"Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.\n\nFor this task you will be using the following puzzle:\n\n\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on.\n\nThere are two solutions, of fifty-two moves:\n\nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd\n\nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\n\nExtra credit.\nSolve the following problem:\n\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n\n\nRelated Task\n\n 15 puzzle game\n A* search algorithm\n\n"},"language_url":{"kind":"string","value":"#Forth"},"language_name":{"kind":"string","value":"Forth"},"code":{"kind":"string","value":" \n#! /usr/bin/gforth\n \ncell 8 <> [if] s\" 64-bit system required\" exception throw [then]\n \n\\ In the stack comments below,\n\\ \"h\" stands for the hole position (0..15),\n\\ \"s\" for a 64-bit integer representing a board state,\n\\ \"t\" a tile value (0..15, 0 is the hole),\n\\ \"b\" for a bit offset of a position within a state,\n\\ \"m\" for a masked value (4 bits selected out of a 64-bit state),\n\\ \"w\" for a weight of a current path,\n\\ \"d\" for a direction constant (0..3)\n \n\\ Utility\n: 3dup 2 pick 2 pick 2 pick ;\n: 4dup 2over 2over ;\n: shift dup 0 > if lshift else negate rshift then ;\n \nhex 123456789abcdef0 decimal constant solution\n: row 2 rshift ; : col 3 and ;\n \n: up-valid? ( h -- f ) row 0 > ;\n: down-valid? ( h -- f ) row 3 < ;\n: left-valid? ( h -- f ) col 0 > ;\n: right-valid? ( h -- f ) col 3 < ;\n \n: up-cost ( h t -- 0|1 ) 1 - row swap row < 1 and ;\n: down-cost ( h t -- 0|1 ) 1 - row swap row > 1 and ;\n: left-cost ( h t -- 0|1 ) 1 - col swap col < 1 and ;\n: right-cost ( h t -- 0|1 ) 1 - col swap col > 1 and ;\n \n\\ To iterate over all possible directions, put direction-related functions into arrays:\n: ith ( u addr -- w ) swap cells + @ ;\ncreate valid? ' up-valid? , ' left-valid? , ' right-valid? , ' down-valid? , does> ith execute ;\ncreate cost ' up-cost , ' left-cost , ' right-cost , ' down-cost , does> ith execute ;\ncreate step -4 , -1 , 1 , 4 , does> ith ;\n \n\\ Advance from a single state to another:\n: bits ( h -- b ) 15 swap - 4 * ;\n: tile ( s b -- t ) rshift 15 and ;\n: new-state ( s h d -- s' ) step dup >r + bits 2dup tile ( s b t ) swap lshift tuck - swap r> 4 * shift + ;\n: new-weight ( w s h d -- w' ) >r tuck r@ step + bits tile r> cost + ;\n: advance ( w s h d -- w s h w' s' h' ) 4dup new-weight >r 3dup new-state >r step over + 2r> rot ;\n \n\\ Print a solution:\n: rollback 2drop drop ;\n: .dir ( u -- ) s\" d..r.l..u\" drop 4 + swap + c@ emit ;\n: .dirs ( .. -- ) 0 begin >r 3 pick -1 <> while 3 pick over - .dir rollback r> 1+ repeat r> ;\n: win cr .\" solved (read right-to-left!): \" .dirs .\" - \" . .\" moves\" bye ;\n \n\\ The main recursive function for depth-first search:\ncreate limit 1 , : deeper 1 limit +! ;\n: u-turn ( .. h2 w1 s1 h1 ) 4 pick 2 pick - ;\n: search ( .. h2 w1 s1 h1 )\n\tover solution = if win then\n\t2 pick limit @ > if exit then\n\t4 0 do dup i valid? if i step u-turn <> if i advance recurse rollback then then loop ;\n \n\\ Iterative-deepning search:\n: solve 1 limit ! begin search deeper again ;\n \n\\ -1 0 hex 0c9dfbae37254861 decimal 0 solve \\ uhm.\n -1 0 hex fe169b4c0a73d852 decimal 8 solve \\ the 52 moves case\n\\ -1 0 hex 123456789afbde0c decimal 14 solve \\ some trivial case, 3 moves\nbye\n "}}},{"rowIdx":78145,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/99_bottles_of_beer"},"task_name":{"kind":"string","value":"99 bottles of beer"},"task_description":{"kind":"string","value":"Task\n\nDisplay the complete lyrics for the song: 99 Bottles of Beer on the Wall.\n\n\n\nThe beer song\n\nThe lyrics follow this form:\n\n\n 99 bottles of beer on the wall\n\n 99 bottles of beer\n\n Take one down, pass it around\n\n 98 bottles of beer on the wall\n\n\n 98 bottles of beer on the wall\n\n 98 bottles of beer\n\n Take one down, pass it around\n\n 97 bottles of beer on the wall\n\n... and so on, until reaching 0 (zero).\n\nGrammatical support for 1 bottle of beer is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n\nSee also\n \n http://99-bottles-of-beer.net/\n Category:99_Bottles_of_Beer\n Category:Programming language families\n Wikipedia 99 bottles of beer\n\n"},"language_url":{"kind":"string","value":"#Apex"},"language_name":{"kind":"string","value":"Apex"},"code":{"kind":"string","value":" \n for(Integer i = 99; i=0; i--){\n system.debug(i + ' bottles of beer on the wall');\n system.debug('\\n');\n system.debug(i + ' bottles of beer on the wall');\n system.debug(i + ' bottles of beer');\n system.debug('take one down, pass it around');\n }\n "}}},{"rowIdx":78146,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game"},"task_name":{"kind":"string","value":"24 game"},"task_description":{"kind":"string","value":"The 24 Game tests one's mental arithmetic.\n\n\n\nTask\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to 24.\n\n Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n Division should use floating point or rational arithmetic, etc, to preserve remainders.\n Brackets are allowed, if using an infix expression evaluator.\n Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n The order of the digits when given does not have to be preserved.\n\n\nNotes\n The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\nRelated tasks\n 24 game/Solve\n\n\nReference\n The 24 Game on h2g2.\n\n"},"language_url":{"kind":"string","value":"#Elena"},"language_name":{"kind":"string","value":"Elena"},"code":{"kind":"string","value":"import system'routines;\nimport system'collections;\nimport system'dynamic;\nimport extensions;\n \n// --- Expression ---\n \nclass ExpressionTree\n{\n object theTree;\n \n constructor(s)\n {\n auto level := new Integer(0);\n \n s.forEach:(ch)\n {\n var node := new DynamicStruct();\n \n ch =>\n $43 { node.Level := level + 1; node.Operation := __subj add } // +\n $45 { node.Level := level + 1; node.Operation := __subj subtract } // -\n $42 { node.Level := level + 2; node.Operation := __subj multiply } // *\n $47 { node.Level := level + 2; node.Operation := __subj divide } // /\n $40 { level.append(10); ^ self } // (\n $41 { level.reduce(10); ^ self } // )\n : {\n node.Leaf := ch.toString().toReal();\n node.Level := level + 3\n };\n \n if (nil == theTree)\n { \n theTree := node \n }\n else\n {\n if (theTree.Level >= node.Level)\n {\n node.Left := theTree;\n node.Right := nilValue;\n \n theTree := node\n }\n else\n {\n var top := theTree;\n while ((nilValue != top.Right)&&(top.Right.Level < node.Level))\n { top := top.Right };\n \n node.Left := top.Right;\n node.Right := nilValue;\n \n top.Right := node\n }\n }\n }\n }\n \n eval(node)\n {\n if (node.containsProperty(subjconst Leaf))\n { \n ^ node.Leaf \n }\n else\n {\n var left := self.eval(node.Left);\n var right := self.eval(node.Right);\n \n var op := node.Operation;\n \n ^ op(left, right);\n }\n }\n \n get Value()\n <= eval(theTree);\n \n readLeaves(list, node)\n {\n if (nil == node)\n { InvalidArgumentException.raise() };\n \n if (node.containsProperty(subjconst Leaf))\n { \n list.append(node.Leaf) \n }\n else\n {\n self.readLeaves(list, node.Left);\n self.readLeaves(list, node.Right)\n }\n } \n \n readLeaves(list)\n <= readLeaves(list,theTree);\n}\n \n// --- Game ---\n \nclass TwentyFourGame\n{\n object theNumbers;\n \n constructor()\n {\n self.newPuzzle();\n }\n \n newPuzzle()\n {\n theNumbers := new object[]\n {\n 1 + randomGenerator.eval:9, \n 1 + randomGenerator.eval:9, \n 1 + randomGenerator.eval:9, \n 1 + randomGenerator.eval:9\n }\n }\n \n help()\n {\n console \n .printLine:\"------------------------------- Instructions ------------------------------\"\n .printLine:\"Four digits will be displayed.\"\n .printLine:\"Enter an equation using all of those four digits that evaluates to 24\"\n .printLine:\"Only * / + - operators and () are allowed\"\n .printLine:\"Digits can only be used once, but in any order you need.\"\n .printLine:\"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed\"\n .printLine:\"Submit a blank line to skip the current puzzle.\"\n .printLine:\"Type 'q' to quit\"\n .writeLine()\n .printLine:\"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)\"\n .printLine:\"------------------------------- --------------------------------------------\"\n }\n \n prompt()\n {\n theNumbers.forEach:(n){ console.print(n,\" \") };\n \n console.print:\": \"\n }\n \n resolve(expr)\n {\n var tree := new ExpressionTree(expr);\n \n var leaves := new ArrayList();\n tree.readLeaves:leaves;\n \n ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant()))\n { console.printLine:\"Invalid input. Enter an equation using all of those four digits. Try again.\"; ^ self };\n \n var result := tree.Value;\n if (result == 24)\n {\n console.printLine(\"Good work. \",expr,\"=\",result);\n \n self.newPuzzle()\n }\n else\n {\n console.printLine(\"Incorrect. \",expr,\"=\",result)\n }\n } \n}\n \nextension gameOp\n{\n playRound(expr)\n {\n if (expr == \"q\")\n {\n ^ false\n }\n else\n {\n if (expr == \"\")\n {\n console.printLine:\"Skipping this puzzle\"; self.newPuzzle()\n }\n else\n {\n try\n {\n self.resolve(expr)\n }\n catch(Exception e)\n {\n console.printLine:\"An error occurred. Check your input and try again.\"\n }\n };\n \n ^ true\n }\n }\n}\n \npublic program()\n{\n var game := new TwentyFourGame().help();\n \n while (game.prompt().playRound(console.readLine())) {}\n}"}}},{"rowIdx":78147,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/A%2BB"},"task_name":{"kind":"string","value":"A+B"},"task_description":{"kind":"string","value":"A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, A and B.\n\nTheir sum needs to be calculated.\n\n\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n \n\n\n\n(\n−\n1000\n≤\nA\n,\nB\n≤\n+\n1000\n)\n\n\n{\\displaystyle (-1000\\leq A,B\\leq +1000)}\n\n\n\n\nOutput data\n\nThe required output is one integer: the sum of A and B.\n\n\n\nExample\n\n\n\n input \n\n output \n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n"},"language_url":{"kind":"string","value":"#Clojure"},"language_name":{"kind":"string","value":"Clojure"},"code":{"kind":"string","value":"(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))\n3\n4\n=>7"}}},{"rowIdx":78148,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Ackermann_function"},"task_name":{"kind":"string","value":"Ackermann function"},"task_description":{"kind":"string","value":"The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.\n\n\n\nThe Ackermann function is usually defined as follows:\n\n\n\n\n\n\n\nA\n(\nm\n,\nn\n)\n=\n\n\n{\n\n\n\nn\n+\n1\n\n\n\nif \n\nm\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\n1\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\nA\n(\nm\n,\nn\n−\n1\n)\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n>\n0.\n\n\n\n\n\n\n\n\n{\\displaystyle A(m,n)={\\begin{cases}n+1&{\\mbox{if }}m=0\\\\A(m-1,1)&{\\mbox{if }}m>0{\\mbox{ and }}n=0\\\\A(m-1,A(m,n-1))&{\\mbox{if }}m>0{\\mbox{ and }}n>0.\\end{cases}}}\n\n\n\n\n\n\nIts arguments are never negative and it always terminates.\n\n\n\nTask\n\nWrite a function which returns the value of \n\n\n\nA\n(\nm\n,\nn\n)\n\n\n{\\displaystyle A(m,n)}\n\n. Arbitrary precision is preferred (since the function grows so quickly), but not required.\n\n\n\nSee also\n\n Conway chained arrow notation for the Ackermann function.\n\n"},"language_url":{"kind":"string","value":"#UNIX_Shell"},"language_name":{"kind":"string","value":"UNIX Shell"},"code":{"kind":"string","value":"ack() {\n local m=$1\n local n=$2\n if [ $m -eq 0 ]; then\n echo -n $((n+1))\n elif [ $n -eq 0 ]; then\n ack $((m-1)) 1\n else\n ack $((m-1)) $(ack $m $((n-1)))\n fi\n}"}}},{"rowIdx":78149,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/ABC_problem"},"task_name":{"kind":"string","value":"ABC problem"},"task_description":{"kind":"string","value":"ABC problem\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nYou are given a collection of ABC blocks (maybe like the ones you had when you were a kid).\n\nThere are twenty blocks with two letters on each block.\n\nA complete alphabet is guaranteed amongst all sides of the blocks.\n\nThe sample collection of blocks:\n\n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n\nTask\n\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.\n\n\n\nThe rules are simple:\n\n Once a letter on a block is used that block cannot be used again\n The function should be case-insensitive\n Show the output on this page for the following 7 words in the following example\n\n\nExample\n\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n"},"language_url":{"kind":"string","value":"#Forth"},"language_name":{"kind":"string","value":"Forth"},"code":{"kind":"string","value":": blockslist s\" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM\" ;\nvariable blocks\n: allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ;\n: freeblocks blockslist nip negate allot ;\n: toupper 223 and ;\n \n: clearblock ( addr-block -- ) \ndup '_' swap c!\ndup blocks @ - 1 and if 1- else 1+ then\n'_' swap c!\n;\n \n: pickblock ( addr-input -- addr-input+1 f )\ndup 1+ swap c@ toupper ( -- addr-input+1 c )\nblockslist nip 0 do\n blocks @ i + dup c@ 2 pick ( -- addr-input+1 c addri ci c )\n = if clearblock drop true unloop exit else drop then\nloop drop false\n;\n \n: abc ( addr-input u -- f )\nallotblocks\n0 do\n pickblock\n invert if drop false unloop exit cr then\nloop drop true\nfreeblocks\n;\n \n: .abc abc if .\" True\" else .\" False\" then ;"}}},{"rowIdx":78150,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/100_prisoners"},"task_name":{"kind":"string","value":"100 prisoners"},"task_description":{"kind":"string","value":"\n\nThe Problem\n\n 100 prisoners are individually numbered 1 to 100\n A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n Prisoners start outside the room\n They can decide some strategy before any enter the room.\n Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n A prisoner can open no more than 50 drawers.\n A prisoner tries to find his own number.\n A prisoner finding his own number is then held apart from the others.\n If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. \n\n\nThe task\n\n Simulate several thousand instances of the game where the prisoners randomly open drawers\n Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n First opening the drawer whose outside number is his prisoner number.\n If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n\n\nReferences\n\n The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n wp:100 prisoners problem\n 100 Prisoners Escape Puzzle DataGenetics.\n Random permutation statistics#One hundred prisoners on Wikipedia.\n\n"},"language_url":{"kind":"string","value":"#D"},"language_name":{"kind":"string","value":"D"},"code":{"kind":"string","value":"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}"}}},{"rowIdx":78151,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Abundant_odd_numbers"},"task_name":{"kind":"string","value":"Abundant odd numbers"},"task_description":{"kind":"string","value":"An Abundant number is a number n for which the sum of divisors σ(n) > 2n,\n\nor, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.\n\n\n\nE.G.\n\n12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);\n\n or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).\n\n\n\nAbundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.\n\nTo make things more interesting, this task is specifically about finding odd abundant numbers.\n\n\n\nTask\nFind and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\nFind and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\nFind and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\nReferences\n\n OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n"},"language_url":{"kind":"string","value":"#Vlang"},"language_name":{"kind":"string","value":"Vlang"},"code":{"kind":"string","value":"fn divisors(n i64) []i64 {\n mut divs := [i64(1)]\n mut divs2 := []i64{}\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n divs << i\n if i != j {\n divs2 << j\n }\n }\n }\n for i := divs2.len - 1; i >= 0; i-- {\n divs << divs2[i]\n }\n return divs\n}\n \nfn sum(divs []i64) i64 {\n mut tot := i64(0)\n for div in divs {\n tot += div\n }\n return tot\n}\n \nfn sum_str(divs []i64) string {\n mut s := \"\"\n for div in divs {\n s += \"${u8(div)} + \"\n }\n return s[0..s.len-3]\n}\n \nfn abundant_odd(search_from i64, count_from int, count_to int, print_one bool) i64 {\n mut count := count_from\n mut n := search_from\n for ; count < count_to; n += 2 {\n divs := divisors(n)\n tot := sum(divs)\n if tot > n {\n count++\n if print_one && count < count_to {\n continue\n }\n s := sum_str(divs)\n if !print_one {\n println(\"${count:2}. ${n:5} < $s = $tot\")\n } else {\n println(\"$n < $s = $tot\")\n }\n }\n }\n return n\n}\n \nconst max = 25\n \nfn main() {\n println(\"The first $max abundant odd numbers are:\")\n n := abundant_odd(1, 0, 25, false)\n \n println(\"\\nThe one thousandth abundant odd number is:\")\n abundant_odd(n, 25, 1000, true)\n \n println(\"\\nThe first abundant odd number above one billion is:\")\n abundant_odd(1_000_000_001, 0, 1, true)\n}"}}},{"rowIdx":78152,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/21_game"},"task_name":{"kind":"string","value":"21 game"},"task_description":{"kind":"string","value":"21 game\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n21 is a two player game, the game is played by choosing\na number (1, 2, or 3) to be added to the running total.\n\nThe game is won by the player whose chosen number causes the running total\nto reach exactly 21.\n\nThe running total starts at zero.\nOne player will be the computer.\n\nPlayers alternate supplying a number to be added to the running total.\n\n\n\nTask\n\nWrite a computer program that will:\n\n do the prompting (or provide a button menu), \n check for errors and display appropriate error messages, \n do the additions (add a chosen number to the running total), \n display the running total, \n provide a mechanism for the player to quit/exit/halt/stop/close the program,\n issue a notification when there is a winner, and\n determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n"},"language_url":{"kind":"string","value":"#Quackery"},"language_name":{"kind":"string","value":"Quackery"},"code":{"kind":"string","value":" [ say\n \"Who goes first: Computer, Player\"\n say \" or Random?\" cr\n [ $ \"Enter C, P or R: \" input\n dup size 1 != 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 ( --> )"}}},{"rowIdx":78153,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game/Solve"},"task_name":{"kind":"string","value":"24 game/Solve"},"task_description":{"kind":"string","value":"task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\n\n\nRelated task\n\n Arithmetic Evaluator\n\n"},"language_url":{"kind":"string","value":"#Go"},"language_name":{"kind":"string","value":"Go"},"code":{"kind":"string","value":"package main\n \nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n \nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n \ntype frac struct {\n\tnum, denom int\n}\n \n// Expression: can either be a single number, or a result of binary\n// operation from left and right node\ntype Expr struct {\n\top int\n\tleft, right *Expr\n\tvalue frac\n}\n \nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n \nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n \n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n \n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n \n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n \n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n \nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n \n\tl, r := expr_eval(x.left), expr_eval(x.right)\n \n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n \n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n \n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n \n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n \nfunc solve(ex_in []*Expr) bool {\n\t// only one expression left, meaning all numbers are arranged into\n\t// a binary tree, so evaluate and see if we get 24\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n \n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n \n\t// try to combine a pair of expressions into one, thus reduce\n\t// the list length by 1, and recurse down\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n \n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n \n\t\t\t// try all 4 operators\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n \n\t\t\t// also - and / are not commutative, so swap arguments\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n \n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n \n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n \n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n \nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n \n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\": \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}"}}},{"rowIdx":78154,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_game"},"task_name":{"kind":"string","value":"15 puzzle game"},"task_description":{"kind":"string","value":" \n\n\nTask\n\nImplement the Fifteen Puzzle Game.\n\n\n\nThe 15-puzzle is also known as:\n\n Fifteen Puzzle\n Gem Puzzle\n Boss Puzzle\n Game of Fifteen\n Mystic Square\n 14-15 Puzzle\n and some others.\n\n\nRelated Tasks\n\n 15 Puzzle Solver\n 16 Puzzle Game\n\n"},"language_url":{"kind":"string","value":"#Action.21"},"language_name":{"kind":"string","value":"Action!"},"code":{"kind":"string","value":"DEFINE BOARDSIZE=\"16\"\nDEFINE X0=\"13\"\nDEFINE Y0=\"6\"\nDEFINE ITEMW=\"3\"\nDEFINE ITEMH=\"2\"\n \nBYTE ARRAY board(BOARDSIZE)\nBYTE emptyX,emptyY,solved,first=[1]\n \nBYTE FUNC Index(BYTE x,y)\nRETURN (x+y*4)\n \nPROC UpdateItem(BYTE x,y)\n BYTE item\n \n Position(X0+x*ITEMW+1,Y0+y*ITEMH+1)\n item=board(Index(x,y))\n IF item=0 THEN\n Print(\" \")\n ELSEIF item<10 THEN\n Put(160) Put(item+176)\n ELSE\n Put(item/10+176)\n Put(item MOD 10+176)\n FI\nRETURN\n \nPROC UpdateBoard()\n BYTE x,y\n \n FOR y=0 TO 3\n DO\n FOR x=0 TO 3\n DO\n UpdateItem(x,y) \n OD\n OD\nRETURN\n \nPROC DrawGrid()\n CHAR ARRAY\n top=[13 17 18 18 23 18 18 23 18 18 23 18 18 5],\n row=[13 124 32 32 124 32 32 124 32 32 124 32 32 124],\n mid=[13 1 18 18 19 18 18 19 18 18 19 18 18 4],\n bot=[13 26 18 18 24 18 18 24 18 18 24 18 18 3]\n BYTE y,i\n \n y=Y0\n Position(X0,y) Print(top) y==+1\n Position(X0,y) Print(row) y==+1\n FOR i=0 TO 2\n DO\n Position(X0,y) Print(mid) y==+1\n Position(X0,y) Print(row) y==+1\n OD\n Position(X0,y) Print(bot)\nRETURN\n \nPROC DrawBoard()\n DrawGrid()\n UpdateBoard()\nRETURN\n \nPROC FindEmpty()\n BYTE i\n \n FOR i=0 TO BOARDSIZE-1\n DO\n IF board(i)=0 THEN\n emptyX=i MOD 4\n emptyY=i/4\n FI\n OD\nRETURN\n \nPROC Wait(BYTE frames)\n BYTE RTCLOK=$14\n frames==+RTCLOK\n WHILE frames#RTCLOK DO OD\nRETURN\n \nPROC UpdateStatus()\n Position(9,3) Print(\"Game status: \")\n IF solved THEN\n Print(\"SOLVED !\")\n IF first=0 THEN\n Sound(0,100,10,5) Wait(5)\n Sound(0,60,10,5) Wait(5)\n Sound(0,40,10,5) Wait(5)\n Sound(0,0,0,0)\n FI\n first=0\n ELSE\n Print(\"Shuffled\")\n FI\nRETURN\n \nPROC InitBoard()\n BYTE i\n \n FOR i=1 TO BOARDSIZE\n DO\n board(i-1)=i MOD 16\n OD\n FindEmpty()\n solved=1\n UpdateStatus()\nRETURN\n \nBYTE FUNC IsSolved()\n BYTE i\n \n FOR i=1 TO BOARDSIZE\n DO\n IF board(i-1)#i MOD 16 THEN\n RETURN (0)\n FI\n OD\nRETURN (1)\n \nPROC CheckStatus()\n BYTE tmp\n \n tmp=IsSolved()\n IF solved#tmp THEN\n solved=tmp\n UpdateStatus()\n FI\nRETURN\n \nPROC Swap(BYTE x1,y1,x2,y2)\n BYTE tmp,i1,i2\n \n i1=Index(x1,y1)\n i2=Index(x2,y2)\n tmp=board(i1)\n board(i1)=board(i2)\n board(i2)=tmp\n UpdateItem(x1,y1)\n UpdateItem(x2,y2)\n CheckStatus()\nRETURN\n \nPROC Shuffle()\n BYTE i,j,tmp\n \n i=BOARDSIZE-1\n WHILE i>0\n DO\n j=Rand(i)\n tmp=board(i)\n board(i)=board(j)\n board(j)=tmp\n i==-1\n OD\n FindEmpty()\n UpdateBoard()\n CheckStatus()\nRETURN\n \nPROC MoveLeft()\n IF emptyX=0 THEN RETURN FI\n Swap(emptyX,emptyY,emptyX-1,emptyY)\n emptyX==-1\nRETURN\n \nPROC MoveRight()\n IF emptyX=3 THEN RETURN FI\n Swap(emptyX,emptyY,emptyX+1,emptyY)\n emptyX==+1\nRETURN\n \nPROC MoveUp()\n IF emptyY=0 THEN RETURN FI\n Swap(emptyX,emptyY,emptyX,emptyY-1)\n emptyY==-1\nRETURN\n \nPROC MoveDown()\n IF emptyY=3 THEN RETURN FI\n Swap(emptyX,emptyY,emptyX,emptyY+1)\n emptyY==+1\nRETURN\n \nPROC Main()\n BYTE k,lastStick=[255],currStick,\n CH=$02FC, ;Internal hardware value for last key pressed\n CRSINH=$02F0 ;Controls visibility of cursor\n \n Graphics(0)\n SetColor(2,0,2)\n CRSINH=1 ;hide cursor\n Position(10,18) Print(\"Joystick - move tiles\")\n Position(9,19) Print(\"Space bar - shuffle\")\n Position(15,20) Print(\"ESC - exit\")\n InitBoard()\n DrawBoard()\n DO\n currStick=Stick(0)\n IF currStick#lastStick THEN\n IF currStick=11 THEN MoveRight()\n ELSEIF currStick=7 THEN MoveLeft()\n ELSEIF currStick=13 THEN MoveUp()\n ELSEIF currStick=14 THEN MoveDown()\n FI\n FI\n lastStick=currStick\n k=CH\n IF k#$FF THEN CH=$FF FI\n IF k=33 THEN Shuffle()\n ELSEIF k=28 THEN EXIT\n FI\n OD\nRETURN"}}},{"rowIdx":78155,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/2048"},"task_name":{"kind":"string","value":"2048"},"task_description":{"kind":"string","value":"Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\n\n\nRules of the game\n\n The rules are that on each turn the player must choose a direction (up, down, left or right).\n All tiles move as far as possible in that direction, some move more than others. \n Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers. \n A move is valid when at least one tile can be moved, if only by combination. \n A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one). \n Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.\n To win, the player must create a tile with the number 2048. \n The player loses if no valid moves are possible.\n\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\n\n\nRequirements\n\n \"Non-greedy\" movement. \n The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n That is to say, that moving the tile row of:\n [2][2][2][2] \n\n to the right should result in: \n ......[4][4] \n\n and not:\n .........[8] \n\n \"Move direction priority\". \n If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n For example, moving the tile row of:\n ...[2][2][2] \n\n to the right should result in:\n ......[2][4] \n\n and not:\n ......[4][2] \n\n\n\n Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.\n Check for a win condition.\n Check for a lose condition.\n\n"},"language_url":{"kind":"string","value":"#BASIC"},"language_name":{"kind":"string","value":"BASIC"},"code":{"kind":"string","value":" \nSCREEN 13\nPALETTE 1, pColor(35, 33, 31)\nPALETTE 2, pColor(46, 46, 51)\nPALETTE 3, pColor(59, 56, 50)\nPALETTE 4, pColor(61, 44, 30)\nPALETTE 5, pColor(61, 37, 25)\nPALETTE 6, pColor(62, 31, 24)\nPALETTE 7, pColor(62, 24, 15)\nPALETTE 8, pColor(59, 52, 29)\nPALETTE 9, pColor(59, 51, 24)\nPALETTE 10, pColor(59, 50, 20)\nPALETTE 11, pColor(59, 49, 16)\nPALETTE 12, pColor(59, 49, 12)\nPALETTE 13, pColor(15, 15, 13)\nPALETTE 14, pColor(23, 22, 20)\n \nDIM SHARED gDebug\nDIM SHARED gOriginX\nDIM SHARED gOriginY\nDIM SHARED gTextOriginX\nDIM SHARED gTextOriginY\nDIM SHARED gSquareSide\nDIM SHARED gGridSize\n \ngGridSize = 4 ' grid size (4 -> 4x4)\n \nDIM SHARED gGrid(gGridSize, gGridSize)\nDIM SHARED gScore\n \n' Don't touch these numbers, seriously\n \ngOriginX = 75 'pixel X of top left of grid\ngOriginY = 12 'pixel Y of top right of grid\ngTextOriginX = 11\ngTextOriginY = 3\ngSquareSide = 38 'width/height of block in pixels\n \n \n'set up all the things!\ngDebug = 0\n \nRANDOMIZE TIMER\nCLS\n \nstart:\ninitGrid\ninitGraphicGrid\nrenderGrid\nupdateScore\n \ngScore = 0\n \nLOCATE 23, 1\nPRINT \"Move with arrow keys. (R)estart, (Q)uit\"\n \n' keyboard input loop\nDO\n DO\n k$ = INKEY$\n LOOP UNTIL k$ <> \"\"\n \n SELECT CASE k$\n CASE CHR$(0) + CHR$(72) 'up\n processMove (\"u\")\n CASE CHR$(0) + CHR$(80) 'down\n processMove (\"d\")\n CASE CHR$(0) + CHR$(77) 'right\n processMove (\"r\")\n CASE CHR$(0) + CHR$(75) 'left\n processMove (\"l\")\n CASE CHR$(27) 'escape\n GOTO programEnd\n CASE \"q\"\n GOTO programEnd\n CASE \"Q\"\n GOTO programEnd\n CASE \"r\"\n GOTO start\n CASE \"R\"\n GOTO start\n END SELECT\nLOOP\n \nprogramEnd:\n \nSUB addblock\n DIM emptyCells(gGridSize * gGridSize, 2)\n emptyCellCount = 0\n \n FOR x = 0 TO gGridSize - 1\n FOR y = 0 TO gGridSize - 1\n IF gGrid(x, y) = 0 THEN\n emptyCells(emptyCellCount, 0) = x\n emptyCells(emptyCellCount, 1) = y\n emptyCellCount = emptyCellCount + 1\n END IF\n NEXT y\n NEXT x\n \n IF emptyCellCount > 0 THEN\n index = INT(RND * emptyCellCount)\n num = CINT(RND + 1) * 2\n gGrid(emptyCells(index, 0), emptyCells(index, 1)) = num\n END IF\n \nEND SUB\n \nSUB drawNumber (num, xPos, yPos)\n SELECT CASE num\n CASE 0: c = 16\n CASE 2: c = 2\n CASE 4: c = 3\n CASE 8: c = 4\n CASE 16: c = 5\n CASE 32: c = 6\n CASE 64: c = 7\n CASE 128: c = 8\n CASE 256: c = 9\n CASE 512: c = 10\n CASE 1024: c = 11\n CASE 2048: c = 12\n CASE 4096: c = 13\n CASE 8192: c = 13\n CASE ELSE: c = 13\n END SELECT\n \n x = xPos * (gSquareSide + 2) + gOriginX + 1\n y = yPos * (gSquareSide + 2) + gOriginY + 1\n LINE (x + 1, y + 1)-(x + gSquareSide - 1, y + gSquareSide - 1), c, BF\n \n IF num > 0 THEN\n LOCATE gTextOriginY + 1 + (yPos * 5), gTextOriginX + (xPos * 5)\n PRINT \" \"\n LOCATE gTextOriginY + 2 + (yPos * 5), gTextOriginX + (xPos * 5)\n PRINT pad$(num)\n LOCATE gTextOriginY + 3 + (yPos * 5), gTextOriginX + (xPos * 5)\n 'PRINT \" \"\n END IF\n \nEND SUB\n \nFUNCTION getAdjacentCell (x, y, d AS STRING)\n \n IF (d = \"l\" AND x = 0) OR (d = \"r\" AND x = gGridSize - 1) OR (d = \"u\" AND y = 0) OR (d = \"d\" AND y = gGridSize - 1) THEN\n getAdjacentCell = -1\n ELSE\n SELECT CASE d\n CASE \"l\": getAdjacentCell = gGrid(x - 1, y)\n CASE \"r\": getAdjacentCell = gGrid(x + 1, y)\n \n CASE \"u\": getAdjacentCell = gGrid(x, y - 1)\n CASE \"d\": getAdjacentCell = gGrid(x, y + 1)\n END SELECT\n END IF\n \nEND FUNCTION\n \n'Draws the outside grid (doesn't render tiles)\nSUB initGraphicGrid\n \n gridSide = (gSquareSide + 2) * gGridSize\n \n LINE (gOriginX, gOriginY)-(gOriginX + gridSide, gOriginY + gridSide), 14, BF 'outer square, 3 thick\n LINE (gOriginX, gOriginY)-(gOriginX + gridSide, gOriginY + gridSide), 1, B 'outer square, 3 thick\n LINE (gOriginX - 1, gOriginY - 1)-(gOriginX + gridSide + 1, gOriginY + gridSide + 1), 1, B\n LINE (gOriginX - 2, gOriginY - 2)-(gOriginX + gridSide + 2, gOriginY + gridSide + 2), 1, B\n \n FOR x = gOriginX + gSquareSide + 2 TO gOriginX + (gSquareSide + 2) * gGridSize STEP gSquareSide + 2 ' horizontal lines\n LINE (x, gOriginY)-(x, gOriginY + gridSide), 1\n NEXT x\n \n FOR y = gOriginY + gSquareSide + 2 TO gOriginY + (gSquareSide + 2) * gGridSize STEP gSquareSide + 2 ' vertical lines\n LINE (gOriginX, y)-(gOriginX + gridSide, y), 1\n NEXT y\n \nEND SUB\n \n'Init the (data) grid with 0s\nSUB initGrid\n FOR x = 0 TO 3\n FOR y = 0 TO 3\n gGrid(x, y) = 0\n NEXT y\n NEXT x\n \n addblock\n addblock\n \nEND SUB\n \nSUB moveBlock (sourceX, sourceY, targetX, targetY, merge)\n \n IF sourceX < 0 OR sourceX >= gGridSize OR sourceY < 0 OR sourceY >= gGridSize AND gDebug = 1 THEN\n LOCATE 0, 0\n PRINT \"moveBlock: source coords out of bounds\"\n END IF\n \n IF targetX < 0 OR targetX >= gGridSize OR targetY < 0 OR targetY >= gGridSize AND gDebug = 1 THEN\n LOCATE 0, 0\n PRINT \"moveBlock: source coords out of bounds\"\n END IF\n \n sourceSquareValue = gGrid(sourceX, sourceY)\n targetSquareValue = gGrid(targetX, targetY)\n \n IF merge = 1 THEN\n \n IF sourceSquareValue = targetSquareValue THEN\n gGrid(sourceX, sourceY) = 0\n gGrid(targetX, targetY) = targetSquareValue * 2\n gScore = gScore + targetSquareValue * 2 ' Points!\n ELSEIF gDebug = 1 THEN\n LOCATE 0, 0\n PRINT \"moveBlock: Attempted to merge unequal sqs\"\n END IF\n \n ELSE\n \n IF targetSquareValue = 0 THEN\n gGrid(sourceX, sourceY) = 0\n gGrid(targetX, targetY) = sourceSquareValue\n ELSEIF gDebug = 1 THEN\n LOCATE 0, 0\n PRINT \"moveBlock: Attempted to move to non-empty block\"\n END IF\n \n END IF\n \nEND SUB\n \nFUNCTION pad$ (num)\n strNum$ = LTRIM$(STR$(num))\n \n SELECT CASE LEN(strNum$)\n CASE 1: pad = \" \" + strNum$ + \" \"\n CASE 2: pad = \" \" + strNum$ + \" \"\n CASE 3: pad = \" \" + strNum$\n CASE 4: pad = strNum$\n END SELECT\n \nEND FUNCTION\n \nFUNCTION pColor (r, g, b)\n pColor = (r + g * 256 + b * 65536)\nEND FUNCTION\n \nSUB processMove (dir AS STRING)\n ' dir can be 'l', 'r', 'u', or 'd'\n \n hasMoved = 0\n \n IF dir = \"l\" THEN\n \n FOR y = 0 TO gGridSize - 1\n wasMerge = 0\n FOR x = 0 TO gGridSize - 1\n GOSUB processBlock\n NEXT x\n NEXT y\n \n ELSEIF dir = \"r\" THEN\n \n FOR y = 0 TO gGridSize - 1\n wasMerge = 0\n FOR x = gGridSize - 1 TO 0 STEP -1\n GOSUB processBlock\n NEXT x\n NEXT y\n \n ELSEIF dir = \"u\" THEN\n FOR x = 0 TO gGridSize - 1\n wasMerge = 0\n FOR y = 0 TO gGridSize - 1\n GOSUB processBlock\n NEXT y\n NEXT x\n \n ELSEIF dir = \"d\" THEN\n FOR x = 0 TO gGridSize - 1\n wasMerge = 0\n FOR y = gGridSize - 1 TO 0 STEP -1\n GOSUB processBlock\n NEXT y\n NEXT x\n \n END IF\n \n GOTO processMoveEnd\n \nmoveToObstacle:\n curX = x\n curY = y\n \n DO WHILE getAdjacentCell(curX, curY, dir) = 0\n SELECT CASE dir\n CASE \"l\": curX = curX - 1\n CASE \"r\": curX = curX + 1\n CASE \"u\": curY = curY - 1\n CASE \"d\": curY = curY + 1\n END SELECT\n LOOP\n RETURN\n \nprocessBlock:\n \n merge = 0\n IF gGrid(x, y) <> 0 THEN ' have block\n \n GOSUB moveToObstacle ' figure out where it can be moved to\n IF getAdjacentCell(curX, curY, dir) = gGrid(x, y) AND wasMerge = 0 THEN ' obstacle can be merged with\n merge = 1\n wasMerge = 1\n ELSE\n wasMerge = 0\n END IF\n \n IF curX <> x OR curY <> y OR merge = 1 THEN\n mergeDirX = 0\n mergeDirY = 0\n IF merge = 1 THEN\n SELECT CASE dir\n CASE \"l\": mergeDirX = -1\n CASE \"r\": mergeDirX = 1\n CASE \"u\": mergeDirY = -1\n CASE \"d\": mergeDirY = 1\n END SELECT\n END IF\n \n CALL moveBlock(x, y, curX + mergeDirX, curY + mergeDirY, merge) ' move to before obstacle or merge\n hasMoved = 1\n END IF\n END IF\n RETURN\n \nprocessMoveEnd:\n \n IF hasMoved = 1 THEN addblock\n renderGrid\n updateScore\n \nEND SUB\n \nSUB renderGrid\n FOR x = 0 TO gGridSize - 1\n FOR y = 0 TO gGridSize - 1\n CALL drawNumber(gGrid(x, y), x, y)\n NEXT y\n NEXT x\nEND SUB\n \nSUB updateScore\n LOCATE 1, 10\n PRINT \"Score:\" + STR$(gScore)\nEND SUB\n "}}},{"rowIdx":78156,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle"},"task_name":{"kind":"string","value":"4-rings or 4-squares puzzle"},"task_description":{"kind":"string","value":"4-rings or 4-squares puzzle\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nReplace a, b, c, d, e, f, and\n g with the decimal\ndigits LOW ───► HIGH\n\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\nShow all output here.\n\n\n\n Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n Show only the number of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n\nRelated task\n\n Solve the no connection puzzle\n\n"},"language_url":{"kind":"string","value":"#Racket"},"language_name":{"kind":"string","value":"Racket"},"code":{"kind":"string","value":"#lang racket\n \n(define solution? (match-lambda [(list a b c d e f g) (= (+ a b) (+ b c d) (+ d e f) (+ f g))]))\n \n(define (fold-4-rings-or-4-squares-puzzle lo hi kons k0)\n (for*/fold ((k k0))\n ((combination (in-combinations (range lo (add1 hi)) 7))\n (permutation (in-permutations combination))\n #:when (solution? permutation))\n (kons permutation k)))\n \n(fold-4-rings-or-4-squares-puzzle 1 7 cons null)\n(fold-4-rings-or-4-squares-puzzle 3 9 cons null)\n(fold-4-rings-or-4-squares-puzzle 0 9 (λ (ignored-solution count) (add1 count)) 0)"}}},{"rowIdx":78157,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_solver"},"task_name":{"kind":"string","value":"15 puzzle solver"},"task_description":{"kind":"string","value":"Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.\n\nFor this task you will be using the following puzzle:\n\n\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on.\n\nThere are two solutions, of fifty-two moves:\n\nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd\n\nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\n\nExtra credit.\nSolve the following problem:\n\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n\n\nRelated Task\n\n 15 puzzle game\n A* search algorithm\n\n"},"language_url":{"kind":"string","value":"#Fortran"},"language_name":{"kind":"string","value":"Fortran"},"code":{"kind":"string","value":"59: H = MOD(ABS(PRODUCT(BRD)),APRIME)\n004016E3 mov esi,1\n004016E8 mov ecx,1\n004016ED cmp ecx,2\n004016F0 jg MAIN$SLIDESOLVE+490h (0040171e)\n004016F2 cmp ecx,1\n004016F5 jl MAIN$SLIDESOLVE+46Eh (004016fc)\n004016F7 cmp ecx,2\n004016FA jle MAIN$SLIDESOLVE+477h (00401705)\n004016FC xor eax,eax\n004016FE mov dword ptr [ebp-54h],eax\n00401701 dec eax\n00401702 bound eax,qword ptr [ebp-54h]\n00401705 imul edx,ecx,4\n00401708 mov edx,dword ptr H (00473714)[edx]\n0040170E imul edx,esi\n00401711 mov esi,edx\n00401713 mov eax,ecx\n00401715 add eax,1\n0040171A mov ecx,eax\n0040171C jmp MAIN$SLIDESOLVE+45Fh (004016ed)\n0040171E mov eax,esi\n00401720 cmp eax,0\n00401725 jge MAIN$SLIDESOLVE+49Bh (00401729)\n00401727 neg eax\n00401729 mov edx,10549h\n0040172E mov dword ptr [ebp-54h],edx\n00401731 cdq\n00401732 idiv eax,dword ptr [ebp-54h]\n00401735 mov eax,edx\n00401737 mov dword ptr [H (00473714)],eax\n60: write (6,*) H,bored\n"}}},{"rowIdx":78158,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/99_bottles_of_beer"},"task_name":{"kind":"string","value":"99 bottles of beer"},"task_description":{"kind":"string","value":"Task\n\nDisplay the complete lyrics for the song: 99 Bottles of Beer on the Wall.\n\n\n\nThe beer song\n\nThe lyrics follow this form:\n\n\n 99 bottles of beer on the wall\n\n 99 bottles of beer\n\n Take one down, pass it around\n\n 98 bottles of beer on the wall\n\n\n 98 bottles of beer on the wall\n\n 98 bottles of beer\n\n Take one down, pass it around\n\n 97 bottles of beer on the wall\n\n... and so on, until reaching 0 (zero).\n\nGrammatical support for 1 bottle of beer is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n\nSee also\n \n http://99-bottles-of-beer.net/\n Category:99_Bottles_of_Beer\n Category:Programming language families\n Wikipedia 99 bottles of beer\n\n"},"language_url":{"kind":"string","value":"#APL"},"language_name":{"kind":"string","value":"APL"},"code":{"kind":"string","value":" bob ← { (⍕⍵), ' bottle', (1=⍵)↓'s of beer'}\n bobw ← {(bob ⍵) , ' on the wall'}\n beer ← { (bobw ⍵) , ', ', (bob ⍵) , '; take one down and pass it around, ', bobw ⍵-1}\n"}}},{"rowIdx":78159,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game"},"task_name":{"kind":"string","value":"24 game"},"task_description":{"kind":"string","value":"The 24 Game tests one's mental arithmetic.\n\n\n\nTask\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to 24.\n\n Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n Division should use floating point or rational arithmetic, etc, to preserve remainders.\n Brackets are allowed, if using an infix expression evaluator.\n Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n The order of the digits when given does not have to be preserved.\n\n\nNotes\n The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\nRelated tasks\n 24 game/Solve\n\n\nReference\n The 24 Game on h2g2.\n\n"},"language_url":{"kind":"string","value":"#Elixir"},"language_name":{"kind":"string","value":"Elixir"},"code":{"kind":"string","value":"defmodule Game24 do\n def main do\n IO.puts \"24 Game\"\n play\n end\n \n defp play do\n IO.puts \"Generating 4 digits...\"\n digts = for _ <- 1..4, do: Enum.random(1..9)\n IO.puts \"Your digits\\t#{inspect digts, char_lists: :as_lists}\"\n read_eval(digts)\n play\n end\n \n defp read_eval(digits) do\n exp = IO.gets(\"Your expression: \") |> String.strip\n if exp in [\"\",\"q\"], do: exit(:normal) # give up\n case {correct_nums(exp, digits), eval(exp)} do\n {:ok, x} when x==24 -> IO.puts \"You Win!\"\n {:ok, x} -> IO.puts \"You Lose with #{inspect x}!\"\n {err, _} -> IO.puts \"The following numbers are wrong: #{inspect err, char_lists: :as_lists}\"\n end\n end\n \n defp correct_nums(exp, digits) do\n nums = String.replace(exp, ~r/\\D/, \" \") |> String.split |> Enum.map(&String.to_integer &1)\n if length(nums)==4 and (nums--digits)==[], do: :ok, else: nums\n end\n \n defp eval(exp) do\n try do\n Code.eval_string(exp) |> elem(0)\n rescue\n e -> Exception.message(e)\n end\n end\nend\n \nGame24.main"}}},{"rowIdx":78160,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/A%2BB"},"task_name":{"kind":"string","value":"A+B"},"task_description":{"kind":"string","value":"A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, A and B.\n\nTheir sum needs to be calculated.\n\n\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n \n\n\n\n(\n−\n1000\n≤\nA\n,\nB\n≤\n+\n1000\n)\n\n\n{\\displaystyle (-1000\\leq A,B\\leq +1000)}\n\n\n\n\nOutput data\n\nThe required output is one integer: the sum of A and B.\n\n\n\nExample\n\n\n\n input \n\n output \n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n"},"language_url":{"kind":"string","value":"#COBOL"},"language_name":{"kind":"string","value":"COBOL"},"code":{"kind":"string","value":" IDENTIFICATION DIVISION.\n PROGRAM-ID. A-Plus-B.\n \n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 A PIC S9(5).\n 01 B PIC S9(5).\n \n 01 A-B-Sum PIC S9(5).\n \n PROCEDURE DIVISION.\n ACCEPT A\n ACCEPT B\n \n ADD A TO B GIVING A-B-Sum\n \n DISPLAY A-B-Sum\n \n GOBACK\n ."}}},{"rowIdx":78161,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Ackermann_function"},"task_name":{"kind":"string","value":"Ackermann function"},"task_description":{"kind":"string","value":"The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.\n\n\n\nThe Ackermann function is usually defined as follows:\n\n\n\n\n\n\n\nA\n(\nm\n,\nn\n)\n=\n\n\n{\n\n\n\nn\n+\n1\n\n\n\nif \n\nm\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\n1\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n=\n0\n\n\n\n\nA\n(\nm\n−\n1\n,\nA\n(\nm\n,\nn\n−\n1\n)\n)\n\n\n\nif \n\nm\n>\n0\n\n and \n\nn\n>\n0.\n\n\n\n\n\n\n\n\n{\\displaystyle A(m,n)={\\begin{cases}n+1&{\\mbox{if }}m=0\\\\A(m-1,1)&{\\mbox{if }}m>0{\\mbox{ and }}n=0\\\\A(m-1,A(m,n-1))&{\\mbox{if }}m>0{\\mbox{ and }}n>0.\\end{cases}}}\n\n\n\n\n\n\nIts arguments are never negative and it always terminates.\n\n\n\nTask\n\nWrite a function which returns the value of \n\n\n\nA\n(\nm\n,\nn\n)\n\n\n{\\displaystyle A(m,n)}\n\n. Arbitrary precision is preferred (since the function grows so quickly), but not required.\n\n\n\nSee also\n\n Conway chained arrow notation for the Ackermann function.\n\n"},"language_url":{"kind":"string","value":"#Ursala"},"language_name":{"kind":"string","value":"Ursala"},"code":{"kind":"string","value":"#import std\n#import nat\n \nackermann = \n \n~&al^?\\successor@ar ~&ar?(\n ^R/~&f ^/predecessor@al ^|R/~& ^|/~& predecessor,\n ^|R/~& ~&\\1+ predecessor@l)"}}},{"rowIdx":78162,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/ABC_problem"},"task_name":{"kind":"string","value":"ABC problem"},"task_description":{"kind":"string","value":"ABC problem\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nYou are given a collection of ABC blocks (maybe like the ones you had when you were a kid).\n\nThere are twenty blocks with two letters on each block.\n\nA complete alphabet is guaranteed amongst all sides of the blocks.\n\nThe sample collection of blocks:\n\n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n\nTask\n\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.\n\n\n\nThe rules are simple:\n\n Once a letter on a block is used that block cannot be used again\n The function should be case-insensitive\n Show the output on this page for the following 7 words in the following example\n\n\nExample\n\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n"},"language_url":{"kind":"string","value":"#Fortran"},"language_name":{"kind":"string","value":"Fortran"},"code":{"kind":"string","value":"!-*- mode: compilation; default-directory: \"/tmp/\" -*-\n!Compilation started at Thu Jun 5 01:52:03\n!\n!make f && for a in '' a bark book treat common squad confuse ; do echo $a | ./f ; done\n!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f\n! T \n! T A NA\n! T BARK BO NA RE XK\n! F BOOK OB BO -- --\n! T TREAT GT RE ER NA TG\n! F COMMON PC OB ZM -- -- --\n! T SQUAD FS DQ HU NA QD\n! T CONFUSE CP BO NA FS HU FS RE\n!\n!Compilation finished at Thu Jun 5 01:52:03\n \nprogram abc\n implicit none\n integer, parameter :: nblocks = 20\n character(len=nblocks) :: goal\n integer, dimension(nblocks) :: solution\n character(len=2), dimension(0:nblocks) :: blocks_copy, blocks = &\n &(/'--','BO','XK','DQ','CP','NA','GT','RE','TG','QD','FS','JW','HU','VI','AN','OB','ER','FS','LY','PC','ZM'/)\n logical :: valid\n integer :: i, iostat\n read(5,*,iostat=iostat) goal\n if (iostat .ne. 0) goal = ''\n call ucase(goal)\n solution = 0\n blocks_copy = blocks\n valid = assign_block(goal(1:len_trim(goal)), blocks, solution, 1)\n write(6,*) valid, ' '//goal, (' '//blocks_copy(solution(i)), i=1,len_trim(goal))\n \ncontains\n \n recursive function assign_block(goal, blocks, solution, n) result(valid)\n implicit none\n logical :: valid\n character(len=*), intent(in) :: goal\n character(len=2), dimension(0:), intent(inout) :: blocks\n integer, dimension(:), intent(out) :: solution\n integer, intent(in) :: n\n integer :: i\n character(len=2) :: backing_store\n valid = .true.\n if (len(goal)+1 .eq. n) return\n do i=1, size(blocks)\n if (index(blocks(i),goal(n:n)) .ne. 0) then\n backing_store = blocks(i)\n blocks(i) = ''\n solution(n) = i\n if (assign_block(goal, blocks, solution, n+1)) return\n blocks(i) = backing_store\n end if\n end do\n valid = .false.\n return\n end function assign_block\n \n subroutine ucase(a)\n implicit none\n character(len=*), intent(inout) :: a\n integer :: i, j\n do i = 1, len_trim(a)\n j = index('abcdefghijklmnopqrstuvwxyz',a(i:i))\n if (j .ne. 0) a(i:i) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'(j:j)\n end do\n end subroutine ucase\n \nend program abc"}}},{"rowIdx":78163,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/100_prisoners"},"task_name":{"kind":"string","value":"100 prisoners"},"task_description":{"kind":"string","value":"\n\nThe Problem\n\n 100 prisoners are individually numbered 1 to 100\n A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n Prisoners start outside the room\n They can decide some strategy before any enter the room.\n Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n A prisoner can open no more than 50 drawers.\n A prisoner tries to find his own number.\n A prisoner finding his own number is then held apart from the others.\n If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. \n\n\nThe task\n\n Simulate several thousand instances of the game where the prisoners randomly open drawers\n Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n First opening the drawer whose outside number is his prisoner number.\n If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n\n\nReferences\n\n The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n wp:100 prisoners problem\n 100 Prisoners Escape Puzzle DataGenetics.\n Random permutation statistics#One hundred prisoners on Wikipedia.\n\n"},"language_url":{"kind":"string","value":"#Delphi"},"language_name":{"kind":"string","value":"Delphi"},"code":{"kind":"string","value":"for i range 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 - 1]\n .\n.\nsubr play_random\n call shuffle_drawer\n found = 1\n prisoner = 0\n while prisoner < 100 and found = 1\n found = 0\n i = 0\n while i < 50 and found = 0\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 .\n i += 1\n .\n prisoner += 1\n .\n.\nsubr play_optimal\n call shuffle_drawer\n found = 1\n prisoner = 0\n while prisoner < 100 and found = 1\n reveal = prisoner\n found = 0\n i = 0\n while i < 50 and found = 0\n card = drawer[reveal]\n if card = prisoner\n found = 1\n .\n reveal = card\n i += 1\n .\n prisoner += 1\n .\n.\nn = 10000\npardoned = 0\nfor round range n\n call play_random\n pardoned += found\n.\nprint \"random: \" & 100.0 * pardoned / n & \"%\"\n# \npardoned = 0\nfor round range n\n call play_optimal\n pardoned += found\n.\nprint \"optimal: \" & 100.0 * pardoned / n & \"%\""}}},{"rowIdx":78164,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/Abundant_odd_numbers"},"task_name":{"kind":"string","value":"Abundant odd numbers"},"task_description":{"kind":"string","value":"An Abundant number is a number n for which the sum of divisors σ(n) > 2n,\n\nor, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.\n\n\n\nE.G.\n\n12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);\n\n or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).\n\n\n\nAbundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.\n\nTo make things more interesting, this task is specifically about finding odd abundant numbers.\n\n\n\nTask\nFind and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\nFind and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\nFind and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\nReferences\n\n OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n"},"language_url":{"kind":"string","value":"#Wren"},"language_name":{"kind":"string","value":"Wren"},"code":{"kind":"string","value":"import \"/fmt\" for Fmt\nimport \"/math\" for Int, Nums\n \nvar sumStr = Fn.new { |divs| divs.reduce(\"\") { |acc, div| acc + \"%(div) + \" }[0...-3] }\n \nvar abundantOdd = Fn.new { |searchFrom, countFrom, countTo, printOne|\n var count = countFrom\n var n = searchFrom\n while (count < countTo) {\n var divs = Int.properDivisors(n)\n var tot = Nums.sum(divs)\n if (tot > n) {\n count = count + 1\n if (!printOne || count >= countTo) {\n var s = sumStr.call(divs)\n if (!printOne) {\n System.print(\"%(Fmt.d(2, count)). %(Fmt.d(5, n)) < %(s) = %(tot)\")\n } else {\n System.print(\"%(n) < %(s) = %(tot)\")\n }\n }\n }\n n = n + 2\n }\n return n\n}\n \nvar MAX = 25\nSystem.print(\"The first %(MAX) abundant odd numbers are:\")\nvar n = abundantOdd.call(1, 0, 25, false)\n \nSystem.print(\"\\nThe one thousandth abundant odd number is:\")\nabundantOdd.call(n, 25, 1000, true)\n \nSystem.print(\"\\nThe first abundant odd number above one billion is:\")\nabundantOdd.call(1e9+1, 0, 1, true)"}}},{"rowIdx":78165,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/21_game"},"task_name":{"kind":"string","value":"21 game"},"task_description":{"kind":"string","value":"21 game\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n21 is a two player game, the game is played by choosing\na number (1, 2, or 3) to be added to the running total.\n\nThe game is won by the player whose chosen number causes the running total\nto reach exactly 21.\n\nThe running total starts at zero.\nOne player will be the computer.\n\nPlayers alternate supplying a number to be added to the running total.\n\n\n\nTask\n\nWrite a computer program that will:\n\n do the prompting (or provide a button menu), \n check for errors and display appropriate error messages, \n do the additions (add a chosen number to the running total), \n display the running total, \n provide a mechanism for the player to quit/exit/halt/stop/close the program,\n issue a notification when there is a winner, and\n determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n"},"language_url":{"kind":"string","value":"#R"},"language_name":{"kind":"string","value":"R"},"code":{"kind":"string","value":"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}"}}},{"rowIdx":78166,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game/Solve"},"task_name":{"kind":"string","value":"24 game/Solve"},"task_description":{"kind":"string","value":"task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\n\n\nRelated task\n\n Arithmetic Evaluator\n\n"},"language_url":{"kind":"string","value":"#Gosu"},"language_name":{"kind":"string","value":"Gosu"},"code":{"kind":"string","value":" \nuses java.lang.Integer\nuses java.lang.Double\nuses java.lang.System\nuses java.util.ArrayList\nuses java.util.LinkedList\nuses java.util.List\nuses java.util.Scanner\nuses java.util.Stack\n \nfunction permutations( lst : List ) : List> {\n if( lst.size() == 0 ) return {}\n if( lst.size() == 1 ) return { lst }\n \n var pivot = lst.get(lst.size()-1)\n \n var sublist = new ArrayList( lst )\n sublist.remove( sublist.size() - 1 )\n \n var subPerms = permutations( sublist )\n \n var ret = new ArrayList>()\n for( x in subPerms ) {\n for( e in x index i ) {\n var next = new LinkedList( x )\n next.add( i, pivot )\n ret.add( next )\n }\n x.add( pivot )\n ret.add( x )\n }\n return ret\n}\n \nfunction readVals() : List {\n var line = new java.io.BufferedReader( new java.io.InputStreamReader( System.in ) ).readLine()\n var scan = new Scanner( line )\n \n var ret = new ArrayList()\n for( i in 0..3 ) {\n var next = scan.nextInt() \n if( 0 >= next || next >= 10 ) {\n print( \"Invalid entry: ${next}\" )\n return null\n }\n ret.add( next )\n }\n return ret\n}\n \nfunction getOp( i : int ) : char[] {\n var ret = new char[3]\n var ops = { '+', '-', '*', '/' }\n ret[0] = ops[i / 16]\n ret[1] = ops[(i / 4) % 4 ]\n ret[2] = ops[i % 4 ]\n return ret\n}\n \nfunction isSoln( nums : List, ops : char[] ) : boolean {\n var stk = new Stack()\n for( n in nums ) {\n stk.push( n )\n }\n \n for( c in ops ) {\n var r = stk.pop().doubleValue()\n var l = stk.pop().doubleValue()\n if( c == '+' ) {\n stk.push( l + r )\n } else if( c == '-' ) {\n stk.push( l - r )\n } else if( c == '*' ) {\n stk.push( l * r )\n } else if( c == '/' ) {\n // Avoid division by 0\n if( r == 0.0 ) {\n return false\n }\n stk.push( l / r )\n }\n }\n \n return java.lang.Math.abs( stk.pop().doubleValue() - 24.0 ) < 0.001\n}\n \nfunction printSoln( nums : List, ops : char[] ) {\n // RPN: a b c d + - *\n // Infix (a * (b - (c + d)))\n print( \"Found soln: (${nums.get(0)} ${ops[0]} (${nums.get(1)} ${ops[1]} (${nums.get(2)} ${ops[2]} ${nums.get(3)})))\" )\n}\n \nSystem.out.print( \"#> \" )\nvar vals = readVals()\n \nvar opPerms = 0..63\nvar solnFound = false\n \nfor( i in permutations( vals ) ) {\n for( j in opPerms ) {\n var opList = getOp( j )\n if( isSoln( i, opList ) ) {\n printSoln( i, opList )\n solnFound = true\n }\n }\n}\n \nif( ! solnFound ) {\n print( \"No solution!\" )\n}\n "}}},{"rowIdx":78167,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_game"},"task_name":{"kind":"string","value":"15 puzzle game"},"task_description":{"kind":"string","value":" \n\n\nTask\n\nImplement the Fifteen Puzzle Game.\n\n\n\nThe 15-puzzle is also known as:\n\n Fifteen Puzzle\n Gem Puzzle\n Boss Puzzle\n Game of Fifteen\n Mystic Square\n 14-15 Puzzle\n and some others.\n\n\nRelated Tasks\n\n 15 Puzzle Solver\n 16 Puzzle Game\n\n"},"language_url":{"kind":"string","value":"#Ada"},"language_name":{"kind":"string","value":"Ada"},"code":{"kind":"string","value":"generic\n Rows, Cols: Positive;\n with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols);\n -- Name(0) shall return the name for the empty tile\npackage Generic_Puzzle is\n \n subtype Row_Type is Positive range 1 .. Rows;\n subtype Col_Type is Positive range 1 .. Cols;\n type Moves is (Up, Down, Left, Right);\n type Move_Arr is array(Moves) of Boolean;\n \n function Get_Point(Row: Row_Type; Col: Col_Type) return String;\n function Possible return Move_Arr;\n procedure Move(The_Move: Moves);\n \nend Generic_Puzzle;"}}},{"rowIdx":78168,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/2048"},"task_name":{"kind":"string","value":"2048"},"task_description":{"kind":"string","value":"Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\n\n\nRules of the game\n\n The rules are that on each turn the player must choose a direction (up, down, left or right).\n All tiles move as far as possible in that direction, some move more than others. \n Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers. \n A move is valid when at least one tile can be moved, if only by combination. \n A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one). \n Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.\n To win, the player must create a tile with the number 2048. \n The player loses if no valid moves are possible.\n\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\n\n\nRequirements\n\n \"Non-greedy\" movement. \n The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n That is to say, that moving the tile row of:\n [2][2][2][2] \n\n to the right should result in: \n ......[4][4] \n\n and not:\n .........[8] \n\n \"Move direction priority\". \n If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n For example, moving the tile row of:\n ...[2][2][2] \n\n to the right should result in:\n ......[2][4] \n\n and not:\n ......[4][2] \n\n\n\n Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.\n Check for a win condition.\n Check for a lose condition.\n\n"},"language_url":{"kind":"string","value":"#BBC_BASIC"},"language_name":{"kind":"string","value":"BBC BASIC"},"code":{"kind":"string","value":" SIZE = 4 : MAX = SIZE-1\n Won% = FALSE : Lost% = FALSE\n @% = 5\n DIM Board(MAX,MAX),Stuck% 3\n \n PROCBreed\n PROCPrint\n REPEAT\n Direction = GET-135\n IF Direction > 0 AND Direction < 5 THEN\n Moved% = FALSE\n PROCShift\n PROCMerge\n PROCShift\n IF Moved% THEN PROCBreed : !Stuck%=0 ELSE ?(Stuck%+Direction-1)=-1 : Lost% = !Stuck%=-1\n PROCPrint\n ENDIF\n UNTIL Won% OR Lost%\n IF Won% THEN PRINT \"You WON! :-)\" ELSE PRINT \"You lost :-(\"\n END\n \n REM -----------------------------------------------------------------------------------------------------------------------\n DEF PROCPrint\n FOR i = 0 TO SIZE*SIZE-1\n IF Board(i DIV SIZE,i MOD SIZE) THEN PRINT Board(i DIV SIZE,i MOD SIZE); ELSE PRINT \" _\";\n IF i MOD SIZE = MAX THEN PRINT\n NEXT\n PRINT STRING$(SIZE,\"-----\")\n ENDPROC\n \n REM ----------------------------------------------------------------------------------------------------------------------\n DEF PROCShift\n IF Direction = 2 OR Direction = 3 THEN loopend = MAX : step = -1 ELSE loopend = 0 : step = 1\n FOR row = loopend TO MAX-loopend STEP step\n zeros = 0\n FOR col = loopend TO MAX-loopend STEP step\n IF Direction < 3 THEN\n IF Board(row,col) = 0 THEN zeros += step ELSE IF zeros THEN SWAP Board(row,col),Board(row,col-zeros) : Moved% = TRUE\n ELSE\n IF Board(col,row) = 0 THEN zeros += step ELSE IF zeros THEN SWAP Board(col,row),Board(col-zeros,row) : Moved% = TRUE\n ENDIF\n NEXT\n NEXT\n ENDPROC\n \n REM -----------------------------------------------------------------------------------------------------------------------\n DEF PROCMerge\n IF Direction = 1 THEN loopend = 0 : rowoff = 0 : coloff = 1 : step = 1\n IF Direction = 2 THEN loopend = MAX : rowoff = 0 : coloff = -1 : step = -1\n IF Direction = 3 THEN loopend = MAX : rowoff = -1 : coloff = 0 : step = -1\n IF Direction = 4 THEN loopend = 0 : rowoff = 1 : coloff = 0 : step = 1\n FOR row = loopend TO MAX-loopend-rowoff STEP step\n FOR col = loopend TO MAX-loopend-coloff STEP step\n IF Board(row,col) THEN IF Board(row,col) = Board(row+rowoff,col+coloff) THEN\n Board(row,col) *= 2 : Board(row+rowoff,col+coloff) = 0\n Moved% = TRUE\n IF NOT Won% THEN Won% = Board(row,col)=2048\n ENDIF\n NEXT\n NEXT\n ENDPROC\n \n REM -----------------------------------------------------------------------------------------------------------------------\n DEF PROCBreed\n cell = RND(SIZE*SIZE)-1\n FOR i = 0 TO SIZE*SIZE-1\n z = (cell+i) MOD (SIZE*SIZE)\n IF Board(z DIV SIZE,z MOD SIZE) = 0 THEN Board(z DIV SIZE,z MOD SIZE) = 2-(RND(10)=1)*2 : EXIT FOR\n NEXT\n ENDPROC"}}},{"rowIdx":78169,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle"},"task_name":{"kind":"string","value":"4-rings or 4-squares puzzle"},"task_description":{"kind":"string","value":"4-rings or 4-squares puzzle\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nReplace a, b, c, d, e, f, and\n g with the decimal\ndigits LOW ───► HIGH\n\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\nShow all output here.\n\n\n\n Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n Show only the number of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n\nRelated task\n\n Solve the no connection puzzle\n\n"},"language_url":{"kind":"string","value":"#Raku"},"language_name":{"kind":"string","value":"Raku"},"code":{"kind":"string","value":"sub four-squares ( @list, :$unique=1, :$show=1 ) {\n \n my @solutions;\n \n for $unique.&combos -> @c {\n @solutions.push: @c if [==]\n @c[0] + @c[1],\n @c[1] + @c[2] + @c[3],\n @c[3] + @c[4] + @c[5],\n @c[5] + @c[6];\n }\n \n say +@solutions, ($unique ?? ' ' !! ' non-'), \"unique solutions found using {join(', ', @list)}.\\n\";\n \n my $f = \"%{@list.max.chars}s\";\n \n say join \"\\n\", (('a'..'g').fmt: $f), @solutions».fmt($f), \"\\n\" if $show;\n \n multi combos ( $ where so * ) { @list.combinations(7).map: |*.permutations }\n \n multi combos ( $ where not * ) { [X] @list xx 7 }\n}\n \n# TASK\nfour-squares( [1..7] );\nfour-squares( [3..9] );\nfour-squares( [8, 9, 11, 12, 17, 18, 20, 21] );\nfour-squares( [0..9], :unique(0), :show(0) );"}}},{"rowIdx":78170,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/15_puzzle_solver"},"task_name":{"kind":"string","value":"15 puzzle solver"},"task_description":{"kind":"string","value":"Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.\n\nFor this task you will be using the following puzzle:\n\n\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n\n\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on.\n\nThere are two solutions, of fifty-two moves:\n\nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd\n\nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\n\nExtra credit.\nSolve the following problem:\n\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n\n\nRelated Task\n\n 15 puzzle game\n A* search algorithm\n\n"},"language_url":{"kind":"string","value":"#Go"},"language_name":{"kind":"string","value":"Go"},"code":{"kind":"string","value":"package main\n \nimport \"fmt\"\n \nvar (\n Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3}\n Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2}\n)\n \nvar (\n n, _n int\n N0, N3, N4 [85]int\n N2 [85]uint64\n)\n \nconst (\n i = 1\n g = 8\n e = 2\n l = 4\n)\n \nfunc fY() bool {\n if N2[n] == 0x123456789abcdef0 {\n return true\n }\n if N4[n] <= _n {\n return fN()\n }\n return false\n}\n \nfunc fZ(w int) bool {\n if w&i > 0 {\n fI()\n if fY() {\n return true\n }\n n--\n }\n if w&g > 0 {\n fG()\n if fY() {\n return true\n }\n n--\n }\n if w&e > 0 {\n fE()\n if fY() {\n return true\n }\n n--\n }\n if w&l > 0 {\n fL()\n if fY() {\n return true\n }\n n--\n }\n return false\n}\n \nfunc fN() bool {\n switch N0[n] {\n case 0:\n switch N3[n] {\n case 'l':\n return fZ(i)\n case 'u':\n return fZ(e)\n default:\n return fZ(i + e)\n }\n case 3:\n switch N3[n] {\n case 'r':\n return fZ(i)\n case 'u':\n return fZ(l)\n default:\n return fZ(i + l)\n }\n case 1, 2:\n switch N3[n] {\n case 'l':\n return fZ(i + l)\n case 'r':\n return fZ(i + e)\n case 'u':\n return fZ(e + l)\n default:\n return fZ(l + e + i)\n }\n case 12:\n switch N3[n] {\n case 'l':\n return fZ(g)\n case 'd':\n return fZ(e)\n default:\n return fZ(e + g)\n }\n case 15:\n switch N3[n] {\n case 'r':\n return fZ(g)\n case 'd':\n return fZ(l)\n default:\n return fZ(g + l)\n }\n case 13, 14:\n switch N3[n] {\n case 'l':\n return fZ(g + l)\n case 'r':\n return fZ(e + g)\n case 'd':\n return fZ(e + l)\n default:\n return fZ(g + e + l)\n }\n case 4, 8:\n switch N3[n] {\n case 'l':\n return fZ(i + g)\n case 'u':\n return fZ(g + e)\n case 'd':\n return fZ(i + e)\n default:\n return fZ(i + g + e)\n }\n case 7, 11:\n switch N3[n] {\n case 'd':\n return fZ(i + l)\n case 'u':\n return fZ(g + l)\n case 'r':\n return fZ(i + g)\n default:\n return fZ(i + g + l)\n }\n default:\n switch N3[n] {\n case 'd':\n return fZ(i + e + l)\n case 'l':\n return fZ(i + g + l)\n case 'r':\n return fZ(i + g + e)\n case 'u':\n return fZ(g + e + l)\n default:\n return fZ(i + g + e + l)\n }\n }\n}\n \nfunc fI() {\n g := (11 - N0[n]) * 4\n a := N2[n] & uint64(15<>uint(g)] <= N0[n]/4\n if !cond {\n N4[n+1]++\n }\n n++\n}\n \nfunc fG() {\n g := (19 - N0[n]) * 4\n a := N2[n] & uint64(15<> 16)\n N3[n+1] = 'u'\n N4[n+1] = N4[n]\n cond := Nr[a>>uint(g)] >= N0[n]/4\n if !cond {\n N4[n+1]++\n }\n n++\n}\n \nfunc fE() {\n g := (14 - N0[n]) * 4\n a := N2[n] & uint64(15<>uint(g)] <= N0[n]%4\n if !cond {\n N4[n+1]++\n }\n n++\n}\n \nfunc fL() {\n g := (16 - N0[n]) * 4\n a := N2[n] & uint64(15<> 4)\n N3[n+1] = 'l'\n N4[n+1] = N4[n]\n cond := Nc[a>>uint(g)] >= N0[n]%4\n if !cond {\n N4[n+1]++\n }\n n++\n}\n \nfunc fifteenSolver(n int, g uint64) {\n N0[0] = n\n N2[0] = g\n N4[0] = 0\n}\n \nfunc solve() {\n if fN() {\n fmt.Print(\"Solution found in \", n, \" moves: \")\n for g := 1; g <= n; g++ {\n fmt.Printf(\"%c\", N3[g])\n }\n fmt.Println()\n } else {\n n = 0\n _n++\n solve()\n }\n}\n \nfunc main() {\n fifteenSolver(8, 0xfe169b4c0a73d852)\n solve()\n}"}}},{"rowIdx":78171,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/99_bottles_of_beer"},"task_name":{"kind":"string","value":"99 bottles of beer"},"task_description":{"kind":"string","value":"Task\n\nDisplay the complete lyrics for the song: 99 Bottles of Beer on the Wall.\n\n\n\nThe beer song\n\nThe lyrics follow this form:\n\n\n 99 bottles of beer on the wall\n\n 99 bottles of beer\n\n Take one down, pass it around\n\n 98 bottles of beer on the wall\n\n\n 98 bottles of beer on the wall\n\n 98 bottles of beer\n\n Take one down, pass it around\n\n 97 bottles of beer on the wall\n\n... and so on, until reaching 0 (zero).\n\nGrammatical support for 1 bottle of beer is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string (assignment)\nCounting\n Word frequency\n Letter frequency\n Jewels and stones\n I before E except after C\n Bioinformatics/base count\n Count occurrences of a substring\n Count how many vowels and consonants occur in a string\nRemove/replace\n XXXX redacted\n Conjugate a Latin verb\n Remove vowels from a string\n String interpolation (included)\n Strip block comments\n Strip comments from a string\n Strip a set of characters from a string\n Strip whitespace from a string -- top and tail\n Strip control codes and extended characters from a string\nAnagrams/Derangements/shuffling\n Word wheel\n ABC problem\n Sattolo cycle\n Knuth shuffle\n Ordered words\n Superpermutation minimisation\n Textonyms (using a phone text pad)\n Anagrams\n Anagrams/Deranged anagrams\n Permutations/Derangements\nFind/Search/Determine\n ABC words\n Odd words\n Word ladder\n Semordnilap\n Word search\n Wordiff (game)\n String matching\n Tea cup rim text\n Alternade words\n Changeable words\n State name puzzle\n String comparison\n Unique characters\n Unique characters in each string\n Extract file extension\n Levenshtein distance\n Palindrome detection\n Common list elements\n Longest common suffix\n Longest common prefix\n Compare a list of strings \n Longest common substring\n Find common directory path\n Words from neighbour ones\n Change e letters to i in words\n Non-continuous subsequences\n Longest common subsequence\n Longest palindromic substrings\n Longest increasing subsequence\n Words containing \"the\" substring\n Sum of the digits of n is substring of n\n Determine if a string is numeric\n Determine if a string is collapsible\n Determine if a string is squeezable\n Determine if a string has all unique characters\n Determine if a string has all the same characters\n Longest substrings without repeating characters\n Find words which contains all the vowels\n Find words which contains most consonants\n Find words which contains more than 3 vowels\n Find words which first and last three letters are equals\n Find words which odd letters are consonants and even letters are vowels or vice_versa\nFormatting\n Substring\n Rep-string\n Word wrap\n String case\n Align columns\n Literals/String\n Repeat a string\n Brace expansion\n Brace expansion using ranges\n Reverse a string\n Phrase reversals\n Comma quibbling\n Special characters\n String concatenation\n Substring/Top and tail\n Commatizing numbers\n Reverse words in a string\n Suffixation of decimal numbers\n Long literals, with continuations \n Numerical and alphabetical suffixes\n Abbreviations, easy\n Abbreviations, simple\n Abbreviations, automatic\nSong lyrics/poems/Mad Libs/phrases\n Mad Libs\n Magic 8-ball\n 99 Bottles of Beer\n The Name Game (a song)\n The Old lady swallowed a fly\n The Twelve Days of Christmas\nTokenize\n Text between\n Tokenize a string\n Word break problem\n Tokenize a string with escaping\n Split a character string based on change of character\nSequences\n Show ASCII table\n De Bruijn sequences\n Self-referential sequences\n Generate lower case ASCII alphabet\n\n\n\n\nSee also\n \n http://99-bottles-of-beer.net/\n Category:99_Bottles_of_Beer\n Category:Programming language families\n Wikipedia 99 bottles of beer\n\n"},"language_url":{"kind":"string","value":"#App_Inventor"},"language_name":{"kind":"string","value":"App Inventor"},"code":{"kind":"string","value":"repeat with beerCount from 99 to 1 by -1\n set bottles to \"bottles\"\n if beerCount < 99 then\n if beerCount = 1 then\n set bottles to \"bottle\"\n end\n log \"\" & beerCount & \" \" & bottles & \" of beer on the wall\"\n log \"\"\n end\n log \"\" & beerCount & \" \" & bottles & \" of beer on the wall\"\n log \"\" & beerCount & \" \" & bottles & \" of beer\"\n log \"Take one down, pass it around\"\nend\nlog \"No more bottles of beer on the wall!\""}}},{"rowIdx":78172,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/24_game"},"task_name":{"kind":"string","value":"24 game"},"task_description":{"kind":"string","value":"The 24 Game tests one's mental arithmetic.\n\n\n\nTask\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to 24.\n\n Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n Division should use floating point or rational arithmetic, etc, to preserve remainders.\n Brackets are allowed, if using an infix expression evaluator.\n Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n The order of the digits when given does not have to be preserved.\n\n\nNotes\n The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\nRelated tasks\n 24 game/Solve\n\n\nReference\n The 24 Game on h2g2.\n\n"},"language_url":{"kind":"string","value":"#Erlang"},"language_name":{"kind":"string","value":"Erlang"},"code":{"kind":"string","value":"-module(g24).\n-export([main/0]).\n \nmain() ->\n random:seed(now()),\n io:format(\"24 Game~n\"),\n play().\n \nplay() ->\n io:format(\"Generating 4 digits...~n\"),\n Digts = [random:uniform(X) || X <- [9,9,9,9]],\n io:format(\"Your digits\\t~w~n\", [Digts]),\n read_eval(Digts),\n play().\n \nread_eval(Digits) ->\n Exp = string:strip(io:get_line(standard_io, \"Your expression: \"), both, $\\n),\n case {correct_nums(Exp, Digits), eval(Exp)} of\n {ok, X} when X == 24 -> io:format(\"You Win!~n\");\n {ok, X} -> io:format(\"You Lose with ~p!~n\",[X]);\n {List, _} -> io:format(\"The following numbers are wrong: ~p~n\", [List])\n end.\n \ncorrect_nums(Exp, Digits) ->\n case re:run(Exp, \"([0-9]+)\", [global, {capture, all_but_first, list}]) of\n nomatch ->\n \"No number entered\";\n {match, IntLs} ->\n case [X || [X] <- IntLs, not lists:member(list_to_integer(X), Digits)] of\n [] -> ok;\n L -> L\n end\n end.\n \neval(Exp) ->\n {X, _} = eval(re:replace(Exp, \"\\\\s\", \"\", [{return, list},global]),\n 0),\n X.\n \neval([], Val) ->\n {Val,[]};\neval([$(|Rest], Val) ->\n {NewVal, Exp} = eval(Rest, Val),\n eval(Exp, NewVal);\neval([$)|Rest], Val) ->\n {Val, Rest};\neval([$[|Rest], Val) ->\n {NewVal, Exp} = eval(Rest, Val),\n eval(Exp, NewVal);\neval([$]|Rest], Val) ->\n {Val, Rest};\neval([$+|Rest], Val) ->\n {NewOperand, Exp} = eval(Rest, 0),\n eval(Exp, Val + NewOperand);\neval([$-|Rest], Val) ->\n {NewOperand, Exp} = eval(Rest, 0),\n eval(Exp, Val - NewOperand);\neval([$*|Rest], Val) ->\n {NewOperand, Exp} = eval(Rest, 0),\n eval(Exp, Val * NewOperand);\neval([$/|Rest], Val) ->\n {NewOperand, Exp} = eval(Rest, 0),\n eval(Exp, Val / NewOperand);\neval([X|Rest], 0) when X >= $1, X =< $9 ->\n eval(Rest, X-$0).\n "}}},{"rowIdx":78173,"cells":{"task_url":{"kind":"string","value":"http://rosettacode.org/wiki/A%2BB"},"task_name":{"kind":"string","value":"A+B"},"task_description":{"kind":"string","value":"A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, A and B.\n\nTheir sum needs to be calculated.\n\n\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n \n\n\n\n(\n−\n1000\n≤\nA\n,\nB\n≤\n+\n1000\n)\n\n\n{\\displaystyle (-1000\\leq A,B\\leq +1000)}\n\n\n\n\nOutput data\n\nThe required output is one integer: the sum of A and B.\n\n\n\nExample\n\n\n\n input \n\n output \n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n"},"language_url":{"kind":"string","value":"#CoffeeScript"},"language_name":{"kind":"string","value":"CoffeeScript"},"code":{"kind":"string","value":"\n\n\n