forked from meta-llama/llama
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrosetta_sql_dataset.json
1 lines (1 loc) · 397 KB
/
rosetta_sql_dataset.json
1
[{"instruction": "Task\n\nDetermine the amount of elements in an array.\n\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\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 \u00a0(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 \u00a0(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", "output": "SELECT COUNT() FROM (VALUES ('apple'),('orange'));", "input": ""}, {"instruction": "\nBasic Data Operation\n\nThis is a basic data operation. It represents a fundamental action on a basic data type.\nYou may see other such operations in the Basic Data Operations category, or:\n\n\nInteger Operations\nArithmetic |\nComparison\nBoolean Operations\nBitwise |\nLogical\nString Operations\nConcatenation |\nInterpolation |\nComparison |\nMatching\nMemory Operations\nPointers & references |\nAddresses\n\n\nTask\n\nGet two integers from the user, \u00a0 and then (for those two integers), display their:\n\n \u00a0 sum \n \u00a0 difference \n \u00a0 product \n \u00a0 integer quotient\n \u00a0 remainder \n \u00a0 exponentiation \u00a0 (if the operator exists) \n\n\nDon't include error handling.\n\nFor quotient, indicate how it rounds \u00a0 (e.g. towards zero, towards negative infinity, etc.).\n\nFor remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.\n\n\n\n", "output": "\u00a0\n-- test.sql\n-- Tested in SQL*plus\n\u00a0\nDROP TABLE test;\n\u00a0\nCREATE TABLE test (a INTEGER, b INTEGER);\n\u00a0\nINSERT INTO test VALUES ('&&A','&&B');\n\u00a0\ncommit;\n\u00a0\nSELECT a-b difference FROM test;\n\u00a0\nSELECT a*b product FROM test;\n\u00a0\nSELECT trunc(a/b) integer_quotient FROM test; \n\u00a0\nSELECT MOD(a,b) remainder FROM test;\n\u00a0\nSELECT POWER(a,b) exponentiation FROM test;\n\u00a0", "input": ""}, {"instruction": "\n\n This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)\n\n\n\nTask\n\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \n\n\n\n\na\ng\nm\n\n(\na\n,\ng\n)\n\n\n{\\displaystyle \\mathrm {agm} (a,g)}\n\n, and is equal to the limit of the sequence:\n\n \n\n\n\n\na\n\n0\n\n\n=\na\n;\n\n\ng\n\n0\n\n\n=\ng\n\n\n{\\displaystyle a_{0}=a;\\qquad g_{0}=g}\n\n\n \n\n\n\n\na\n\nn\n+\n1\n\n\n=\n\n\n\n1\n2\n\n\n\n(\n\na\n\nn\n\n\n+\n\ng\n\nn\n\n\n)\n;\n\n\ng\n\nn\n+\n1\n\n\n=\n\n\n\na\n\nn\n\n\n\ng\n\nn\n\n\n\n\n.\n\n\n{\\displaystyle a_{n+1}={\\tfrac {1}{2}}(a_{n}+g_{n});\\quad g_{n+1}={\\sqrt {a_{n}g_{n}}}.}\n\n\nSince the limit of \n\n\n\n\na\n\nn\n\n\n\u2212\n\ng\n\nn\n\n\n\n\n{\\displaystyle a_{n}-g_{n}}\n\n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n\n\n\n\n\n\na\ng\nm\n\n(\n1\n,\n1\n\n/\n\n\n\n2\n\n\n)\n\n\n{\\displaystyle \\mathrm {agm} (1,1/{\\sqrt {2}})}\n\n\n\n\nAlso see\n\n \u00a0 mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "output": "WITH\n rec (rn, a, g, diff) AS (\n SELECT 1, 1, 1/SQRT(2), 1 - 1/SQRT(2)\n FROM dual\n UNION ALL\n SELECT rn + 1, (a + g)/2, SQRT(a * g), (a + g)/2 - SQRT(a * g)\n FROM rec\n WHERE diff > 1e-38\n )\nSELECT *\nFROM rec\nWHERE diff <= 1e-38\n;", "input": ""}, {"instruction": "Some computer programming languages are not exactly consistent \u00a0 (with other computer programming languages) \u00a0\n\nwhen \u00a0 raising zero to the zeroth power: \u00a0 \u00a0 00\n\n\n\nTask\n\nShow the results of raising \u00a0 zero \u00a0 to the \u00a0 zeroth \u00a0 power.\n\n\n\nIf your computer language objects to \u00a0 \u00a0 0**0 \u00a0 \u00a0 or \u00a0 \u00a0 0^0 \u00a0 \u00a0 at compile time, \u00a0 you may also try something like:\n\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\nShow the result here.\n\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation.\n\n\n\nSee also\n\n The Wiki entry: Zero to the power of zero. \n The Wiki entry: History of differing points of view.\n The MathWorld\u2122 entry: exponent laws.\n Also, in the above MathWorld\u2122 entry, see formula (9): \n\n\n\n\nx\n\n0\n\n\n=\n1\n\n\n{\\displaystyle x^{0}=1}\n\n.\n The OEIS entry: The special case of zero to the zeroth power\n\n", "output": "\u00a0\nSQL> SELECT POWER(0,0) FROM dual;\n\u00a0", "input": ""}, {"instruction": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and \u00a0toggle\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it).\n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it.\n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n\nTask\n\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\nAlternate:\nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n\n\n", "output": "\u00a0\nDROP PROCEDURE IF EXISTS one_hundred_doors;\n\u00a0\nDELIMITER |\n\u00a0\nCREATE PROCEDURE one_hundred_doors (n INT)\nBEGIN\n DROP TEMPORARY TABLE IF EXISTS doors; \n CREATE TEMPORARY TABLE doors (\n id INTEGER NOT NULL,\n open BOOLEAN DEFAULT FALSE,\n PRIMARY KEY (id)\n );\n\u00a0\n SET @i = 1;\n create_doors: LOOP\n INSERT INTO doors (id, open) values (@i, FALSE);\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE create_doors;\n END IF;\n END LOOP create_doors;\n\u00a0\n SET @i = 1;\n toggle_doors: LOOP\n UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0;\n SET @i = @i + 1;\n IF @i > n THEN\n LEAVE toggle_doors;\n END IF;\n END LOOP toggle_doors;\n\u00a0\n SELECT id FROM doors WHERE open;\nEND|\n\u00a0\nDELIMITER ;\n\u00a0\nCALL one_hundred_doors(100);\n\u00a0", "input": ""}, {"instruction": "Task\n\nWrite/display a language's name in 3D ASCII.\n\n\n\n(We can leave the definition of \"3D ASCII\" fuzzy,\nso long as the result is interesting or amusing,\nnot a cheap hack to satisfy the task.)\n\n\n\nRelated tasks\n\n draw a sphere\n draw a cuboid\n draw a rotating cube\n draw a Deathstar\n\n", "output": "SELECT ' SSS\\ ' AS s, ' QQQ\\ ' AS q, 'L\\ ' AS l FROM dual\nUNION ALL SELECT 'S \\|', 'Q Q\\ ', 'L | ' FROM dual\nUNION ALL SELECT '\\SSS ', 'Q Q |', 'L | ' FROM dual\nUNION ALL SELECT ' \\ S\\', 'Q Q Q |', 'L | ' from dual\nunion all select ' SSS |', '\\QQQ\\\\|', 'LLLL\\' from dual\nunion all select ' \\__\\/', ' \\_Q_/ ', '\\___\\' from dual\nunion all select ' ', ' \\\\ ', ' ' from dual;", "input": ""}, {"instruction": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and \u00a0toggle\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it).\n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it.\n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n\nTask\n\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\nAlternate:\nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n\n\n", "output": "\u00a0\nDECLARE\n TYPE doorsarray IS VARRAY(100) OF BOOLEAN;\n doors doorsarray := doorsarray();\nBEGIN\n\u00a0\ndoors.EXTEND(100); --ACCOMMODATE 100 DOORS\n\u00a0\nFOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE\n LOOP\n doors(i) := FALSE; \n END LOOP;\n\u00a0\nFOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE\n LOOP\n FOR k IN 1 .. 100\n LOOP\n IF MOD(k,j)=0 THEN \n doors(k) := NOT doors(k); \n END IF;\n END LOOP;\n END LOOP;\n\u00a0\nFOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION\n LOOP\n DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE' \n THEN 'OPEN' \n ELSE 'CLOSED' \n END);\n END LOOP;\n\u00a0\nEND;\n\u00a0", "input": ""}, {"instruction": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and \u00a0toggle\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it).\n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it.\n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n\nTask\n\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\nAlternate:\nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n\n\n", "output": "\u00a0\nDECLARE\t@sqr INT,\n\t\t@i INT,\n\t\t@door INT;\n\u00a0\nSELECT @sqr =1,\n\t@i = 3,\n\t@door = 1;\t\n\u00a0\nWHILE(@door <=100)\nBEGIN\n\tIF(@door = @sqr)\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CAST(@door AS CHAR)) + ' is open.';\n\t\tSET @sqr= @sqr+@i;\n\t\tSET @i=@i+2;\n\tEND\n\tELSE\n\tBEGIN\n\t\tPRINT 'Door ' + RTRIM(CONVERT(CHAR,@door)) + ' is closed.';\n\tEND\nSET @door = @door + 1\nEND\n\u00a0\n\u00a0", "input": ""}, {"instruction": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and \u00a0toggle\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it).\n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it.\n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n\nTask\n\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\nAlternate:\nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE TYPE DOORS_ARRAY AS BOOLEAN ARRAY [100];\n DECLARE DOORS DOORS_ARRAY;\n DECLARE I SMALLINT;\n DECLARE J SMALLINT;\n DECLARE STATUS CHAR(10);\n DECLARE SIZE SMALLINT DEFAULT 100;\n\u00a0\n -- Initializes the array, with all spaces (doors) as false (closed).\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET DOORS[I] = FALSE;\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- Processes the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET J = 1;\n WHILE (J <= SIZE) DO\n IF (MOD(J, I) = 0) THEN\n IF (DOORS[J] = TRUE) THEN\n SET DOORS[J] = FALSE;\n ELSE\n SET DOORS[J] = TRUE;\n END IF;\n END IF;\n SET J = J + 1;\n END WHILE;\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- Prints the final status o the doors.\n SET I = 1;\n WHILE (I <= SIZE) DO\n SET STATUS = (CASE WHEN (DOORS[I] = TRUE) THEN 'OPEN' ELSE 'CLOSED' END);\n CALL DBMS_OUTPUT.PUT_LINE('Door ' || I || ' is '|| STATUS);\n SET I = I + 1;\n END WHILE;\nEND @\n\u00a0", "input": ""}, {"instruction": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and \u00a0toggle\u00a0 the door \u00a0(if the door is closed, \u00a0open it; \u00a0 if it is open,\u00a0 close it).\n\nThe second time, only visit every 2nd door \u00a0 (door #2, #4, #6, ...), \u00a0 and toggle it.\n\nThe third time, visit every 3rd door \u00a0 (door #3, #6, #9, ...), etc, \u00a0 until you only visit the 100th door.\n\n\n\nTask\n\nAnswer the question: \u00a0 what state are the doors in after the last pass? \u00a0 Which are open, which are closed?\n\n\nAlternate:\nAs noted in this page's \u00a0 discussion page, \u00a0 the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an \u00a0 optimization \u00a0 that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n\n\n", "output": "\u00a0\nWITH OneToTen (N)\nAS ( SELECT N\n FROM ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)\n ) V(N)\n )\n , InitDoors (Num, IsOpen)\nAS ( SELECT 1\n + 1 * Units.N\n + 10 * Tens.N AS Num\n , CONVERT(Bit, 0) AS IsOpen\n FROM OneToTen AS Units\n CROSS JOIN OneToTen AS Tens\n ) -- This part could be easier with a tally table or equivalent table-valued function\n , States (NbStep, Num, IsOpen)\nAS ( SELECT 0 AS NbStep\n , Num\n , IsOpen\n FROM InitDoors AS InitState\n UNION ALL\n SELECT 1 + NbStep\n , Num\n , CASE Num\u00a0% (1 + NbStep)\n WHEN 0 THEN ~IsOpen\n ELSE IsOpen\n END\n FROM States\n WHERE NbStep < 100\n )\nSELECT Num AS DoorNumber\n , Concat( 'Door number ', Num, ' is '\n , CASE IsOpen\n WHEN 1 THEN ' open'\n ELSE ' closed'\n END ) AS RESULT -- Concat needs SQL Server 2012\nFROM States\nWHERE NbStep = 100\nORDER BY Num\n; -- Fortunately, maximum recursion is 100 in SQL Server.\n-- For more doors, the MAXRECURSION hint should be used.\n-- More doors would also need an InitDoors with more rows.\n\u00a0", "input": ""}, {"instruction": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.\n\n\n\nTask\n\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, \u00a0 and \u00a0 the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n\nDetails\n\nThe format of an ISIN is as follows:\n\n\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 2-character ISO country code (A-Z)\n\u2502\u00a0\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 9-character security code (A-Z, 0-9)\n\u2502\u00a0\u2502\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u250c\u2500\u2500 a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n\n Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 \u21921030000033311635103.\n Perform the Luhn test on this base-10 number.\nThere is a separate task for this test: Luhn test of credit card numbers.\nYou don't have to replicate the implementation of this test here \u00a0 \u2500\u2500\u2500 \u00a0 you can just call the existing function from that task. \u00a0 (Add a comment stating if you did this.)\n\n\nTest cases\n\n\n\n ISIN\n\n Validity\n\n Comment\n\n\n US0378331005 \n valid \n\n\n\n US0373831005 \n not valid \n The transposition typo is caught by the checksum constraint.\n\n\n U50378331005 \n not valid \n The substitution typo is caught by the format constraint.\n\n\n US03378331005 \n not valid \n The duplication typo is caught by the format constraint.\n\n\n AU0000XVGZA3 \n valid \n\n\n\n AU0000VXGZA3 \n valid \n Unfortunately, not all transposition typos are caught by the checksum constraint.\n\n\n FR0000988040 \n valid \n\n\n(The comments are just informational. \u00a0 Your function should simply return a Boolean result. \u00a0 See #Raku for a reference solution.)\n\n\n\nRelated task:\n\n Luhn test of credit card numbers\n\n\nAlso see\n\n Interactive online ISIN validator\n Wikipedia article: International Securities Identification Number\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nCREATE OR REPLACE FUNCTION VALIDATE_ISIN (\n IN IDENTIFIER VARCHAR(12)\n ) RETURNS SMALLINT\n -- ) RETURNS BOOLEAN\n BEGIN\n DECLARE CHECKSUM_FUNC CHAR(1);\n DECLARE CONVERTED VARCHAR(24);\n DECLARE I SMALLINT;\n DECLARE LENGTH SMALLINT;\n DECLARE RET SMALLINT DEFAULT 1;\n --DECLARE RET BOOLEAN DEFAULT FALSE;\n DECLARE CHAR_AT CHAR(1);\n DECLARE INVALID_CHAR CONDITION FOR SQLSTATE 'ISIN1';\n\u00a0\n SET CHAR_AT = SUBSTR(IDENTIFIER, 1, 1);\n IF (ASCII(CHAR_AT) < 65 OR 90 < ASCII(CHAR_AT)) THEN\n SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Country code with invalid characters';\n END IF;\n SET CHAR_AT = SUBSTR(IDENTIFIER, 2, 1);\n IF (ASCII(CHAR_AT) < 65 OR 90 < ASCII(CHAR_AT)) THEN\n SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Country code with invalid characters';\n END IF;\n\u00a0\n -- Convert letters to numbers.\n SET I = 1;\n SET CONVERTED = '';\n SET LENGTH = LENGTH(IDENTIFIER);\n WHILE (I <= LENGTH) DO\n SET CHAR_AT = SUBSTR(IDENTIFIER, I, 1);\n IF (48 <= ASCII(CHAR_AT) AND ASCII(CHAR_AT) <= 57) THEN\n SET CONVERTED = CONVERTED || CHAR_AT;\n ELSE\n SET CONVERTED = CONVERTED || (ASCII(CHAR_AT) - 55);\n END IF;\n SET I = I + 1;\n END WHILE;\n\u00a0\n CALL DBMS_OUTPUT.PUT_LINE(CONVERTED);\n\u00a0\n -- This function is implemented in Rosetta code.\n SET CHECKSUM_FUNC = LUHN_TEST(CONVERTED);\n IF (CHECKSUM_FUNC = 0) THEN\n SET RET = 0;\n --SET RET = TRUE;\n END IF;\n\u00a0\n RETURN RET;\n END @\n\u00a0", "input": ""}, {"instruction": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.\n\n\n\nTask\n\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, \u00a0 and \u00a0 the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n\nDetails\n\nThe format of an ISIN is as follows:\n\n\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 2-character ISO country code (A-Z)\n\u2502\u00a0\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 a 9-character security code (A-Z, 0-9)\n\u2502\u00a0\u2502\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u250c\u2500\u2500 a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n\n Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 \u21921030000033311635103.\n Perform the Luhn test on this base-10 number.\nThere is a separate task for this test: Luhn test of credit card numbers.\nYou don't have to replicate the implementation of this test here \u00a0 \u2500\u2500\u2500 \u00a0 you can just call the existing function from that task. \u00a0 (Add a comment stating if you did this.)\n\n\nTest cases\n\n\n\n ISIN\n\n Validity\n\n Comment\n\n\n US0378331005 \n valid \n\n\n\n US0373831005 \n not valid \n The transposition typo is caught by the checksum constraint.\n\n\n U50378331005 \n not valid \n The substitution typo is caught by the format constraint.\n\n\n US03378331005 \n not valid \n The duplication typo is caught by the format constraint.\n\n\n AU0000XVGZA3 \n valid \n\n\n\n AU0000VXGZA3 \n valid \n Unfortunately, not all transposition typos are caught by the checksum constraint.\n\n\n FR0000988040 \n valid \n\n\n(The comments are just informational. \u00a0 Your function should simply return a Boolean result. \u00a0 See #Raku for a reference solution.)\n\n\n\nRelated task:\n\n Luhn test of credit card numbers\n\n\nAlso see\n\n Interactive online ISIN validator\n Wikipedia article: International Securities Identification Number\n\n", "output": "\u00a0\nCREATE FUNCTION dbo._ISINCheck( @strISIN VarChar(40) )\nRETURNS bit\nAS\nBEGIN\n--*** Test an ISIN code and return 1 if it is valid, 0 if invalid.\nDECLARE @bValid\t bit;\n\u00a0\nSET @bValid = CASE WHEN @strISIN LIKE '[A-Z][A-Z][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9]' THEN 1 ELSE 0 END\nIF @bValid = 1\n\tBEGIN\n\t\tDECLARE @strTest VarChar(40) = '';\n\t\tDECLARE @strAdd VarChar(2);\n\t\tDECLARE @p INT = 0;\n\t\tWHILE @p < LEN(@strISIN)\n\t\t\tBEGIN\n\t\t\t\tSET @p = @p+1;\n\t\t\t\tSET @strAdd = SUBSTRING(@strISIN,@p,1);\n\t\t\t\tIF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55);\n\t\t\t\tSET @strTest = @strTest + @strAdd;\n\t\t\tEND;\n\u00a0\n\t\t-- Proceed with Luhn test\n\t\tDECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed\n\t\tDECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values\n\t\tSET @p = 0; -- reset loop counter\n\t\tDECLARE @intValue INT;\n\t\tDECLARE @intSum\tINT = 0;\n\t\t-- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum\n\t\tWHILE @p < LEN(@strLuhn)\n\t\t\tBEGIN\n\t\t\t\tSET @p = @p+1;\n\t\t\t\tSET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string\n\t\t\t\tIF @p\u00a0% 2 = 0\tSET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1))\n\t\t\t\tSET @intSum = @intSum + @intValue\n\t\t\tEND\n\t\t-- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds\n\t\tSET @bValid = CASE WHEN @intSum\u00a0% 10 = 0 THEN 1 ELSE 0 END \n\tEND;\n\u00a0\nRETURN @bValid\nEND\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a Thue-Morse sequence.\n\n\n\nSee also\n \u00a0 YouTube entry: The Fairest Sharing Sequence Ever\n \u00a0 YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n \u00a0 Task: Fairshare between two and more\n\n", "output": "WITH recursive a(a) AS (SELECT '0' UNION ALL SELECT REPLACE(REPLACE(hex(a),'30','01'),'31','10') FROM a) SELECT * FROM a;", "input": ""}, {"instruction": "Task\n\nFind the top \u00a0 N \u00a0 salaries in each department, \u00a0 where \u00a0 N \u00a0 is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "output": "CREATE OR REPLACE PROCEDURE \"Top rank per group\"(TOP_N IN PLS_INTEGER DEFAULT 3) AS\n CURSOR CSR_EMP(TOP_N PLS_INTEGER) IS\n SELECT CASE LINE\n WHEN 10 THEN\n 'Tot.' || LPAD(POPULATION, 2) || ' Employees in ' || TIE_COUNT ||\n ' deps.Avg salary:' || TO_CHAR(SALARY, '99990.99')\n WHEN 30 THEN\n '-'\n WHEN 50 THEN\n 'Department: ' || DEPT_ID || ', pop: ' || POPULATION ||\n '. Avg Salary: ' || TO_CHAR(SALARY, '99990.99')\n WHEN 70 THEN\n LPAD('Employee ID', 14) || LPAD('Employee name', 20) ||\n LPAD('Salary', 9) || 'Rank'\n WHEN 90 THEN\n LPAD('+', 14, '-') || LPAD('+', 20, '-') || LPAD('+', 9, '-') ||\n LPAD('+', 4, '-')\n ELSE\n LPAD(' ', 8) || LPAD(EMP_ID, 6) || LPAD(EMP_NAME, 20) ||\n TO_CHAR(SALARY, '99990.99') ||\n LPAD(CASE WHEN TIE_COUNT = 1 THEN ' ' ELSE 'T' END || RANK, 4)\n END \"Top rank per group\"\n FROM (SELECT 10 LINE\n ,NULL EMP_ID\n ,NULL EMP_NAME\n ,' ' DEPT_ID\n ,AVG(SALARY) SALARY\n ,0 RANK\n ,COUNT(DISTINCT DEPT_ID) TIE_COUNT\n ,COUNT(*) POPULATION\n FROM EMP\n UNION ALL\n SELECT 30 LINE\n ,NULL EMP_ID\n ,NULL EMP_NAME\n ,DEPT_ID\n ,0 SALARY\n ,0 RANK\n ,0 TIE_COUNT\n ,0 POPULATION\n FROM EMP\n GROUP BY DEPT_ID\n UNION ALL\n SELECT 50 LINE\n ,NULL EMP_ID\n ,NULL EMP_NAME\n ,DEPT_ID\n ,AVG(SALARY) SALARY\n ,0 RANK\n ,0 TIE_COUNT\n ,COUNT(*) POPULATION\n FROM EMP\n GROUP BY DEPT_ID\n UNION ALL\n SELECT 70 LINE\n ,NULL EMP_ID\n ,NULL EMP_NAME\n ,DEPT_ID\n ,0 SALARY\n ,0 RANK\n ,0 TIE_COUNT\n ,0 POPULATION\n FROM EMP\n GROUP BY DEPT_ID\n UNION ALL\n SELECT 90 LINE\n ,NULL EMP_ID\n ,NULL EMP_NAME\n ,DEPT_ID\n ,0 SALARY\n ,0 RANK\n ,0 TIE_COUNT\n ,0 POPULATION\n FROM EMP\n GROUP BY DEPT_ID\n UNION ALL\n SELECT 110 LINE\n ,EMP_ID\n ,EMP_NAME\n ,DEPT_ID\n ,SALARY\n ,(SELECT COUNT(DISTINCT EMP4.SALARY)\n FROM EMP EMP4\n WHERE EMP4.DEPT_ID = EMP3.DEPT_ID\n AND EMP4.SALARY >= EMP3.SALARY) RANK\n ,(SELECT COUNT(*)\n FROM EMP EMP2\n WHERE EMP2.DEPT_ID = EMP3.DEPT_ID\n AND EMP2.SALARY = EMP3.SALARY) TIE_COUNT\n ,0 POPULATION\n FROM EMP EMP3\n WHERE TOP_N >= -- Here is the meat, Correlated subquery\n (SELECT COUNT(DISTINCT EMP4.SALARY)\n FROM EMP EMP4\n WHERE EMP4.DEPT_ID = EMP3.DEPT_ID\n AND EMP4.SALARY >= EMP3.SALARY))\n ORDER BY DEPT_ID\n ,LINE\n ,SALARY DESC\n ,EMP_ID;\n\u00a0\n V_EMP CSR_EMP%ROWTYPE;\nBEGIN\n FOR V_EMP IN CSR_EMP(TOP_N)\n LOOP\n DBMS_OUTPUT.PUT_LINE(v_emp.\"Top rank per group\");\n END LOOP;\nEND;", "input": ""}, {"instruction": "Task\n\nIf your language has a library or built-in functions for trigonometry, show examples of:\n\n \u00a0 sine\n \u00a0 cosine\n \u00a0 tangent\n \u00a0 inverses \u00a0 (of the above)\n\nusing the same angle in radians and degrees.\n\nFor the non-inverse functions, \u00a0 each radian/degree pair should use arguments that evaluate to the same angle \u00a0 (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).\n\nFor the inverse functions, \u00a0 use the same number and convert its answer to radians and degrees.\n\nIf your language does not have trigonometric functions available or only has some available, \u00a0 write functions to calculate the functions based on any \u00a0 known approximation or identity.\n\n\n\n", "output": "DECLARE\n pi NUMBER := 4 * ATAN(1);\n radians NUMBER := pi / 4;\n degrees NUMBER := 45.0;\nBEGIN\n DBMS_OUTPUT.put_line(SIN(radians) || ' ' || SIN(degrees * pi/180) );\n DBMS_OUTPUT.put_line(COS(radians) || ' ' || COS(degrees * pi/180) );\n DBMS_OUTPUT.put_line(TAN(radians) || ' ' || TAN(degrees * pi/180) );\n DBMS_OUTPUT.put_line(ASIN(SIN(radians)) || ' ' || ASIN(SIN(degrees * pi/180)) * 180/pi);\n DBMS_OUTPUT.put_line(ACOS(COS(radians)) || ' ' || ACOS(COS(degrees * pi/180)) * 180/pi);\n DBMS_OUTPUT.put_line(ATAN(TAN(radians)) || ' ' || ATAN(TAN(degrees * pi/180)) * 180/pi);\nEND;", "input": ""}, {"instruction": "\nTask\n\nPlay a game of tic-tac-toe.\n\nEnsure that legal moves are played and that a winning position is notified.\n\n\nTic-tac-toe \u00a0 is also known as:\n\n \u00a0 naughts and crosses \n \u00a0 tic tac toe \n \u00a0 tick tack toe \n \u00a0 three in a row \n \u00a0 tres en rayo \u00a0 \u00a0 \u00a0 and\n \u00a0 Xs \u00a0and\u00a0 Os\n\n\nSee also\n \u00a0 MathWorld\u2122, Tic-Tac-Toe game.\n \u00a0 Wikipedia tic-tac-toe.\n\n", "output": "\u00a0\n--Setup\nDROP TABLE IF EXISTS board;\nCREATE TABLE board (p CHAR, r INTEGER, c INTEGER);\nINSERT INTO board VALUES('.', 0, 0),('.', 0, 1),('.', 0, 2),('.', 1, 0),('.', 1, 1),('.', 1, 2),('.', 2, 0),('.', 2, 1),('.', 2, 2);\n\u00a0\n\u00a0\n-- Use a trigger for move events\nDROP TRIGGER IF EXISTS after_moved;\nCREATE TRIGGER after_moved after UPDATE ON board FOR each ROW WHEN NEW.p <> '.' AND NEW.p <> 'O'\nBEGIN\n\u00a0\n -- Verify move is valid\n SELECT \n CASE \n WHEN (SELECT v FROM msg) LIKE '%Wins!' THEN raise(ABORT, 'The game is already over.') \n WHEN (SELECT OLD.p FROM board WHERE rowid = rid) <> '.' THEN raise(ABORT, 'That position has already been taken. Please choose an available position.') \n WHEN NEW.p <> 'X' THEN raise(ABORT, 'Please place an ''X''')\n END \n FROM (\n SELECT rowid rid FROM board\n WHERE p = NEW.p\n EXCEPT \n SELECT p FROM board WHERE p = OLD.p\n );\n\u00a0\n\u00a0\n -- Check for game over\n UPDATE msg SET v = (\n SELECT \n CASE \n WHEN MAX(num) >= 3 THEN 'X Wins!'\n WHEN (SELECT COUNT(*) FROM board WHERE p = '.') = 0 THEN 'Cat Wins!'\n ELSE 'Move made'\n END \n FROM ( -- Is Game Over\n SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY r UNION -- Horz\n SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY c UNION -- Vert\n SELECT COUNT(*) num FROM board WHERE p = 'X' AND r = c UNION -- Diag TL->BR\n SELECT COUNT(*) num FROM board WHERE p = 'X' AND (2-r) = c -- Diag TR->BL\n )\n );\n\u00a0\n\u00a0\n --Have computer player make a random move\n UPDATE board SET p = 'O' \n WHERE rowid = (SELECT rid FROM (SELECT MAX(rnd),rid FROM (SELECT rowid rid, random() rnd FROM board WHERE p = '.')))\n AND (SELECT v FROM msg) NOT LIKE '%Wins!';\n --NOTE: SQLite doesn't allow update order by in triggers, otherwise we could just use this beautiful line:\n -- update board set p = 'O' where p = '.' order by random() limit 1;\n\u00a0\n --Check to see if the computer player won\n UPDATE msg SET v = (\n SELECT \n CASE \n WHEN MAX(num) >= 3 THEN 'O Wins!' \n ELSE v\n END \n FROM ( -- Is Game Over\n SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY r UNION -- Horz\n SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY c UNION -- Vert\n SELECT COUNT(*) num FROM board WHERE p = 'O' AND r = c UNION -- Diag TL->BR\n SELECT COUNT(*) num FROM board WHERE p = 'O' AND (2-r) = c -- Diag TR->BL\n )\n );\n\u00a0\n\u00a0\nEND;\n\u00a0\n-- UI to display the logical board as a grid\nDROP VIEW IF EXISTS ui;\nCREATE VIEW ui AS\nSELECT CASE WHEN p = '.' THEN col0.rowid ELSE p END c0, c1, c2\nFROM board AS col0 \nJOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c1, r FROM board WHERE c = 1) AS col1 ON col0.r = col1.r\nJOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c2, r FROM board WHERE c = 2) AS col2 ON col0.r = col2.r\nWHERE c = 0;\n\u00a0\nDROP TABLE IF EXISTS msg;\nCREATE TABLE msg (v text);\nINSERT INTO msg VALUES('');\n\u00a0\n-- Readme\nSELECT * FROM ui;\n.print \"Use this to play:\"\n.print \"->update board set p = 'X' where rowid =\u00a0?; select * from ui; select * from msg;\"'\n\u00a0\n", "input": ""}, {"instruction": "Task\n\nIf your language has a library or built-in functions for trigonometry, show examples of:\n\n \u00a0 sine\n \u00a0 cosine\n \u00a0 tangent\n \u00a0 inverses \u00a0 (of the above)\n\nusing the same angle in radians and degrees.\n\nFor the non-inverse functions, \u00a0 each radian/degree pair should use arguments that evaluate to the same angle \u00a0 (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).\n\nFor the inverse functions, \u00a0 use the same number and convert its answer to radians and degrees.\n\nIf your language does not have trigonometric functions available or only has some available, \u00a0 write functions to calculate the functions based on any \u00a0 known approximation or identity.\n\n\n\n", "output": "\u00a0\n--Conversion\nVALUES degrees(3.1415926);\nVALUES radians(180);\n-- This is equal to Pi.\n\u00a0\n--PI/4 45\nVALUES sin(radians(180)/4);\nVALUES sin(radians(45));\nVALUES cos(radians(180)/4);\nVALUES cos(radians(45));\nVALUES tan(radians(180)/4);\nVALUES tan(radians(45));\nVALUES cot(radians(180)/4);\nVALUES cot(radians(45));\nVALUES asin(sin(radians(180)/4));\nVALUES asin(sin(radians(45)));\nVALUES atan(tan(radians(180)/4));\nVALUES atan(tan(radians(45)));\n\u00a0\n--PI/3 60\nVALUES sin(radians(180)/3);\nVALUES sin(radians(60));\nVALUES cos(radians(180)/3);\nVALUES cos(radians(60));\nVALUES tan(radians(180)/3);\nVALUES tan(radians(60));\nVALUES cot(radians(180)/3);\nVALUES cot(radians(60));\nVALUES asin(sin(radians(180)/3));\nVALUES asin(sin(radians(60)));\nVALUES atan(tan(radians(180)/3));\nVALUES atan(tan(radians(60)));\n\u00a0", "input": ""}, {"instruction": "Task\n\nFind the top \u00a0 N \u00a0 salaries in each department, \u00a0 where \u00a0 N \u00a0 is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "output": "CREATE TABLE EMP\n(\nEMP_ID varchar2(6 CHAR),\nEMP_NAMEvarchar2(20 CHAR),\nDEPT_ID varchar2(4 CHAR),\nSALARY NUMBER(10,2)\n);\n\u00a0\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E21437','John Rappl','D050',47000);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E10297','Tyler Bennett','D101',32000);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E00127','George Woltman','D101',53500);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E63535','Adam Smith','D202',18000);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E39876','Claire Buckman','D202',27800);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E04242','David McClellan','D101',41500);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E41298','Nathan Adams','D050',21900);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E43128','Richard Potter','D101',15900);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E27002','David Motsinger','D202',19250);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E03033','Tim Sampair','D101',27000);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E10001','Kim Arlich','D190',57000);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E16398','Timothy Grove','D190',29900);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E01234','Rich Holcomb','D202',49500);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E16399','Timothy Grave','D190',29900);\nINSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)\n VALUES ('E16400','Timothy Grive','D190',29900);\nCOMMIT;", "input": ""}, {"instruction": "\n\nTask\n\nUsing a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.\n\nIf your language does not have a testing specific library well known to the language's community then state this or omit the language.\n\n\n", "output": "\u00a0\nCREATE OR REPLACE PROCEDURE TEST_MY_TEST()\n BEGIN\n DECLARE EXPECTED INTEGER;\n DECLARE ACTUAL INTEGER;\n CALL DB2UNIT.REGISTER_MESSAGE('My first test');\n SET EXPECTED = 2;\n SET ACTUAL = 1+1;\n CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);\n END @\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "CREATE TABLE `Address` (\n `addrID` int(11) NOT NULL auto_increment,\n `addrStreet` varchar(50) NOT NULL default '',\n `addrCity` varchar(25) NOT NULL default '',\n `addrState` char(2) NOT NULL default '',\n `addrZIP` char(10) NOT NULL default '',\n PRIMARY KEY (`addrID`)\n);", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "<?php\n$db = new SQLite3(':memory:');\n$db->exec(\"\n CREATE TABLE address (\n addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n addrStreet TEXT NOT NULL,\n addrCity TEXT NOT NULL,\n addrState TEXT NOT NULL,\n addrZIP TEXT NOT NULL\n )\n\");\n?>", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "CREATE SEQUENCE address_seq START 100;\nCREATE TABLE address (\n addrID int4 PRIMARY KEY DEFAULT NEXTVAL('address_seq'),\n street VARCHAR(50) NOT NULL,\n city VARCHAR(25) NOT NULL,\n state VARCHAR(2) NOT NULL,\n zip VARCHAR(20) NOT NULL\n);", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "\u00a0\nImport-Module -Name PSSQLite\n\u00a0\n\u00a0\n## Create a database and a table\n$dataSource = \".\\Addresses.db\"\n$query = \"CREATE TABLE SSADDRESS (Id INTEGER PRIMARY KEY AUTOINCREMENT,\n LastName TEXT NOT NULL,\n FirstName TEXT NOT NULL,\n Address TEXT NOT NULL,\n City TEXT NOT NULL,\n State CHAR(2) NOT NULL,\n Zip CHAR(5) NOT NULL\n)\"\n\u00a0\nInvoke-SqliteQuery -Query $Query -DataSource $DataSource\n\u00a0\n\u00a0\n## Insert some data\n$query = \"INSERT INTO SSADDRESS ( FirstName, LastName, Address, City, State, Zip)\n VALUES (@FirstName, @LastName, @Address, @City, @State, @Zip)\"\n\u00a0\nInvoke-SqliteQuery -DataSource $DataSource -Query $query -SqlParameters @{\n LastName = \"Monster\"\n FirstName = \"Cookie\"\n Address = \"666 Sesame St\"\n City = \"Holywood\"\n State = \"CA\"\n Zip = \"90013\"\n}\n\u00a0\n\u00a0\n## View the data\nInvoke-SqliteQuery -DataSource $DataSource -Query \"SELECT * FROM SSADDRESS\" | FormatTable -AutoSize\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "\u00a0\nUseSQLiteDatabase()\nProcedure CheckDatabaseUpdate(Database, Query$)\n Result = DatabaseUpdate(Database, Query$)\n If Result = 0\n Print(DatabaseError())\n EndIf\n ProcedureReturn Result\nEndProcedure\nopenconsole()\nDatabaseFile$ = GetCurrentDirectory()+\"/rosettadb.sdb\"\nIf CreateFile(0, DatabaseFile$)\n CloseFile(0)\n If OpenDatabase(0, DatabaseFile$, \"\", \"\")\n CheckDatabaseUpdate(0,\"CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT,\taddrStreet TEXT Not NULL, addrCity TEXT Not NULL, addrState TEXT Not NULL, addrZIP TEXT Not NULL)\")\n CloseDatabase(0)\n Else\n print(\"Can't open database\u00a0!\")\n EndIf\nElse\n print(\"Can't create the database file\u00a0!\")\nEndIf\ncloseconsole()\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": ">>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> conn.execute('''CREATE TABLE address (\n\taddrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\n\taddrStreet\tTEXT NOT NULL,\n\taddrCity\tTEXT NOT NULL,\n\taddrState\tTEXT NOT NULL,\n\taddrZIP\t\tTEXT NOT NULL\n )''')\n<sqlite3.Cursor object at 0x013265C0>\n>>> ", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "\u00a0\nCREATE TABLE Address (\n addrID INTEGER generated BY DEFAULT AS IDENTITY,\n addrStreet VARCHAR(50) NOT NULL,\n addrCity VARCHAR(25) NOT NULL,\n addrState CHAR(2) NOT NULL,\n addrZIP CHAR(10) NOT NULL\n);\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "\u00a0\nCREATE TABLE address_USA (\n address_ID INTEGER PRIMARY KEY,\n address_Street TEXT,\n address_City TEXT,\n address_State TEXT,\n address_Zip INTEGER\n);\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "package require sqlite3\n\u00a0\nsqlite3 db address.db\ndb eval {\n CREATE TABLE address (\n\taddrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\n\taddrStreet\tTEXT NOT NULL,\n\taddrCity\tTEXT NOT NULL,\n\taddrState\tTEXT NOT NULL,\n\taddrZIP\t\tTEXT NOT NULL\n )\n}", "input": ""}, {"instruction": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA. \u00a0 As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. \u00a0 Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.\n\n\n\n", "output": "CREATE TABLE #Address (\n addrID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,\n addrStreet VARCHAR(50) NOT NULL , \n addrCity VARCHAR(25) NOT NULL , \n addrState CHAR(2) NOT NULL , \n addrZIP CHAR(10) NOT NULL\n)\nDROP TABLE #Address", "input": ""}, {"instruction": "Task\n\nWrite a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.\nThe lyrics can be found here.\n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "\u00a0\nWITH\nFUNCTION nl ( s IN varchar2 )\nRETURN varchar2\nIS\nBEGIN\n RETURN chr(10) || s;\nEND nl;\nFUNCTION v ( d NUMBER, x NUMBER, g IN varchar2 )\nRETURN varchar2\nIS\nBEGIN\n RETURN\n CASE WHEN d >= x THEN nl (g) END;\nEND v;\nSELECT 'On the '\n || to_char(to_date(level,'j'),'jspth' )\n || ' day of Christmas,'\n || nl( 'my true love sent to me:')\n || v ( level, 12, 'Twelve drummers drumming,' )\n || v ( level, 11, 'Eleven pipers piping,' )\n || v ( level, 10, 'Ten lords a-leaping,' )\n || v ( level, 9, 'Nine ladies dancing,' )\n || v ( level, 8, 'Eight maids a-milking,' )\n || v ( level, 7, 'Seven swans a-swimming,' )\n || v ( level, 6, 'Six geese a-laying,' )\n || v ( level, 5, 'Five golden rings!' )\n || v ( level, 4, 'Four calling birds,' )\n || v ( level, 3, 'Three French hens,' )\n || v ( level, 2, 'Two turtle doves,' )\n || v ( level, 1, CASE level WHEN 1 THEN 'A' ELSE 'And a' END || ' partridge in a pear tree.' )\n || nl(NULL)\n \"The Twelve Days of Christmas\"\nFROM dual\nCONNECT BY level <= 12\n/\n\u00a0", "input": ""}, {"instruction": "Task\nGiven two sets A and B, compute \n\n\n\n(\nA\n\u2216\nB\n)\n\u222a\n(\nB\n\u2216\nA\n)\n.\n\n\n{\\displaystyle (A\\setminus B)\\cup (B\\setminus A).}\n\n\n\nThat is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.\n\nIn other words: \n\n\n\n(\nA\n\u222a\nB\n)\n\u2216\n(\nA\n\u2229\nB\n)\n\n\n{\\displaystyle (A\\cup B)\\setminus (A\\cap B)}\n\n (the set of items that are in at least one of A or B minus the set of items that are in both A and B).\n\nOptionally, give the individual differences (\n\n\n\nA\n\u2216\nB\n\n\n{\\displaystyle A\\setminus B}\n\n and \n\n\n\nB\n\u2216\nA\n\n\n{\\displaystyle B\\setminus A}\n\n) as well.\n\n\n\nTest cases\nA = {John, Bob, Mary, Serena}\nB = {Jim, Mary, John, Bob}\n\n\n\nNotes\n If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = [\"John\", \"Serena\", \"Bob\", \"Mary\", \"Serena\"] and b = [\"Jim\", \"Mary\", \"John\", \"Jim\", \"Bob\"] should produce the result of just two strings: [\"Serena\", \"Jim\"], in any order.\n In the mathematical notation above A \\ B gives the set of items in A that are not in B; A \u222a B gives the set of items in both A and B, (their union); and A \u2229 B gives the set of items that are in both A and B (their intersection).\n\n", "output": "CREATE OR REPLACE FUNCTION arrxor(anyarray,anyarray) RETURNS anyarray AS $$\nSELECT ARRAY(\n (\n SELECT r.elements\n FROM (\n (SELECT 1,unnest($1))\n UNION ALL\n (SELECT 2,unnest($2))\n ) AS r (arr, elements)\n GROUP BY 1\n HAVING MIN(arr) = MAX(arr)\n )\n)\n$$ LANGUAGE SQL strict immutable;", "input": ""}, {"instruction": "Task\n\nOutput the system time \u00a0 (any units will do as long as they are noted) either by a system command or one built into the language.\n\nThe system time can be used for debugging, network information, random number seeds, or something as simple as program performance.\n\n\n\nRelated task\n\n \u00a0 Date format\n\n\nSee also\n\n \u00a0 Retrieving system time (wiki)\n\n", "output": "\u00a0\nSELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1;\n\u00a0", "input": ""}, {"instruction": "Task\n\nWrite a program to find the sum of squares of a numeric vector.\n\nThe program should work on a zero-length vector (with an answer of \u00a0 0).\n\n\n\nRelated task\n\n \u00a0 Mean\n\n", "output": "SELECT SUM(x*x) FROM vector", "input": ""}, {"instruction": "Task\n\nTake a \u00a0 Natural Number \u00a0 in a given base and return the sum of its digits:\n\n \u00a0 110 \u00a0 \u00a0 \u00a0 \u00a0 sums to \u00a0 1\n \u00a0 123410 \u00a0 sums to \u00a0 10\n \u00a0 fe16 \u00a0 \u00a0 \u00a0 sums to \u00a0 29\n \u00a0 f0e16 \u00a0 \u00a0 sums to \u00a0 29\n\n", "output": "\u00a0\n/*\nThis code is an implementation of \"Sum digits of an integer\" in SQL ORACLE 19c \np_in_str -- input string\n*/\nWITH\n FUNCTION sum_digits(p_in_str IN varchar2) RETURN varchar2 IS\n v_in_str VARCHAR(32767)\u00a0:= translate(p_in_str,'*-+','*');\n v_sum INTEGER;\nBEGIN\n --\n IF regexp_count(v_in_str,'[0-9A-F]',1,'i')=LENGTH(v_in_str) THEN -- base 16\n EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\\w)','to_number(''\\1'',''X'')+')||'0) from dual' INTO v_sum;\n -- \n elsif regexp_count(v_in_str,'[0-9]',1,'i')=LENGTH(v_in_str) THEN -- base 10 \n EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\\d)','\\1+')||'0) from dual' INTO v_sum;\n --\n ELSE\n RETURN 'Sum of digits for integer \"'||p_in_str||'\" not defined';\n -- \n END IF;\n -- \n RETURN 'Sum of digits for integer \"'||p_in_str||'\" = '||v_sum;\nEND;\n\u00a0\n--Test\nSELECT sum_digits('') AS res FROM dual\nUNION ALL \nSELECT sum_digits('000') AS res FROM dual\nUNION ALL \nSELECT sum_digits('-010') AS res FROM dual\nUNION ALL\nSELECT sum_digits('+010') AS res FROM dual\nUNION ALL \nSELECT sum_digits('120034') AS res FROM dual\nUNION ALL \nSELECT sum_digits('FE') AS res FROM dual\nUNION ALL \nSELECT sum_digits('f0e') AS res FROM dual\nUNION ALL\nSELECT sum_digits('\u00f6st12') AS res FROM dual;\n\u00a0", "input": ""}, {"instruction": "Task\n\nSolve a partially filled-in normal \u00a0 9x9 \u00a0 Sudoku grid \u00a0 and display the result in a human-readable format.\n\nreferences\n\n Algorithmics of Sudoku \u00a0 may help implement this.\n Python Sudoku Solver Computerphile video.\n\n", "output": "WITH\n symbols (d) AS (SELECT to_char(level) FROM dual CONNECT BY level <= 9)\n, board (i) AS (SELECT level FROM dual CONNECT BY level <= 81)\n, neighbors (i, j) AS (\n SELECT b1.i, b2.i\n FROM board b1 INNER JOIN board b2\n ON b1.i\u00a0!= b2.i\n AND (\n MOD(b1.i - b2.i, 9) = 0\n OR CEIL(b1.i / 9) = CEIL(b2.i / 9)\n OR CEIL(b1.i / 27) = CEIL(b2.i / 27) AND trunc(MOD(b1.i - 1, 9) / 3) = trunc(MOD(b2.i - 1, 9) / 3)\n )\n )\n, r (str, pos) AS (\n SELECT \u00a0:game, instr(:game, ' ')\n FROM dual\n UNION ALL\n SELECT substr(r.str, 1, r.pos - 1) || s.d || substr(r.str, r.pos + 1), instr(r.str, ' ', r.pos + 1)\n FROM r INNER JOIN symbols s\n ON r.pos > 0 AND NOT EXISTS (\n SELECT *\n FROM neighbors n\n WHERE r.pos = n.i AND s.d = substr(r.str, n.j, 1)\n )\n )\nSELECT str\nFROM r\nWHERE pos = 0\n;", "input": ""}, {"instruction": "Task\n\nTake the string \u00a0 \u00a0 alphaBETA \u00a0 \u00a0 and demonstrate how to convert it to:\n\n \u00a0 upper-case \u00a0 \u00a0 and \n \u00a0 lower-case\n\n\nUse the default encoding of a string literal or plain ASCII if there is no string literal in your language.\n\nNote: In some languages alphabets toLower and toUpper is not reversable.\n\nShow any additional case conversion functions \u00a0 (e.g. swapping case, capitalizing the first letter, etc.) \u00a0 that may be included in the library of your language.\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 \u00a0(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 \u00a0(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", "output": "DECLARE\n vc VARCHAR2(40) := 'alphaBETA';\n ivc VARCHAR2(40);\n lvc VARCHAR2(40);\n uvc VARCHAR2(40);\nBEGIN\n ivc := INITCAP(vc); -- 'Alphabeta'\n lvc := LOWER(vc); -- 'alphabeta'\n uvc := UPPER(vc); -- 'ALPHABETA'\nEND; ", "input": ""}, {"instruction": "Task\n\nFind the character and byte length of a string.\n\nThis means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.\n\nBy character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.\n\nFor example, the character length of \"m\u00f8\u00f8se\" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16.\n\nNon-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts.\n\nTherefore a string like \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16.\n\nPlease mark your examples with ===Character Length=== or ===Byte Length===.\n\nIf your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===.\n\nFor example, the string \"J\u0332o\u0332s\u0332\u00e9\u0332\" (\"J\\x{332}o\\x{332}s\\x{332}e\\x{301}\\x{332}\") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8.\n\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 \u00a0(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 \u00a0(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", "output": "DECLARE\n string VARCHAR2(50) := 'Hello, world!';\n stringlength NUMBER;\nBEGIN\n stringlength := LENGTHB(string);\nEND;", "input": ""}, {"instruction": "Task\n\nTake the string \u00a0 \u00a0 alphaBETA \u00a0 \u00a0 and demonstrate how to convert it to:\n\n \u00a0 upper-case \u00a0 \u00a0 and \n \u00a0 lower-case\n\n\nUse the default encoding of a string literal or plain ASCII if there is no string literal in your language.\n\nNote: In some languages alphabets toLower and toUpper is not reversable.\n\nShow any additional case conversion functions \u00a0 (e.g. swapping case, capitalizing the first letter, etc.) \u00a0 that may be included in the library of your language.\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 \u00a0(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 \u00a0(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", "output": "DECLARE @s VARCHAR(10)\nSET @s = 'alphaBETA'\nprint UPPER(@s)\nprint LOWER(@s)", "input": ""}, {"instruction": "Task\n\nTake the string \u00a0 \u00a0 alphaBETA \u00a0 \u00a0 and demonstrate how to convert it to:\n\n \u00a0 upper-case \u00a0 \u00a0 and \n \u00a0 lower-case\n\n\nUse the default encoding of a string literal or plain ASCII if there is no string literal in your language.\n\nNote: In some languages alphabets toLower and toUpper is not reversable.\n\nShow any additional case conversion functions \u00a0 (e.g. swapping case, capitalizing the first letter, etc.) \u00a0 that may be included in the library of your language.\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 \u00a0(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 \u00a0(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", "output": "\u00a0\nVALUES UPPER('alphaBETA');\nVALUES LOWER('alphaBETA');\nVALUES initcap('alphaBETA');\n-- Within a SQL query.\nSELECT UPPER('alphaBETA') FROM sysibm.sysdummy1;\n\u00a0", "input": ""}, {"instruction": "Compute the \u00a0 nth \u00a0 term of a series, \u00a0 i.e. the sum of the \u00a0 n \u00a0 first terms of the corresponding sequence.\n\nInformally this value, or its limit when \u00a0 n \u00a0 tends to infinity, is also called the sum of the series, thus the title of this task.\n\nFor this task, use:\n\n \n\n\n\n\nS\n\nn\n\n\n=\n\n\u2211\n\nk\n=\n1\n\n\nn\n\n\n\n\n1\n\nk\n\n2\n\n\n\n\n\n\n{\\displaystyle S_{n}=\\sum _{k=1}^{n}{\\frac {1}{k^{2}}}}\n\n\n\n\n and compute \u00a0 \n\n\n\n\nS\n\n1000\n\n\n\n\n{\\displaystyle S_{1000}}\n\n\n\n\nThis approximates the \u00a0 zeta function \u00a0 for \u00a0 S=2, \u00a0 whose exact value\n\n \n\n\n\n\u03b6\n(\n2\n)\n=\n\n\n\n\u03c0\n\n2\n\n\n6\n\n\n\n\n{\\displaystyle \\zeta (2)={\\pi ^{2} \\over 6}}\n\n\nis the solution of the Basel problem.\n\n\n\n", "output": "CREATE TABLE t1 (n REAL);\n-- this is postgresql specific, fill the table\nINSERT INTO t1 (SELECT generate_series(1,1000)::REAL);\nWITH tt AS (\n SELECT 1/(n*n) AS recip FROM t1\n) SELECT SUM(recip) FROM tt; \n\u00a0", "input": ""}, {"instruction": "\nBasic Data Operation\n\nThis is a basic data operation. It represents a fundamental action on a basic data type.\nYou may see other such operations in the Basic Data Operations category, or:\n\n\nInteger Operations\nArithmetic |\nComparison\nBoolean Operations\nBitwise |\nLogical\nString Operations\nConcatenation |\nInterpolation |\nComparison |\nMatching\nMemory Operations\nPointers & references |\nAddresses\n\n\n\n\nTask\n\nDisplay a substring:\n\n \u00a0 starting from \u00a0 n \u00a0 characters in and of \u00a0 m \u00a0 length;\n \u00a0 starting from \u00a0 n \u00a0 characters in, \u00a0 up to the end of the string;\n \u00a0 whole string minus the last character;\n \u00a0 starting from a known \u00a0 character \u00a0 within the string and of \u00a0 m \u00a0 length;\n \u00a0 starting from a known \u00a0 substring \u00a0 within the string and of \u00a0 m \u00a0 length.\n\n\nIf the program uses UTF-8 or UTF-16, \u00a0 it must work on any valid Unicode code point,\nwhether in the \u00a0 Basic Multilingual Plane \u00a0 or above it.\n\nThe program must reference logical characters (code points), \u00a0 not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "\u00a0\nSELECT 'the quick brown fox jumps over the lazy dog' FROM sysibm.sysdummy1;\nSELECT substr('the quick brown fox jumps over the lazy dog', 5, 15) FROM sysibm.sysdummy1;\nSELECT substr('the quick brown fox jumps over the lazy dog', 32) FROM sysibm.sysdummy1;\nSELECT substr('the quick brown fox jumps over the lazy dog', 1, LENGTH ('the quick brown fox jumps over the lazy dog') - 1) FROM sysibm.sysdummy1;\n\u00a0\nSELECT locate('j', 'the quick brown fox jumps over the lazy dog') FROM sysibm.sysdummy1;\nSELECT locate_in_string('the quick brown fox jumps over the lazy dog', 'j') FROM sysibm.sysdummy1;\nSELECT posstr('the quick brown fox jumps over the lazy dog', 'j') FROM sysibm.sysdummy1;\nSELECT POSITION('j', 'the quick brown fox jumps over the lazy dog', OCTETS) FROM sysibm.sysdummy1;\n\u00a0\nSELECT substr('the quick brown fox jumps over the lazy dog', locate('j', 'the quick brown fox jumps over the lazy dog')) FROM sysibm.sysdummy1;\n\u00a0\nSELECT locate('fox', 'the quick brown fox jumps over the lazy dog') FROM sysibm.sysdummy1;\nSELECT locate_in_string('the quick brown fox jumps over the lazy dog', 'fox') FROM sysibm.sysdummy1;\nSELECT posstr('the quick brown fox jumps over the lazy dog', 'fox') FROM sysibm.sysdummy1;\nSELECT POSITION('fox', 'the quick brown fox jumps over the lazy dog', OCTETS) FROM sysibm.sysdummy1;\n\u00a0\nSELECT substr('the quick brown fox jumps over the lazy dog', locate('fox', 'the quick brown fox jumps over the lazy dog')) FROM sysibm.sysdummy1;\n\u00a0", "input": ""}, {"instruction": "Task\n\nFind the character and byte length of a string.\n\nThis means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.\n\nBy character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.\n\nFor example, the character length of \"m\u00f8\u00f8se\" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16.\n\nNon-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts.\n\nTherefore a string like \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16.\n\nPlease mark your examples with ===Character Length=== or ===Byte Length===.\n\nIf your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===.\n\nFor example, the string \"J\u0332o\u0332s\u0332\u00e9\u0332\" (\"J\\x{332}o\\x{332}s\\x{332}e\\x{301}\\x{332}\") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8.\n\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 \u00a0(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 \u00a0(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", "output": "\u00a0\nVALUES LENGTH('m\u00f8\u00f8se', CODEUNITS16);\nVALUES LENGTH('m\u00f8\u00f8se', CODEUNITS32);\nVALUES CHARACTER_LENGTH('m\u00f8\u00f8se', CODEUNITS32);\nVALUES LENGTH2('m\u00f8\u00f8se');\nVALUES LENGTH4('m\u00f8\u00f8se');\nVALUES LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS16);\nVALUES LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS32);\nVALUES CHARACTER_LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS32);\nVALUES LENGTH2('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22');\nVALUES LENGTH4('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22');\nVALUES LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS16);\nVALUES LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS32);\nVALUES CHARACTER_LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS32);\nVALUES LENGTH2('J\u0332o\u0332s\u0332\u00e9\u0332');\nVALUES LENGTH4('J\u0332o\u0332s\u0332\u00e9\u0332');\n\u00a0", "input": ""}, {"instruction": "Task\n\nFind the character and byte length of a string.\n\nThis means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.\n\nBy character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters.\n\nFor example, the character length of \"m\u00f8\u00f8se\" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16.\n\nNon-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts.\n\nTherefore a string like \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16.\n\nPlease mark your examples with ===Character Length=== or ===Byte Length===.\n\nIf your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===.\n\nFor example, the string \"J\u0332o\u0332s\u0332\u00e9\u0332\" (\"J\\x{332}o\\x{332}s\\x{332}e\\x{301}\\x{332}\") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8.\n\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 \u00a0(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 \u00a0(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", "output": "\u00a0\nVALUES LENGTH('m\u00f8\u00f8se', CODEUNITS16);\nVALUES LENGTH('m\u00f8\u00f8se', CODEUNITS32);\nVALUES CHARACTER_LENGTH('m\u00f8\u00f8se', CODEUNITS32);\nVALUES LENGTH2('m\u00f8\u00f8se');\nVALUES LENGTH4('m\u00f8\u00f8se');\nVALUES LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS16);\nVALUES LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS32);\nVALUES CHARACTER_LENGTH('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', CODEUNITS32);\nVALUES LENGTH2('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22');\nVALUES LENGTH4('\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22');\nVALUES LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS16);\nVALUES LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS32);\nVALUES CHARACTER_LENGTH('J\u0332o\u0332s\u0332\u00e9\u0332', CODEUNITS32);\nVALUES LENGTH2('J\u0332o\u0332s\u0332\u00e9\u0332');\nVALUES LENGTH4('J\u0332o\u0332s\u0332\u00e9\u0332');\n\u00a0", "input": ""}, {"instruction": "Special characters are symbols (single characters or sequences of characters) that have a \"special\" built-in meaning in the language and typically cannot be used in identifiers.\n\nEscape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.\n\n\n\nTask\n\nList the special characters and show escape sequences in the language.\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 \u00a0(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 \u00a0(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", "output": "' ' String literal\n\" \" Identifier\n[ ] Identifier\n` ` Identifier\n? Numbered host parameter\n: Named host parameter\n$ Named host parameter\n@ Named host parameter\n( ) Parentheses\n+ Add\n- Subtract/negative\n* Multiply\n/ Divide\n% Modulo\n& Bitwise AND\n| Bitwise OR\n~ Bitwise NOT\n<< Left shift\n>> Right shift\n= Equal\n== Equal\n<> Not equal\n!= Not equal\n< Less\n> Greater\n<= Less or equal\n>= Greater or equal\n|| String concatenation\n", "input": ""}, {"instruction": "\nSorting Algorithm\n\nThis is a sorting algorithm. \u00a0 It may be applied to a set of data in order to sort it. \u00a0 \u00a0\nFor comparing various sorts, see compare sorts. \u00a0\nFor other sorting algorithms, \u00a0 see sorting\u00a0algorithms, \u00a0 or:\n\nO(n logn) sorts\nHeap\u00a0sort |\nMerge\u00a0sort |\nPatience\u00a0sort |\nQuick\u00a0sort\nO(n log2n) sorts\nShell\u00a0Sort\nO(n2) sorts\nBubble\u00a0sort |\nCocktail\u00a0sort |\nCocktail\u00a0sort\u00a0with\u00a0shifting\u00a0bounds |\nComb\u00a0sort |\nCycle\u00a0sort |\nGnome\u00a0sort |\nInsertion\u00a0sort |\nSelection\u00a0sort |\nStrand\u00a0sort\nother sorts\nBead\u00a0sort |\nBogo\u00a0sort |\nCommon\u00a0sorted\u00a0list |\nComposite\u00a0structures\u00a0sort |\nCustom\u00a0comparator\u00a0sort |\nCounting\u00a0sort |\nDisjoint\u00a0sublist\u00a0sort |\nExternal\u00a0sort |\nJort\u00a0sort |\nLexicographical\u00a0sort |\nNatural\u00a0sorting |\nOrder\u00a0by\u00a0pair\u00a0comparisons |\nOrder\u00a0disjoint\u00a0list\u00a0items |\nOrder\u00a0two\u00a0numerical\u00a0lists |\nObject\u00a0identifier\u00a0(OID)\u00a0sort |\nPancake\u00a0sort |\nQuickselect |\nPermutation\u00a0sort |\nRadix\u00a0sort |\nRanking\u00a0methods |\nRemove\u00a0duplicate\u00a0elements |\nSleep\u00a0sort |\nStooge\u00a0sort |\n[Sort\u00a0letters\u00a0of\u00a0a\u00a0string] |\nThree\u00a0variable\u00a0sort |\nTopological\u00a0sort |\nTree\u00a0sort\n\n\nSort an array of composite structures by a key.\n\n\n\nFor example, if you define a composite structure that presents a name-value pair (in pseudo-code):\n\nDefine structure pair such that: \n name as a string\n value as a string\n\nand an array of such pairs:\n\n x: array of pairs\n\nthen define a sort routine that sorts the array x by the key name.\n\nThis task can always be accomplished with Sorting Using a Custom Comparator.\n\nIf your language is not listed here, please see the other article.\n\n\n\n", "output": "-- setup\nCREATE TABLE pairs (name VARCHAR(16), VALUE VARCHAR(16));\nINSERT INTO pairs VALUES ('Fluffy', 'cat');\nINSERT INTO pairs VALUES ('Fido', 'dog');\nINSERT INTO pairs VALUES ('Francis', 'fish');\n-- order them by name\nSELECT * FROM pairs ORDER BY name;", "input": ""}, {"instruction": "Task\n\nWrite a function to send an email.\n\nThe function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.\n\n If appropriate, explain what notifications of problems/success are given.\n Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.\n Note how portable the solution given is between operating systems when multi-OS languages are used.\n\n\n(Remember to obfuscate any sensitive data used in examples)\n\n\n\n", "output": "\u00a0\nUPDATE DB CFG FOR myDb USING SMTP_SERVER 'smtp.ibm.com';\n\u00a0\nCALL UTL_MAIL.SEND ('[email protected]','[email protected]', '[email protected]', NULL, 'The subject of the message', 'The content of the message');\n\u00a0", "input": ""}, {"instruction": "Task\n\nFor each number list of 6-digit SEDOLs, calculate and append the checksum digit.\n\n\n\nThat is, given this input:\n\n710889\nB0YBKJ\n406566\nB0YBLH\n228276\nB0YBKL\n557910\nB0YBKR\n585284\nB0YBKT\nB00030\n\nProduce this output:\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\nB000300\n\nExtra credit\n\nCheck each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.\n\n\n\nRelated tasks\n\n \u00a0 Luhn test\n \u00a0 ISIN\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON@\n\u00a0\nCREATE OR REPLACE FUNCTION CHECK_SEDOL (\n IN TEXT VARCHAR(6)\n ) RETURNS VARCHAR(7)\n BEGIN\n DECLARE TYPE SEDOL AS CHAR(1) ARRAY [6];\n--declare text varchar(6) default 'B12345';\n DECLARE WEIGHT SEDOL;\n DECLARE I SMALLINT;\n DECLARE SENTENCE VARCHAR(256);\n DECLARE CHAR_AT CHAR(1);\n DECLARE OUTPUT CHAR(1);\n DECLARE SUM SMALLINT;\n DECLARE CHECK SMALLINT;\n DECLARE INVALID_CHAR CONDITION FOR SQLSTATE '22004'\u00a0;\n DECLARE STMT STATEMENT;\n\u00a0\n -- Converts all to upper.\n SET TEXT = UPPER (TEXT);\n -- CALL DBMS_OUTPUT.PUT_LINE(TEXT);\n -- Checks the characters.\n SET I = 1;\n WHILE (I <= 6) DO\n SET CHAR_AT = SUBSTR(TEXT, I, 1);\n -- CALL DBMS_OUTPUT.PUT_LINE('Char ' || CHAR_AT);\n SET SENTENCE = 'SET\u00a0? = (SELECT SEDOL FROM (SELECT ''' || CHAR_AT\n || ''' SEDOL FROM SYSIBM.SYSDUMMY1) WHERE SEDOL IN (''B'',''C'',''D'',''F'',''G'',''H'',''J'','\n || '''K'',''L'',''M'',''N'',''P'',''Q'',''R'',''S'',''T'',''V'',''W'',''X'',''Y'',''Z'',''0'','\n || '''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9''))';\n PREPARE STMT FROM SENTENCE;\n EXECUTE STMT INTO OUTPUT;\n IF (OUTPUT IS NULL) THEN\n SIGNAL INVALID_CHAR;\n END IF;\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- Assigns weight\n SET WEIGHT[1] = '1';\n SET WEIGHT[2] = '3';\n SET WEIGHT[3] = '1';\n SET WEIGHT[4] = '7';\n SET WEIGHT[5] = '3';\n SET WEIGHT[6] = '9';\n\u00a0\n -- Process the SEDOL.\n SET SUM = 0;\n SET I = 1;\n WHILE (I <= 6) DO\n SET CHAR_AT = SUBSTR(TEXT, I, 1);\n IF (ASCII(CHAR_AT) > 65) THEN\n SET SUM = SUM + WEIGHT[I] * (ASCII(CHAR_AT) - 64 + 9);\n ELSE\n SET SUM = SUM + WEIGHT[I] * CHAR_AT;\n END IF;\n SET I = I + 1;\n END WHILE;\n SET CHECK = MOD((10 - MOD(SUM, 10)), 10);\n CALL DBMS_OUTPUT.PUT_LINE(CHECK);\n RETURN TEXT || CHECK;\n END @\n\u00a0", "input": ""}, {"instruction": "Task\n\nFor each number list of 6-digit SEDOLs, calculate and append the checksum digit.\n\n\n\nThat is, given this input:\n\n710889\nB0YBKJ\n406566\nB0YBLH\n228276\nB0YBKL\n557910\nB0YBKR\n585284\nB0YBKT\nB00030\n\nProduce this output:\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\nB000300\n\nExtra credit\n\nCheck each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.\n\n\n\nRelated tasks\n\n \u00a0 Luhn test\n \u00a0 ISIN\n\n", "output": "CREATE FUNCTION [dbo].[fn_CheckSEDOL]\n( @SEDOL varchar(50) )\nRETURNS varchar(7)\nAS\nBEGIN\n\tdeclare\t@true bit = 1,\n\t\t@false bit = 0,\n\t\t@isSEDOL bit,\t\t\n\t\t@sedol_weights varchar(6) ='131739',\n\t\t@sedol_len int = LEN(@SEDOL),\n\t\t@sum int = 0\n\u00a0\n\u00a0\n\tif ((@sedol_len = 6)) \n\tbegin\n\t\tselect @SEDOL = UPPER(@SEDOL)\n\t\tDeclare\t@vowels varchar(5) = 'AEIOU', \n\t\t\t@letters varchar(21) = 'BCDFGHJKLMNPQRSTVWXYZ',\n\t\t\t@i int=1,\n\t\t\t@isStillGood bit = @true,\t\t\t\t\t\n\t\t\t@char char = '',\n\t\t\t@weighting int =0\n\u00a0\n\t\tselect @isSEDOL = @false\n\u00a0\n\t\twhile ((@i < 7) and (@isStillGood = @true))\n\t\tbegin\n\t\t\tselect\t@char = SUBSTRING(@SEDOL,@i,1), \n\t\t\t\t@weighting = CONVERT (INT,SUBSTRING(@sedol_weights, @i, 1))\n\t\t\tif (CHARINDEX(@char, @vowels) > 0) -- no vowels please\n\t\t\tbegin\n\t\t\t\tselect @isStillGood=@false\n\t\t\tend\n\t\t\telse\n\t\t\tbegin\n\t\t\t\tif (ISNUMERIC(@char) = @true) -- is a number\n\t\t\t\tbegin\n\t\t\t\t\tselect @sum = @sum + (ASCII(@char) - 48) * @weighting\n\t\t\t\tend\n\t\t\t\telse if (CHARINDEX(@char, @letters) = 0) -- test for the rest of the alphabet\n\t\t\t\tbegin\n\t\t\t\t\tselect @isStillGood=@false\n\t\t\t\tend\n\t\t\t\telse\n\t\t\t\tbegin\n\t\t\t\t\tselect @sum = @sum + (ASCII(@char) - 55) * @weighting\n\t\t\t\tend\n\t\t\tend \n\t\t\tselect @i = @i +1 \n\t\tend -- of while loop\n\t\tif (@isStillGood = @true) \n\t\tbegin\n\t\t\tdeclare @checksum int = (10 - (@sum%10))%10 \n\t\t\tselect @SEDOL = @SEDOL + CONVERT(CHAR,@checksum)\n\t\tend\n\tend\n\telse\n\tbegin\n\t\tselect @SEDOL = ''\n\tend \n\t-- Return the result of the function\n\tRETURN @SEDOL\nEND", "input": ""}, {"instruction": "\nData Structure\n\nThis illustrates a data structure, a means of storing data within a program.\n\nYou may see other such structures in the Data Structures category.\nA \u00a0 set \u00a0is a collection of elements, without duplicates and without order.\n\n\n\nTask\n\nShow each of these set operations:\n\n Set creation\n Test m \u2208 S -- \"m is an element in set S\"\n A \u222a B -- union; a set of all elements either in set A or in set B.\n A \u2229 B -- intersection; a set of all elements in both set A and set B.\n A \u2216 B -- difference; a set of all elements in set A, except those in set B.\n A \u2286 B -- subset; true if every element in set A is also in set B.\n A = B -- equality; true if every element of set A is in set B and vice versa.\n\n\nAs an option, show some other set operations.\n\n(If A \u2286 B, but A \u2260 B, then A is called a true or proper subset of B, written A \u2282 B or A \u228a B.)\n\nAs another option, show how to modify a mutable set.\n\n\n\nOne might implement a set using an associative array (with set elements as array keys and some dummy value as the values).\n\nOne might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).\n\nThe basic test, m \u2208 S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.\n\n\n\nSee also\n\n Array\n Associative array: Creation, Iteration\n Collections\n Compound data type\n Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n Linked list\n Queue: Definition, Usage\n Set\n Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n Stack\n\n", "output": "\u00a0\n-- set of numbers is a table\n-- create one set with 3 elements\n\u00a0\nCREATE TABLE myset1 (element NUMBER);\n\u00a0\nINSERT INTO myset1 VALUES (1);\nINSERT INTO myset1 VALUES (2);\nINSERT INTO myset1 VALUES (3);\n\u00a0\ncommit;\n\u00a0\n-- check if 1 is an element\n\u00a0\nSELECT 'TRUE' BOOL FROM dual\nWHERE 1 IN \n(SELECT element FROM myset1);\n\u00a0\n-- create second set with 3 elements\n\u00a0\nCREATE TABLE myset2 (element NUMBER);\n\u00a0\nINSERT INTO myset2 VALUES (1);\nINSERT INTO myset2 VALUES (5);\nINSERT INTO myset2 VALUES (6);\n\u00a0\ncommit;\n\u00a0\n-- union sets\n\u00a0\nSELECT element FROM myset1\nUNION\nSELECT element FROM myset2;\n\u00a0\n-- intersection\n\u00a0\nSELECT element FROM myset1\nINTERSECT\nSELECT element FROM myset2;\n\u00a0\n-- difference\n\u00a0\nSELECT element FROM myset1\nminus\nSELECT element FROM myset2;\n\u00a0\n-- subset\n\u00a0\n-- change myset2 to only have 1 as element\n\u00a0\nDELETE FROM myset2 WHERE NOT element = 1;\n\u00a0\ncommit;\n\u00a0\n-- check if myset2 subset of myset1\n\u00a0\nSELECT 'TRUE' BOOL FROM dual\nWHERE 0 = (SELECT COUNT(*) FROM \n(SELECT element FROM myset2\nminus\nSELECT element FROM myset1));\n\u00a0\n-- equality\n\u00a0\n-- change myset1 to only have 1 as element\n\u00a0\nDELETE FROM myset1 WHERE NOT element = 1;\n\u00a0\ncommit;\n\u00a0\n -- check if myset2 subset of myset1 and\n -- check if myset1 subset of myset2 and\n\u00a0\nSELECT 'TRUE' BOOL FROM dual\nWHERE \n0 = (SELECT COUNT(*) FROM \n(SELECT element FROM myset2\nminus\nSELECT element FROM myset1)) AND\n0 =\n(SELECT COUNT(*) FROM \n(SELECT element FROM myset1\nminus\nSELECT element FROM myset2));\n\u00a0", "input": ""}, {"instruction": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\n\nThe Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.\n\n\n\nTask\n\nImplement the \u00a0 Sieve of Eratosthenes \u00a0 algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.\n\nThat means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.\n\nIf there's an easy way to add such a wheel based optimization, implement it as an alternative version.\n\n\n\nNote\n\n It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.\n\n\nRelated tasks\n\n \u00a0 Emirp primes\n \u00a0 count in factors\n \u00a0 prime decomposition\n \u00a0 factors of an integer\n \u00a0 extensible prime generator\n \u00a0 primality by trial division\n \u00a0 factors of a Mersenne number\n \u00a0 trial factoring of a Mersenne number\n \u00a0 partition an integer X into N primes\n \u00a0 sequence of primes by Trial Division\n\n", "output": "CREATE OR REPLACE PACKAGE sieve_of_eratosthenes AS\n TYPE array_of_booleans IS varray(100000000) OF BOOLEAN;\n TYPE table_of_integers IS TABLE OF INTEGER;\n FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined;\nEND sieve_of_eratosthenes;\n/\n\u00a0\nCREATE OR REPLACE PACKAGE BODY sieve_of_eratosthenes AS\n FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined IS\n flag array_of_booleans;\n ptr INTEGER;\n i INTEGER;\n BEGIN\n flag := array_of_booleans(FALSE, TRUE);\n flag.extend(n - 2, 2);\n ptr := 1;\n << outer_loop >>\n WHILE ptr * ptr <= n LOOP\n WHILE NOT flag(ptr) LOOP\n ptr := ptr + 1;\n END LOOP;\n i := ptr * ptr;\n WHILE i <= n LOOP\n flag(i) := FALSE;\n i := i + ptr;\n END LOOP;\n ptr := ptr + 1;\n END LOOP outer_loop;\n FOR i IN 1 .. n LOOP\n IF flag(i) THEN\n pipe ROW (i);\n END IF;\n END LOOP;\n RETURN;\n END find_primes;\nEND sieve_of_eratosthenes;\n/", "input": ""}, {"instruction": "Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.\n\nBut what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?\n\nTask[edit]\nWrite a function/method/etc. that can find the first element in a given list matching a given condition.\n\nIt should be as generic and reusable as possible.\n\n(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)\n\nThen to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.\n\nData set\nThe data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:\n\n[\n { \"name\": \"Lagos\", \"population\": 21.0 },\n { \"name\": \"Cairo\", \"population\": 15.2 },\n { \"name\": \"Kinshasa-Brazzaville\", \"population\": 11.3 },\n { \"name\": \"Greater Johannesburg\", \"population\": 7.55 },\n { \"name\": \"Mogadishu\", \"population\": 5.85 },\n { \"name\": \"Khartoum-Omdurman\", \"population\": 4.98 },\n { \"name\": \"Dar Es Salaam\", \"population\": 4.7 },\n { \"name\": \"Alexandria\", \"population\": 4.58 },\n { \"name\": \"Abidjan\", \"population\": 4.4 },\n { \"name\": \"Casablanca\", \"population\": 3.98 }\n]\nHowever, you shouldn't parse it from JSON, but rather represent it natively in your programming language.\n\n The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).\n Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).\n Each of them has two entries: One string value with key \"name\", and one numeric value with key \"population\".\n You may rely on the list being sorted by population count, as long as you explain this to readers.\n\n\nIf any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.\n\nTest cases\n\n\n Search\n\n Expected result\n\n\n Find the (zero-based) index of the first city in the list whose name is \"Dar Es Salaam\"\n\n 6\n\n\n Find the name of the first city in this list whose population is less than 5 million\n\n Khartoum-Omdurman\n\n\n Find the population of the first city in this list whose name starts with the letter \"A\"\n\n 4.58\n\nGuidance\nIf your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called \"find_index\" or similar), that takes two arguments:\n\n The list to search through.\n A function/lambda/closure (the so-called \"predicate\"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.\nIf this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.\n\nRelated tasks\n Search a list\n", "output": "\u00a0\nCREATE TABLE african_capitals(name varchar2(100), population_in_millions NUMBER(3,2));\n\u00a0", "input": ""}, {"instruction": "Run-length encoding\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n\n\nTask\n\nGiven a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.\n\nThe output can be anything, as long as you can recreate the input with it.\n\n\n\nExample\n\n Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n Output: 12W1B12W3B24W1B14W\n\n\nNote: the encoding step in the above example is the same as a step of the Look-and-say sequence.\n\n\n\n", "output": "\u00a0\n-- variable table\nDROP TABLE IF EXISTS var;\nCREATE temp TABLE var (\tVALUE VARCHAR(1000) );\nINSERT INTO var(VALUE) SELECT 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';\n\u00a0\n-- select\nWITH recursive\nints(num) AS \n(\n\tSELECT 1\n\tUNION ALL\n\tSELECT num+1\n\tFROM ints\n\tWHERE num+1 <= LENGTH((SELECT VALUE FROM var))\n)\n,\nchars(num,chr,nextChr,isGroupEnd) AS\n(\n\tSELECT tmp.*, CASE WHEN tmp.nextChr <> tmp.chr THEN 1 ELSE 0 END groupEnds\n\tFROM (\n\tSELECT num, \n\t\t SUBSTRING((SELECT VALUE FROM var), num, 1) chr,\n\t\t (SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr\n\tFROM ints\n\t) tmp\n)\nSELECT (SELECT VALUE FROM var) plain_text, (\n\tSELECT string_agg(concat(CAST(maxNoWithinGroup AS VARCHAR(10)) , chr), '' ORDER BY num)\n\tFROM (\n\t\tSELECT *, MAX(noWithinGroup) OVER (partition BY chr, groupNo) maxNoWithinGroup\n\t\tFROM (\n\t\t\tSELECT\tnum, \n\t\t\t\t\tchr, \n\t\t\t\t\tgroupNo, \n\t\t\t\t\tROW_NUMBER() OVER( partition BY chr, groupNo ORDER BY num) noWithinGroup\n\t\t\tFROM (\n\t\t\tSELECT *, (SELECT COUNT(*) \n\t\t\t\t\t FROM chars chars2 \n\t\t\t\t\t WHERE chars2.isGroupEnd = 1 AND \n\t\t\t\t\t chars2.chr = chars.chr AND \n\t\t\t\t\t chars2.num < chars.num) groupNo \n\t\t\tFROM chars\n\t\t\t) tmp\n\t\t) sub\n\t) final\n\tWHERE noWithinGroup = 1\n\t) Rle_Compressed\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.\n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,\n\nstarting with the leftmost decimal digit and skipping any 0s \u00a0 (zeroes).\n\n1990 is rendered as \u00a0 MCMXC \u00a0 \u00a0 (1000 = M, \u00a0 900 = CM, \u00a0 90 = XC) \u00a0 \u00a0 and\n\n2008 is rendered as \u00a0 MMVIII \u00a0 \u00a0 \u00a0 (2000 = MM, \u00a0 8 = VIII).\n\nThe Roman numeral for 1666, \u00a0 MDCLXVI, \u00a0 uses each letter in descending order.\n\n\n\n", "output": "\u00a0\n/*****************************************************************\n * $Author: Atanas Kebedjiev $\n *****************************************************************\n * PL/SQL code can be run as anonymous block.\n * To test, execute the whole script or create the functions and then e.g. 'select rdecode('2012') from dual;\n * Please note that task definition does not describe fully some current rules, such as\n * * subtraction - IX XC CM are the valid subtraction combinations\n * * A subtraction character cannot be repeated: 8 is expressed as VIII and not as IIX\n * * V L and D cannot be used for subtraction\n * * Any numeral cannot be repeated more than 3 times: 1910 should be MCMX and not MDCCCCX\n * Code below does not validate the Roman numeral itself and will return a result even for a non-compliant number\n * E.g. both MCMXCIX and IMM will return 1999 but the first one is the correct notation\n */\n\u00a0\nDECLARE\n\u00a0\nFUNCTION rvalue(c IN CHAR) RETURN NUMBER IS\n i INTEGER;\nBEGIN\n i\u00a0:= 0;\n CASE (c)\n when 'M' THEN i\u00a0:= 1000;\n when 'D' THEN i\u00a0:= 500;\n when 'C' THEN i\u00a0:= 100;\n when 'L' THEN i\u00a0:= 50;\n when 'X' THEN i\u00a0:= 10;\n when 'V' THEN i\u00a0:= 5;\n when 'I' THEN i\u00a0:= 1;\n END CASE;\n RETURN i;\nEND;\n\u00a0\n\u00a0\nFUNCTION decode(rn IN VARCHAR2) RETURN NUMBER IS\n i INTEGER;\n l INTEGER;\n cr CHAR; -- current Roman numeral as substring from r\n cv INTEGER; -- value of current Roman numeral\n\u00a0\n gr CHAR; -- next Roman numeral\n gv NUMBER; -- value of the next numeral;\n\u00a0\n dv NUMBER; -- decimal value to return\nBEGIN\n l\u00a0:= length(rn);\n i\u00a0:= 1;\n dv\u00a0:= 0;\n while (i <= l)\n LOOP\n cr\u00a0:= substr(rn,i,1);\n cv\u00a0:= rvalue(cr);\n\u00a0\n /* Look for a larger numeral in next position, like IV or CM \n The number to subtract should be at least 1/10th of the bigger number\n CM and XC are valid, but IC and XM are not */\n IF (i < l) THEN\n gr\u00a0:= substr(rn,i+1,1);\n gv\u00a0:= rvalue(gr);\n IF (cv < gv ) THEN\n dv\u00a0:= dv - cv;\n ELSE\n dv\u00a0:= dv + cv;\n END IF;\n ELSE\n dv\u00a0:= dv + cv;\n END IF; -- need to add the last value unconditionally\n\u00a0\n i\u00a0:= i + 1;\n END LOOP;\n\u00a0\nRETURN dv;\n\u00a0\nEND;\n\u00a0\nBEGIN\n\u00a0\n DBMS_OUTPUT.PUT_LINE ('MMXII = ' || rdecode('MMXII')); -- 2012\n DBMS_OUTPUT.PUT_LINE ('MCMLI = ' || rdecode('MCMLI')); -- 1951\n DBMS_OUTPUT.PUT_LINE ('MCMLXXXVII = ' || rdecode('MCMLXXXVII')); -- 1987\n DBMS_OUTPUT.PUT_LINE ('MDCLXVI = ' || rdecode('MDCLXVI')); -- 1666\n DBMS_OUTPUT.PUT_LINE ('MCMXCIX = ' || rdecode('MCMXCIX')); -- 1999\n\u00a0\nEND;\n\u00a0", "input": ""}, {"instruction": "\n\nTask\n\nImplement a \u00a0 rot-13 \u00a0 function \u00a0 (or procedure, class, subroutine, or other \"callable\" object as appropriate to your programming environment).\n\nOptionally wrap this function in a utility program \u00a0 (like tr, \u00a0 which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, \u00a0 or (if no filenames are passed thereon) acting as a filter on its \u00a0 \"standard input.\"\n\n\n\n(A number of UNIX scripting languages and utilities, such as \u00a0 awk \u00a0 and \u00a0 sed \u00a0 either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., \u00a0 Perl \u00a0 and \u00a0 Python).\n\nThe \u00a0 rot-13 \u00a0 encoding is commonly known from the early days of Usenet \"Netnews\" as a way of obfuscating text to prevent casual reading of \u00a0 spoiler \u00a0 or potentially offensive material.\n\nMany news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.\n\nThe definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters \"around\" the 26 letter alphabet from its normal cardinal position \u00a0 (wrapping around from \u00a0 z \u00a0 to \u00a0 a \u00a0 as necessary).\n\nThus the letters \u00a0 abc \u00a0 become \u00a0 nop \u00a0 and so on.\n\nTechnically rot-13 is a \u00a0 \"mono-alphabetic substitution cipher\" \u00a0 with a trivial \u00a0 \"key\".\n\nA proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters\nin the input stream through without alteration.\n\n\n\nRelated tasks\n\n \u00a0 Caesar cipher\n \u00a0 Substitution Cipher\n \u00a0 Vigen\u00e8re Cipher/Cryptanalysis\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "-- Works for VARCHAR2 (up to 32k chars)\nCREATE OR REPLACE FUNCTION fn_rot13_native(p_text VARCHAR2) RETURN VARCHAR2 IS\n c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';\nBEGIN\n RETURN TRANSLATE(p_text, c_source, c_target);\nEND;\n/\n\u00a0\n-- For CLOBs (translate only works with VARCHAR2, so do it in chunks)\nCREATE OR REPLACE FUNCTION fn_rot13_clob(p_text CLOB) RETURN CLOB IS\n c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';\n c_chunk_size CONSTANT PLS_INTEGER := 4000;\n v_result CLOB := NULL;\nBEGIN\n FOR i IN 0..TRUNC(LENGTH(p_text) / c_chunk_size) LOOP\n v_result := v_result || \n TRANSLATE(DBMS_LOB.SUBSTR(p_text, c_chunk_size, i * c_chunk_size + 1), c_source, c_target);\n END LOOP;\n RETURN v_result;\nEND;\n/\n\u00a0\n-- The full algorithm (Slower. And MUCH slower if using CLOB!)\nCREATE OR REPLACE FUNCTION fn_rot13_algorithm(p_text VARCHAR2) RETURN CLOB IS\n c_upper_a CONSTANT PLS_INTEGER := ASCII('A');\n c_lower_a CONSTANT PLS_INTEGER := ASCII('a');\n v_rot VARCHAR2(32000);\n v_char VARCHAR2(1);\nBEGIN\n FOR i IN 1..LENGTH(p_text) LOOP\n v_char := SUBSTR(p_text, i, 1);\n IF v_char BETWEEN 'A' AND 'Z' THEN\n v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_upper_a + 13, 26) + c_upper_a);\n ELSIF v_char BETWEEN 'a' AND 'z' THEN\n v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_lower_a + 13, 26) + c_lower_a);\n ELSE\n v_rot := v_rot || v_char;\n END IF;\n END LOOP;\n RETURN v_rot;\nEND;\n/\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.\n\n\n\nIn Roman numerals:\n\n 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n 2008 is written as 2000=MM, 8=VIII; or MMVIII\n 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "output": "\u00a0\n\u00a0\n/*****************************************************************\n * $Author: Atanas Kebedjiev $\n *****************************************************************\n * Encoding an Arabic numeral to a Roman in the range 1..3999 is much simpler as Oracle provides the conversion formats.\n * Please see also the SQL solution for the same task.\n */\n\u00a0\nCREATE OR REPLACE\nFUNCTION rencode(an IN NUMBER) \n RETURN VARCHAR2 \nIS\nBEGIN\n RETURN to_char(an, 'RN');\nEND rencode;\n\u00a0\nBEGIN\n\u00a0\n DBMS_OUTPUT.PUT_LINE ('2012 = ' || rencode('2012')); -- MMXII\n DBMS_OUTPUT.PUT_LINE ('1951 = ' || rencode('1951')); -- MCMLI\n DBMS_OUTPUT.PUT_LINE ('1987 = ' || rencode('1987')); -- MCMLXXXVII\n DBMS_OUTPUT.PUT_LINE ('1666 = ' || rencode('1666')); -- MDCLXVI\n DBMS_OUTPUT.PUT_LINE ('1999 = ' || rencode('1999')); -- MCMXCIX\n\u00a0\nEND;\n\u00a0", "input": ""}, {"instruction": "\n\nTask\n\nImplement a \u00a0 rot-13 \u00a0 function \u00a0 (or procedure, class, subroutine, or other \"callable\" object as appropriate to your programming environment).\n\nOptionally wrap this function in a utility program \u00a0 (like tr, \u00a0 which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line, \u00a0 or (if no filenames are passed thereon) acting as a filter on its \u00a0 \"standard input.\"\n\n\n\n(A number of UNIX scripting languages and utilities, such as \u00a0 awk \u00a0 and \u00a0 sed \u00a0 either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., \u00a0 Perl \u00a0 and \u00a0 Python).\n\nThe \u00a0 rot-13 \u00a0 encoding is commonly known from the early days of Usenet \"Netnews\" as a way of obfuscating text to prevent casual reading of \u00a0 spoiler \u00a0 or potentially offensive material.\n\nMany news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.\n\nThe definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters \"around\" the 26 letter alphabet from its normal cardinal position \u00a0 (wrapping around from \u00a0 z \u00a0 to \u00a0 a \u00a0 as necessary).\n\nThus the letters \u00a0 abc \u00a0 become \u00a0 nop \u00a0 and so on.\n\nTechnically rot-13 is a \u00a0 \"mono-alphabetic substitution cipher\" \u00a0 with a trivial \u00a0 \"key\".\n\nA proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters\nin the input stream through without alteration.\n\n\n\nRelated tasks\n\n \u00a0 Caesar cipher\n \u00a0 Substitution Cipher\n \u00a0 Vigen\u00e8re Cipher/Cryptanalysis\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "\u00a0\nSELECT translate(\n 'The quick brown fox jumps over the lazy dog.',\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'\n )\n FROM dual;\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.\n\n\n\nIn Roman numerals:\n\n 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n 2008 is written as 2000=MM, 8=VIII; or MMVIII\n 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "output": "\u00a0\n-- \n-- This only works under Oracle and has the limitation of 1 to 3999\n\u00a0\n\u00a0\nSQL> SELECT to_char(1666, 'RN') urcoman, to_char(1666, 'rn') lcroman FROM dual;\n\u00a0\nURCOMAN LCROMAN\n--------------- ---------------\n MDCLXVI mdclxvi\n\u00a0", "input": ""}, {"instruction": "Take a string and repeat it some number of times.\n\nExample: repeat(\"ha\", 5) \u00a0 => \u00a0 \"hahahahaha\"\n\nIf there is a simpler/more efficient way to repeat a single \u201ccharacter\u201d (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char(\"*\", 5) => \"*****\").\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 \u00a0(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 \u00a0(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", "output": "SELECT rpad('', 10, 'ha')", "input": ""}, {"instruction": "Take a string and repeat it some number of times.\n\nExample: repeat(\"ha\", 5) \u00a0 => \u00a0 \"hahahahaha\"\n\nIf there is a simpler/more efficient way to repeat a single \u201ccharacter\u201d (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char(\"*\", 5) => \"*****\").\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 \u00a0(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 \u00a0(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", "output": "\u00a0\nVALUES REPEAT('ha', 5);\nVALUES RPAD('', 10, 'ha');\n\u00a0", "input": ""}, {"instruction": "Take a string and repeat it some number of times.\n\nExample: repeat(\"ha\", 5) \u00a0 => \u00a0 \"hahahahaha\"\n\nIf there is a simpler/more efficient way to repeat a single \u201ccharacter\u201d (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char(\"*\", 5) => \"*****\").\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 \u00a0(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 \u00a0(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", "output": "select REPLICATE( 'ha', 5 )", "input": ""}, {"instruction": "\nSorting Algorithm\n\nThis is a sorting algorithm. \u00a0 It may be applied to a set of data in order to sort it. \u00a0 \u00a0\nFor comparing various sorts, see compare sorts. \u00a0\nFor other sorting algorithms, \u00a0 see sorting\u00a0algorithms, \u00a0 or:\n\nO(n logn) sorts\nHeap\u00a0sort |\nMerge\u00a0sort |\nPatience\u00a0sort |\nQuick\u00a0sort\nO(n log2n) sorts\nShell\u00a0Sort\nO(n2) sorts\nBubble\u00a0sort |\nCocktail\u00a0sort |\nCocktail\u00a0sort\u00a0with\u00a0shifting\u00a0bounds |\nComb\u00a0sort |\nCycle\u00a0sort |\nGnome\u00a0sort |\nInsertion\u00a0sort |\nSelection\u00a0sort |\nStrand\u00a0sort\nother sorts\nBead\u00a0sort |\nBogo\u00a0sort |\nCommon\u00a0sorted\u00a0list |\nComposite\u00a0structures\u00a0sort |\nCustom\u00a0comparator\u00a0sort |\nCounting\u00a0sort |\nDisjoint\u00a0sublist\u00a0sort |\nExternal\u00a0sort |\nJort\u00a0sort |\nLexicographical\u00a0sort |\nNatural\u00a0sorting |\nOrder\u00a0by\u00a0pair\u00a0comparisons |\nOrder\u00a0disjoint\u00a0list\u00a0items |\nOrder\u00a0two\u00a0numerical\u00a0lists |\nObject\u00a0identifier\u00a0(OID)\u00a0sort |\nPancake\u00a0sort |\nQuickselect |\nPermutation\u00a0sort |\nRadix\u00a0sort |\nRanking\u00a0methods |\nRemove\u00a0duplicate\u00a0elements |\nSleep\u00a0sort |\nStooge\u00a0sort |\n[Sort\u00a0letters\u00a0of\u00a0a\u00a0string] |\nThree\u00a0variable\u00a0sort |\nTopological\u00a0sort |\nTree\u00a0sort\n\n\nGiven an Array, derive a sequence of elements in which all duplicates are removed.\n\nThere are basically three approaches seen here:\n\n Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.\n Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be \"comparable\", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.\n Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).\n\n", "output": "\u00a0\n/*\nThis code is an implementation of \"Remove duplicate elements\" in SQL ORACLE 19c \np_in_str -- input string \np_delimiter -- delimeter \n*/\nWITH\n FUNCTION remove_duplicate_elements(p_in_str IN varchar2, p_delimiter IN varchar2 DEFAULT ',') RETURN varchar2 IS\n v_in_str varchar2(32767)\u00a0:= REPLACE(p_in_str,p_delimiter,',');\n v_res varchar2(32767);\nBEGIN\n --\n EXECUTE immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstringval() cv from xmltable(:v_in_str))' \n INTO v_res USING p_delimiter, v_in_str;\n --\n RETURN v_res;\n --\nEND;\n\u00a0\n--Test\nSELECT remove_duplicate_elements('1, 2, 3, \"a\", \"b\", \"c\", 2, 3, 4, \"b\", \"c\", \"d\"') AS res FROM dual\nUNION ALL \nSELECT remove_duplicate_elements('3 9 1 10 3 7 6 5 2 7 4 7 4 2 2 2 2 8 2 10 4 9 2 4 9 3 4 3 4 7',' ') AS res FROM dual\n; \n\u00a0", "input": ""}, {"instruction": "The task is to:\n\n State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n If possible, give a link to a wider explanation of the algorithm used.\nNote: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.\n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n", "output": "DBMS_RANDOM.RANDOM --produces integers in [-2^^31, 2^^31).\nDBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision.\nDBMS_RANDOM.NORMAL --produces normal distributed numbers with a mean of 0 and a variance of 1", "input": ""}, {"instruction": "Task\n\nGenerate a collection filled with \u00a0 1000 \u00a0 normally distributed random (or pseudo-random) numbers\nwith a mean of \u00a0 1.0 \u00a0 and a \u00a0 standard deviation \u00a0 of \u00a0 0.5\n\n\n\nMany libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.\n\n\n\nRelated task\n\n \u00a0 Standard deviation\n\n", "output": "\u00a0\nDECLARE\n --The desired collection\n type t_coll is table of number index by binary_integer; \n l_coll t_coll;\n\u00a0\n c_max pls_integer\u00a0:= 1000;\nBEGIN\n FOR l_counter IN 1 .. c_max\n LOOP\n -- dbms_random.normal delivers normal distributed random numbers with a mean of 0 and a variance of 1\n -- We just adjust the values and get the desired result:\n l_coll(l_counter)\u00a0:= DBMS_RANDOM.normal * 0.5 + 1;\n DBMS_OUTPUT.put_line (l_coll(l_counter));\n END LOOP;\nEND;\n\u00a0", "input": ""}, {"instruction": "Playfair cipher\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nImplement a Playfair cipher for encryption and decryption.\n\n\n\nThe user must be able to choose \u00a0 J \u00a0=\u00a0 I \u00a0 \u00a0 or \u00a0 no \u00a0 Q \u00a0 in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n\nOutput example\n\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n\n", "output": "\u00a0\n--Clean up previous run \nIF EXISTS (SELECT * \n FROM SYS.TYPES \n WHERE NAME = 'FairPlayTable') \n DROP TYPE FAIRPLAYTABLE \n\u00a0\n--Set Types \nCREATE TYPE FAIRPLAYTABLE AS TABLE (LETTER VARCHAR(1), COLID INT, ROWID INT) \n\u00a0\nGO \n\u00a0\n--Configuration Variables \nDECLARE @KEYWORD VARCHAR(25) = 'CHARLES' --Keyword for encryption \nDECLARE @INPUT VARCHAR(MAX) = 'Testing Seeconqz' --Word to be encrypted \nDECLARE @Q INT = 0 -- Q removed? \nDECLARE @ENCRYPT INT = 1 --Encrypt? \n--Setup Variables \nDECLARE @WORDS TABLE \n ( \n WORD_PRE VARCHAR(2), \n WORD_POST VARCHAR(2) \n ) \nDECLARE @T_TABLE FAIRPLAYTABLE \nDECLARE @NEXTLETTER CHAR(1) \nDECLARE @WORD VARCHAR(2), \n @COL1 INT, \n @COL2 INT, \n @ROW1 INT, \n @ROW2 INT, \n @TMP INT \nDECLARE @SQL NVARCHAR(MAX) = '', \n @COUNTER INT = 1, \n @I INT = 1 \nDECLARE @COUNTER_2 INT = 1 \n\u00a0\nSET @INPUT = REPLACE(@INPUT, ' ', '') \nSET @KEYWORD = UPPER(@KEYWORD) \n\u00a0\nDECLARE @USEDLETTERS VARCHAR(MAX) = '' \nDECLARE @TESTWORDS VARCHAR(2), \n @A INT = 0 \n\u00a0\nWHILE @COUNTER_2 <= 5 \n BEGIN \n WHILE @COUNTER <= 5 \n BEGIN \n IF LEN(@KEYWORD) > 0 \n BEGIN \n SET @NEXTLETTER = LEFT(@KEYWORD, 1) \n SET @KEYWORD = RIGHT(@KEYWORD, LEN(@KEYWORD) - 1) \n\u00a0\n IF CHARINDEX(@NEXTLETTER, @USEDLETTERS) = 0 \n BEGIN \n INSERT INTO @T_TABLE \n SELECT @NEXTLETTER, \n @COUNTER, \n @COUNTER_2 \n\u00a0\n SET @COUNTER = @COUNTER + 1 \n SET @USEDLETTERS = @USEDLETTERS + @NEXTLETTER \n END \n END \n ELSE \n BEGIN \n WHILE 1 = 1 \n BEGIN \n IF CHARINDEX(CHAR(64 + @I), @USEDLETTERS) = 0 \n AND NOT ( CHAR(64 + @I) = 'Q' \n AND @Q = 1 ) \n AND NOT ( @Q = 0 \n AND CHAR(64 + @I) = 'J' ) \n BEGIN \n SET @NEXTLETTER = CHAR(64 + @I) \n SET @USEDLETTERS = @USEDLETTERS + CHAR(64 + @I) \n SET @I = @I + 1 \n\u00a0\n BREAK \n END \n\u00a0\n SET @I = @I + 1 \n END \n\u00a0\n -- SELECT 1 AS [T] \n --BREAK \n INSERT INTO @T_TABLE \n SELECT @NEXTLETTER, \n @COUNTER, \n @COUNTER_2 \n\u00a0\n SET @COUNTER = @COUNTER + 1 \n END \n END \n\u00a0\n SET @COUNTER_2 = @COUNTER_2 + 1 \n SET @COUNTER = 1 \n END \n\u00a0\n--Split word into Digraphs \nWHILE @A < 1 \n BEGIN \n SET @TESTWORDS = UPPER(LEFT(@INPUT, 2)) \n\u00a0\n IF LEN(@TESTWORDS) = 1 \n BEGIN \n SET @TESTWORDS = @TESTWORDS + 'X' \n SET @A = 1 \n END \n ELSE IF RIGHT(@TESTWORDS, 1) = LEFT(@TESTWORDS, 1) \n BEGIN \n SET @TESTWORDS = RIGHT(@TESTWORDS, 1) + 'X' \n SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 1) \n END \n ELSE \n SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 2) \n\u00a0\n IF LEN(@INPUT) = 0 \n SET @A = 1 \n\u00a0\n INSERT @WORDS \n SELECT @TESTWORDS, \n '' \n END \n\u00a0\n--Start Encryption \nIF @ENCRYPT = 1 \n BEGIN \n --Loop through Digraphs amd encrypt \n DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR \n SELECT WORD_PRE \n FROM @WORDS \n FOR UPDATE OF WORD_POST \n\u00a0\n OPEN WORDS_LOOP \n\u00a0\n FETCH NEXT FROM WORDS_LOOP INTO @WORD \n\u00a0\n WHILE @@FETCH_STATUS = 0 \n BEGIN \n --Find letter positions \n SET @ROW1 = (SELECT ROWID \n FROM @T_TABLE \n WHERE LETTER = LEFT(@WORD, 1)) \n SET @ROW2 = (SELECT ROWID \n FROM @T_TABLE \n WHERE LETTER = RIGHT(@WORD, 1)) \n SET @COL1 = (SELECT COLID \n FROM @T_TABLE \n WHERE LETTER = LEFT(@WORD, 1)) \n SET @COL2 = (SELECT COLID \n FROM @T_TABLE \n WHERE LETTER = RIGHT(@WORD, 1)) \n\u00a0\n --Move positions according to encryption rules \n IF @COL1 = @COL2 \n BEGIN \n SET @ROW1 = @ROW1 + 1 \n SET @ROW2 = @ROW2 + 1 \n --select 'row' \n END \n ELSE IF @ROW1 = @ROW2 \n BEGIN \n SET @COL1 = @COL1 + 1 \n SET @COL2 = @COL2 + 1 \n --select 'col' \n END \n ELSE \n BEGIN \n SET @TMP = @COL2 \n SET @COL2 = @COL1 \n SET @COL1 = @TMP \n --select 'reg' \n END \n\u00a0\n IF @ROW1 = 6 \n SET @ROW1 = 1 \n\u00a0\n IF @ROW2 = 6 \n SET @ROW2 = 1 \n\u00a0\n IF @COL1 = 6 \n SET @COL1 = 1 \n\u00a0\n IF @COL2 = 6 \n SET @COL2 = 1 \n\u00a0\n --Find encrypted letters by positions \n UPDATE @WORDS \n SET WORD_POST = (SELECT (SELECT LETTER \n FROM @T_TABLE \n WHERE ROWID = @ROW1 \n AND COLID = @COL1) \n + (SELECT LETTER \n FROM @T_TABLE \n WHERE COLID = @COL2 \n AND ROWID = @ROW2)) \n WHERE WORD_PRE = @WORD \n\u00a0\n FETCH NEXT FROM WORDS_LOOP INTO @WORD \n END \n\u00a0\n CLOSE WORDS_LOOP \n\u00a0\n DEALLOCATE WORDS_LOOP \n END \n--Start Decryption \nELSE \n BEGIN \n --Loop through Digraphs amd decrypt \n DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR \n SELECT WORD_PRE \n FROM @WORDS \n FOR UPDATE OF WORD_POST \n\u00a0\n OPEN WORDS_LOOP \n\u00a0\n FETCH NEXT FROM WORDS_LOOP INTO @WORD \n\u00a0\n WHILE @@FETCH_STATUS = 0 \n BEGIN \n --Find letter positions \n SET @ROW1 = (SELECT ROWID \n FROM @T_TABLE \n WHERE LETTER = LEFT(@WORD, 1)) \n SET @ROW2 = (SELECT ROWID \n FROM @T_TABLE \n WHERE LETTER = RIGHT(@WORD, 1)) \n SET @COL1 = (SELECT COLID \n FROM @T_TABLE \n WHERE LETTER = LEFT(@WORD, 1)) \n SET @COL2 = (SELECT COLID \n FROM @T_TABLE \n WHERE LETTER = RIGHT(@WORD, 1)) \n\u00a0\n --Move positions according to encryption rules \n IF @COL1 = @COL2 \n BEGIN \n SET @ROW1 = @ROW1 - 1 \n SET @ROW2 = @ROW2 - 1 \n --select 'row' \n END \n ELSE IF @ROW1 = @ROW2 \n BEGIN \n SET @COL1 = @COL1 - 1 \n SET @COL2 = @COL2 - 1 \n --select 'col' \n END \n ELSE \n BEGIN \n SET @TMP = @COL2 \n SET @COL2 = @COL1 \n SET @COL1 = @TMP \n --select 'reg' \n END \n\u00a0\n IF @ROW1 = 0 \n SET @ROW1 = 5 \n\u00a0\n IF @ROW2 = 0 \n SET @ROW2 = 5 \n\u00a0\n IF @COL1 = 0 \n SET @COL1 = 5 \n\u00a0\n IF @COL2 = 0 \n SET @COL2 = 5 \n\u00a0\n --Find decrypted letters by positions \n UPDATE @WORDS \n SET WORD_POST = (SELECT (SELECT LETTER \n FROM @T_TABLE \n WHERE ROWID = @ROW1 \n AND COLID = @COL1) \n + (SELECT LETTER \n FROM @T_TABLE \n WHERE COLID = @COL2 \n AND ROWID = @ROW2)) \n WHERE WORD_PRE = @WORD \n\u00a0\n FETCH NEXT FROM WORDS_LOOP INTO @WORD \n END \n\u00a0\n CLOSE WORDS_LOOP \n\u00a0\n DEALLOCATE WORDS_LOOP \n END \n\u00a0\n--Output \nDECLARE WORDS CURSOR LOCAL FAST_FORWARD FOR \n SELECT WORD_POST \n FROM @WORDS \n\u00a0\nOPEN WORDS \n\u00a0\nFETCH NEXT FROM WORDS INTO @WORD \n\u00a0\nWHILE @@FETCH_STATUS = 0 \n BEGIN \n SET @SQL = @SQL + @WORD + ' '\n\u00a0\n FETCH NEXT FROM WORDS INTO @WORD \n END \n\u00a0\nCLOSE WORDS \n\u00a0\nDEALLOCATE WORDS \n\u00a0\nSELECT @SQL \n\u00a0\n--Cleanup \nIF EXISTS (SELECT * \n FROM SYS.TYPES \n WHERE NAME = 'FairPlayTable') \n DROP TYPE FAIRPLAYTABLE \n\u00a0", "input": ""}, {"instruction": "Task\n\nWrite a boolean function that tells whether a given integer is prime.\n\n\n\nRemember that \u00a0 1 \u00a0 and all non-positive numbers are not prime.\n\nUse trial division.\n\nEven numbers greater than \u00a0 2 \u00a0 may be eliminated right away.\n\nA loop from \u00a0 3 \u00a0 to \u00a0 \u221a\u00a0n\u00a0 \u00a0 will suffice, \u00a0 but other loops are allowed.\n\n\n\nRelated tasks\n\n \u00a0 count in factors\n \u00a0 prime decomposition\n \u00a0 AKS test for primes\n \u00a0 factors of an integer\n \u00a0 Sieve of Eratosthenes\n \u00a0 factors of a Mersenne number\n \u00a0 trial factoring of a Mersenne number\n \u00a0 partition an integer X into N primes\n \u00a0 sequence of primes by Trial Division\n\n", "output": "declare @number int\nset @number = 514229 -- number to check\n\u00a0\n;with cte(number) as \n(\n select 2\n union all\n select number+1\n from cte\n where number+1 < @number\n)\nselect\n cast(@number as varchar(100)) +\n case \n when exists\n\t\t\t\t (\n\t\t\t\t\tselect * \n\t\t\t\t\tfrom \n\t\t\t\t\t(\n\t\t\t\t\t\tselect number, @number % number modNumber\n\t\t\t\t\t\tfrom cte\n\t\t\t\t\t) tmp\n\t\t\t\t\twhere tmp.modNumber = 0 \n\t\t\t\t ) \n\t\t\t\t then ' is composite'\n\t\t else\n\t\t\t\t\t\t ' is prime'\n\t end primalityTest\noption (maxrecursion 0)", "input": ""}, {"instruction": "SQL injection\nUsing a SQL update statement like this one (spacing is optional):\n\nUPDATE players\n SET name = 'Smith, Steve', score = 42, active = TRUE\n WHERE jerseyNum = 99\nNon-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.", "output": "-- This works in Oracle's SQL*Plus command line utility\n\u00a0\nVARIABLE P_NAME VARCHAR2(20);\nVARIABLE P_SCORE NUMBER;\nVARIABLE P_ACTIVE VARCHAR2(5);\nVARIABLE P_JERSEYNUM NUMBER;\n\u00a0\nBEGIN\n\u00a0\n:P_NAME\u00a0:= 'Smith, Steve';\n:P_SCORE\u00a0:= 42;\n:P_ACTIVE\u00a0:= 'TRUE';\n:P_JERSEYNUM\u00a0:= 99;\n\u00a0\nEND;\n/\n\u00a0\nDROP TABLE players;\n\u00a0\nCREATE TABLE players \n(\nNAME VARCHAR2(20),\nSCORE NUMBER,\nACTIVE VARCHAR2(5),\nJERSEYNUM NUMBER\n);\n\u00a0\nINSERT INTO players VALUES ('No name',0,'FALSE',99);\n\u00a0\ncommit;\n\u00a0\nSELECT * FROM players;\n\u00a0\nUPDATE players\n SET name =\u00a0:P_NAME, score =\u00a0:P_SCORE, active =\u00a0:P_ACTIVE\n WHERE jerseyNum =\u00a0:P_JERSEYNUM;\n\u00a0\ncommit;\n\u00a0\nSELECT * FROM players;", "input": ""}, {"instruction": "SQL injection\nUsing a SQL update statement like this one (spacing is optional):\n\nUPDATE players\n SET name = 'Smith, Steve', score = 42, active = TRUE\n WHERE jerseyNum = 99\nNon-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nCREATE TABLE PLAYERS (\n NAME VARCHAR(32),\n SCORE INT,\n ACTIVE SMALLINT,\n JERSEYNUM INT\n) @\n\u00a0\nCREATE PROCEDURE UPDATE_PLAYER (\n IN PLAYER_NAME VARCHAR(32),\n IN PLAYER_SCORE INT,\n IN PLAYER_ACTIVE SMALLINT,\n IN JERSEY_NUMBER INT\n )\n BEGIN\n UPDATE PLAYERS\n SET NAME = PLAYER_NAME, SCORE = PLAYER_SCORE, ACTIVE = PLAYER_ACTIVE\n WHERE JERSEYNUM = JERSEY_NUMBER;\n END @\n\u00a0\nINSERT INTO PLAYERS VALUES ('Pele', '1280', 0, 10) @\n\u00a0\nCALL UPDATE_PLAYER ('Maradona', '600', 1, 10) @\n\u00a0\nSELECT * FROM PLAYERS @\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a stack-based evaluator for an expression in \u00a0 reverse Polish notation (RPN) \u00a0 that also shows the changes in the stack as each individual token is processed as a table.\n\n\n\n Assume an input of a correct, space separated, string of tokens of an RPN expression\n Test with the RPN expression generated from the \u00a0 Parsing/Shunting-yard algorithm \u00a0 task: \n\n\u00a0 \u00a0 \u00a0 \u00a0 3 4 2 * 1 5 - 2 3 ^ ^ / + \n\n Print or display the output here\n\n\nNotes\n\n \u00a0 ^ \u00a0 means exponentiation in the expression above.\n \u00a0 / \u00a0 means division.\n\n\nSee also\n\n \u00a0 Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.\n \u00a0 Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).\n \u00a0 Parsing/RPN to infix conversion.\n \u00a0 Arithmetic evaluation.\n\n", "output": "CREATE OR REPLACE FUNCTION rpn_calc(str VARCHAR2) RETURN NUMBER AS\n TYPE num_aa IS TABLE OF NUMBER INDEX BY PLS_INTEGER;\n TYPE num_stack IS RECORD (a num_aa, top PLS_INTEGER DEFAULT 0);\n ns num_stack;\n pos1 INTEGER := 1;\n pos2 INTEGER;\n token VARCHAR2(100);\n op2 NUMBER;\n PROCEDURE push(s IN OUT NOCOPY num_stack, x NUMBER) IS\n BEGIN\n s.top := s.top + 1;\n s.a(s.top) := x;\n END;\n FUNCTION pop(s IN OUT NOCOPY num_stack) RETURN NUMBER IS\n x NUMBER;\n BEGIN\n x := s.a(s.top);\n s.top := s.top - 1;\n RETURN x;\n END;\n PROCEDURE print_stack(s num_stack) IS -- for debugging only; remove from final version\n ps VARCHAR2(4000);\n BEGIN \n FOR i IN 1 .. s.top LOOP\n ps := ps || s.a(i) || ' ';\n END LOOP;\n DBMS_OUTPUT.put_line('Stack: ' || RTRIM(ps));\n END;\nBEGIN\n WHILE pos1 <= LENGTH(str) LOOP\n pos2 := INSTR(str || ' ', ' ', pos1);\n token := SUBSTR(str, pos1, pos2 - pos1);\n pos1 := pos2 + 1;\n CASE token \n WHEN '+' THEN push(ns, pop(ns) + pop(ns));\n WHEN '-' THEN op2 := pop(ns); push(ns, pop(ns) - op2);\n WHEN '*' THEN push(ns, pop(ns) * pop(ns));\n WHEN '/' THEN op2 := pop(ns); push(ns, pop(ns) / op2);\n WHEN '^' THEN op2 := pop(ns); push(ns, POWER(pop(ns), op2));\n ELSE push(ns, TO_NUMBER(token));\n END CASE;\n print_stack(ns); -- for debugging purposes only\n END LOOP;\n RETURN pop(ns);\nEND rpn_calc;\n/", "input": ""}, {"instruction": "A palindrome is a phrase which reads the same backward and forward.\n\nTask[edit]\nWrite a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)\nis a palindrome.\n\nFor extra credit:\n\n Support Unicode characters.\n Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.\nHints\n It might be useful for this task to know how to reverse a string.\n This task's entries might also form the subjects of the task Test a function.\nRelated tasks\nWord plays\n\nOrdered words\nPalindrome detection\nSemordnilap\nAnagrams\nAnagrams/Deranged anagrams\n\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 \u00a0(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 \u00a0(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", "output": "SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');\nSELECT REVERSE(@txt) = @txt;", "input": ""}, {"instruction": "Task\n\nShow how to spell out a number in English.\n\nYou can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).\n\nSupport for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.\n\n\n\nRelated task\n\n \u00a0 Spelling of ordinal numbers.\n\n", "output": "\u00a0\nSELECT val, to_char(to_date(val,'j'),'jsp') name\nFROM\n(\nSELECT\nround( dbms_random.VALUE(1, 5373484)) val\nFROM dual\nCONNECT BY level <= 5\n);\n\u00a0\nSELECT to_char(to_date(5373485,'j'),'jsp') FROM dual;\n\u00a0", "input": ""}, {"instruction": "Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.\n\n\n\nExample\n\nReturns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th\n\n\n\nTask\n\nUse your routine to show here the output for at least the following (inclusive) ranges of integer inputs:\n0..25, 250..265, 1000..1025\n\n\nNote: apostrophes are now optional to allow correct apostrophe-less English.\n\n\n\n", "output": "\u00a0\nSELECT level card,\n to_char(to_date(level,'j'),'fmjth') ord\nFROM dual\nCONNECT BY level <= 15;\n\u00a0\nSELECT to_char(to_date(5373485,'j'),'fmjth')\nFROM dual;\n\u00a0", "input": ""}, {"instruction": "From Wikipedia:\n\nIn modular arithmetic, \u00a0 the modular multiplicative inverse of an integer \u00a0 a \u00a0 modulo \u00a0 m \u00a0 is an integer \u00a0 x \u00a0 such that\n\n\n\n\n\na\n\nx\n\u2261\n1\n\n\n(\nmod\n\nm\n)\n\n.\n\n\n{\\displaystyle a\\,x\\equiv 1{\\pmod {m}}.}\n\n\nOr in other words, such that:\n\n\n\n\n\n\u2203\nk\n\u2208\n\nZ\n\n,\n\na\n\nx\n=\n1\n+\nk\n\nm\n\n\n{\\displaystyle \\exists k\\in \\mathbb {Z} ,\\qquad a\\,x=1+k\\,m}\n\n\nIt can be shown that such an inverse exists \u00a0 if and only if \u00a0 a \u00a0 and \u00a0 m \u00a0 are coprime, \u00a0 but we will ignore this for this task.\n\n\n\nTask\n\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in\nyour language, \u00a0 compute the modular inverse of \u00a0 42 modulo 2017.\n\n\n\n", "output": ";WITH Iterate(N,A,B,X0,X1)\n\tAS (\n\t\tSELECT \n\t\t\t1\n\t\t\t,CASE WHEN @a < 0 THEN @b-(-@a % @b) ELSE @a END\n\t\t\t,CASE WHEN @b < 0 THEN -@b ELSE @b END\n\t\t\t,0\n\t\t\t,1\n\t\tUNION ALL\n\t\tSELECT \n\t\t\tN+1\n\t\t\t,B\n\t\t\t,A%B\n\t\t\t,X1-((A/B)*X0)\n\t\t\t,X0\n\t\tFROM Iterate\n\t\tWHERE A != 1 AND B != 0\n\t),\n\tModularInverse(Result)\n\tAS (\n\t\tSELECT\n\t\t\t-1\n\t\t\tFROM Iterate\n\t\t\tWHERE A != 1 AND B = 0\n\t\tUNION ALL\n\t\tSELECT\n\t\t\tTOP(1)\n\t\t\tCASE WHEN X1 < 0 THEN X1+@b ELSE X1 END AS Result\n\t\t\tFROM Iterate\n\t\t\tWHERE (SELECT COUNT(*) FROM Iterate WHERE A != 1 AND B = 0) = 0\n\t\t\tORDER BY N DESC\n\t)\n\tSELECT *\n\tFROM ModularInverse", "input": ""}, {"instruction": "\n\nSolve the eight queens puzzle.\n\n\n\nYou can extend the problem to solve the puzzle with a board of size \u00a0 NxN.\n\nFor the number of solutions for small values of \u00a0 N, \u00a0 see \u00a0 OEIS: A000170.\n\n\n\nRelated tasks\n\n A* search algorithm\n Solve a Hidato puzzle\n Solve a Holy Knight's tour\n Knight's tour\n Peaceful chess queen armies\n Solve a Hopido puzzle\n Solve a Numbrix puzzle\n Solve the no connection puzzle\n\n", "output": "\u00a0\nWITH RECURSIVE\n positions(i) AS (\n VALUES(0)\n UNION SELECT ALL\n i+1 FROM positions WHERE i < 63\n ),\n solutions(board, n_queens) AS (\n SELECT '----------------------------------------------------------------', CAST(0 AS BIGINT) \n FROM positions\n UNION\n SELECT\n substr(board, 1, i) || '*' || substr(board, i+2),n_queens + 1 AS n_queens\n FROM positions AS ps, solutions \n WHERE n_queens < 8\n AND substr(board,1,i)\u00a0!= '*'\n AND NOT EXISTS (\n SELECT 1 FROM positions WHERE\n substr(board,i+1,1) = '*' AND\n (\n i\u00a0% 8 = ps.i\u00a0%8 OR\n CAST(i / 8 AS INT) = CAST(ps.i / 8 AS INT) OR\n CAST(i / 8 AS INT) + (i\u00a0% 8) = CAST(ps.i / 8 AS INT) + (ps.i\u00a0% 8) OR\n CAST(i / 8 AS INT) - (i\u00a0% 8) = CAST(ps.i / 8 AS INT) - (ps.i\u00a0% 8)\n )\n LIMIT 1\n ) \n ORDER BY n_queens DESC -- remove this when using Postgres (they don't support ORDER BY in CTEs)\n )\nSELECT board,n_queens FROM solutions WHERE n_queens = 8;\n\u00a0\n\u00a0", "input": ""}, {"instruction": "\n\nSolve the eight queens puzzle.\n\n\n\nYou can extend the problem to solve the puzzle with a board of size \u00a0 NxN.\n\nFor the number of solutions for small values of \u00a0 N, \u00a0 see \u00a0 OEIS: A000170.\n\n\n\nRelated tasks\n\n A* search algorithm\n Solve a Hidato puzzle\n Solve a Holy Knight's tour\n Knight's tour\n Peaceful chess queen armies\n Solve a Hopido puzzle\n Solve a Numbrix puzzle\n Solve the no connection puzzle\n\n", "output": "\u00a0\n-- A column of a matrix.\nCREATE TYPE INTEGER_ARRAY AS INTEGER ARRAY[]@\n-- The whole matrix of any size.\nCREATE TYPE INTEGER_MATRIX AS INTEGER_ARRAY ARRAY[]@\n\u00a0\n/**\n * Retrieves the value from a matrix at a specific position.\n * \n * IN X: Row number.\n * IN Y: Column number.\n * IN M: Matrix.\n * RETURN the integer value at that position.\n */\nCREATE OR REPLACE FUNCTION GET_INTEGER_VALUE(\n IN X SMALLINT,\n IN Y SMALLINT,\n IN M INTEGER_MATRIX)\nRETURNS INTEGER\nF_GET_INTEGER_VALUE: BEGIN\n DECLARE A INTEGER_ARRAY;\n DECLARE RET INTEGER;\n\u00a0\n SET A = M[X];\n SET RET = A[Y];\n RETURN RET;\nEND F_GET_INTEGER_VALUE\n@\n\u00a0\n/**\n * Establishes the given value at a specific position in the matrix.\n * \n * IN X: Row number.\n * IN Y: Column number.\n * INOUT M: Matrix.\n * IN VAL: Value to set in the matrix.\n */\nCREATE OR REPLACE PROCEDURE SET_INTEGER_VALUE(\n IN X SMALLINT,\n IN Y SMALLINT,\n INOUT M INTEGER_MATRIX,\n IN VAL INTEGER)\nP_SET_INTEGER_VALUE: BEGIN\n DECLARE A INTEGER_ARRAY;\n\u00a0\n SET A = M[X];\n SET A[Y] = VAL;\n SET M[X] = A;\nEND P_SET_INTEGER_VALUE\n@\n\u00a0\n/**\n * Initializes the matriz at a given size with the same value in all positions.\n * \n * INOUT M: Matrix.\n * IN X: Number of rows.\n * IN Y: Number of columns per row.\n * IN VAL: Value to set in the matrix.\n */\nCREATE OR REPLACE PROCEDURE INIT_INTEGER_MATRIX(\n INOUT M INTEGER_MATRIX,\n IN X SMALLINT,\n IN Y SMALLINT,\n IN VAL INTEGER)\nP_INIT_INTEGER_MATRIX: BEGIN\n DECLARE I SMALLINT DEFAULT 1;\n DECLARE J SMALLINT;\n DECLARE A INTEGER_ARRAY;\n\u00a0\n WHILE (I <= X) DO\n SET A = ARRAY[];\n SET J = 1;\n WHILE (J <= Y) DO\n SET A[J] = VAL;\n SET J = J + 1;\n END WHILE;\n SET M[I] = A;\n SET I = I + 1;\n END WHILE;\nEND P_INIT_INTEGER_MATRIX\n@\n\u00a0\n/**\n * Prints the content of the matrix to the standard output.\n * \n * INOUT M: Matrix.\n */\nCREATE OR REPLACE PROCEDURE PRINT_INTEGER_MATRIX(\n IN M INTEGER_MATRIX)\nP_PRINT_INTEGER_MATRIX: BEGIN\n DECLARE I SMALLINT DEFAULT 1;\n DECLARE J SMALLINT;\n DECLARE X SMALLINT;\n DECLARE Y SMALLINT;\n DECLARE VAL INTEGER;\n DECLARE A INTEGER_ARRAY;\n DECLARE RET VARCHAR(256);\n\u00a0\n SET X = CARDINALITY(M);\n CALL DBMS_OUTPUT.PUT_LINE('>>>>>');\n WHILE (I <= X) DO\n SET A = M[I];\n SET RET = '[';\n SET Y = CARDINALITY(A);\n SET J = 1;\n WHILE (J <= Y) DO\n SET VAL = A[J];\n SET RET = RET || VAL;\n SET J = J + 1;\n IF (J <= Y) THEN\n SET RET = RET || ',';\n END IF;\n END WHILE;\n SET RET = RET || ']';\n CALL DBMS_OUTPUT.PUT_LINE(RET);\n SET I = I + 1;\n END WHILE;\n CALL DBMS_OUTPUT.PUT_LINE('<<<<<');\nEND P_PRINT_INTEGER_MATRIX\n@\n\u00a0\n/**\n * Checks if a queen is safe in the given position.\n * \n * IN M: Matrix representing the chessboard.\n * IN ROW: Row of the queen.\n * IN COL: Column in the row for the queen.\n * IN SIZE: Size of the chessboard (max row, max col).\n * RETURNS true if the position is safe.\n */\nCREATE OR REPLACE FUNCTION IS_SAFE(\n IN M INTEGER_MATRIX,\n IN ROW SMALLINT,\n IN COL SMALLINT,\n IN SIZE SMALLINT)\n MODIFIES SQL DATA\n RETURNS BOOLEAN\n F_IS_SAFE: BEGIN\n DECLARE I SMALLINT;\n DECLARE J SMALLINT;\n DECLARE VAL INTEGER;\n\u00a0\n -- Debug purposes.\n --CALL SET_INTEGER_VALUE(ROW, COL, M, -1);\n --CALL PRINT_INTEGER_MATRIX(M);\n --CALL SET_INTEGER_VALUE(ROW, COL, M, 0);\n\u00a0\n SET I = 1;\n WHILE (I <= COL) DO\n SET VAL = GET_INTEGER_VALUE(ROW, I, M);\n IF (VAL = 1) THEN\n RETURN FALSE;\n END IF;\n SET I = I + 1;\n END WHILE;\n\u00a0\n SET I = ROW;\n SET J = COL;\n WHILE (I >= 1 AND J >= 1) DO\n SET VAL = GET_INTEGER_VALUE(I, J, M);\n IF (VAL = 1) THEN\n CALL SET_INTEGER_VALUE(ROW, COL, M, 0);\n RETURN FALSE;\n END IF;\n SET I = I - 1;\n SET J = J - 1;\n END WHILE;\n\u00a0\n SET I = ROW;\n SET J = COL;\n WHILE (J >= 1 AND I <= SIZE) DO\n SET VAL = GET_INTEGER_VALUE(I, J, M);\n IF (VAL = 1) THEN\n RETURN FALSE;\n END IF;\n SET I = I + 1;\n SET J = J - 1;\n END WHILE;\n\u00a0\n RETURN TRUE;\n END F_IS_SAFE\n@\n\u00a0\n/**\n * Dummy procedure for the recurssion.\n * \n * IN SIZE: Size of the chessboard (max row, max col).\n * IN COL: Column to analyse.\n * OUT RET: True if it was possible to put all queens\n */\nCREATE OR REPLACE PROCEDURE SOLVE_N_QUEENS(\n INOUT M INTEGER_MATRIX,\n IN SIZE SMALLINT,\n IN COL SMALLINT,\n OUT RET BOOLEAN)\n P_SOLVE_N_QUEENS: BEGIN\n END P_SOLVE_N_QUEENS\n@\n\u00a0\n/**\n * Solves the n-queens algoritm.\n * \n * IN SIZE: Size of the chessboard (max row, max col).\n * IN COL: Column to analyse.\n * OUT RET: True if it was possible to put all queens\n */\nCREATE OR REPLACE PROCEDURE SOLVE_N_QUEENS(\n INOUT M INTEGER_MATRIX,\n IN SIZE SMALLINT,\n IN COL SMALLINT,\n OUT RET BOOLEAN)\n MODIFIES SQL DATA\n P_SOLVE_N_QUEENS: BEGIN\n DECLARE I SMALLINT;\n DECLARE SAFE BOOLEAN;\n DECLARE SOLVED BOOLEAN;\n\u00a0\n -- Debug purposes.\n --CALL PRINT_INTEGER_MATRIX(M);\n SET RET = FALSE;\n IF (COL > SIZE) THEN\n SET RET = TRUE;\n ELSE\n SET I = 1;\n WHILE (I <= SIZE AND NOT RET) DO\n SET SAFE = IS_SAFE(M, I, COL, SIZE);\n IF (SAFE) THEN\n CALL SET_INTEGER_VALUE(I, COL, M, 1);\n CALL SOLVE_N_QUEENS(M, SIZE, COL + 1, SOLVED);\n IF (SOLVED) THEN\n SET RET = TRUE;\n ELSE\n CALL SET_INTEGER_VALUE(I, COL, M, 0); -- Backtrack.\n END IF;\n\u00a0\n END IF;\n\u00a0\n SET I = I + 1;\n END WHILE;\n\u00a0\n END IF;\n END P_SOLVE_N_QUEENS\n@\n\u00a0\n/**\n * Main procedure to solve the n-queen algoritm.\n * \n * IN SIZE: Size of the chessboard. The bigger it is, the more time it takes.\n */\nCREATE OR REPLACE PROCEDURE N_QUEENS(\n IN SIZE SMALLINT)\n P_N_QUEENS: BEGIN\n DECLARE M INTEGER_MATRIX;\n DECLARE SOL BOOLEAN DEFAULT FALSE;\n\u00a0\n CALL INIT_INTEGER_MATRIX(M, SIZE, SIZE, 0);\n\u00a0\n CALL SOLVE_N_QUEENS(M, SIZE, 1, SOL);\n IF (SOL = TRUE) THEN\n CALL PRINT_INTEGER_MATRIX(M);\n ELSE\n CALL DBMS_OUTPUT.PUT_LINE('Solution does not exist.');\n END IF;\n\u00a0\n END P_N_QUEENS\n@\n\u00a0\n--#SET TERMINATOR\u00a0;\n\u00a0\n-- Activates the standard output for the current session.\nSET SERVEROUTPUT ON;\n\u00a0\nCALL N_QUEENS(4);\n\u00a0\nCALL N_QUEENS(8);\n\u00a0\nCALL N_QUEENS(16);\n\u00a0\n\u00a0\n\u00a0", "input": ""}, {"instruction": "\nSuppose you're on a game show and you're given the choice of three doors.\n\nBehind one door is a car; behind the others, goats.\n\nThe car and the goats were placed randomly behind the doors before the show.\n\n\n\nRules of the game\n\nAfter you have chosen a door, the door remains closed for the time being.\n\nThe game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.\n\nIf both remaining doors have goats behind them, he chooses one randomly.\n\nAfter Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.\n\nImagine that you chose Door 1 and the host opens Door 3, which has a goat.\n\nHe then asks you \"Do you want to switch to Door Number 2?\"\n\n\n\nThe question\n\nIs it to your advantage to change your choice?\n\n\n\nNote\n\nThe player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.\n\n\n\nTask\n\nRun random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.\n\nSimulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.\n\n\n\nReferences\n\n Stefan Krauss, X. T. Wang, \"The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.\", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3\n A YouTube video: \u00a0 Monty Hall Problem - Numberphile. \n\n", "output": "\u00a0\n---- BEGIN ------------\ncreate table MONTY_HALL(\n NOE int,\n CAR int,\n ALTERNATIVE int,\n ORIGIN int,\n [KEEP] int,\n [CHANGE] int,\n [RANDOM] int\n )\n\u00a0\n-- INIT \ntruncate table MONTY_HALL\n\u00a0\ndeclare @N int , @i int -- No of Experiments and their counter\ndeclare @rooms int , -- number of rooms\n @origin int, -- original choice\n\t\t@car int , -- room with car\n\t\t@alternative int -- alternative room\n\u00a0\nselect @rooms = 3, @N = 100000 , @i = 0 \n\u00a0\n-- EXPERIMENTS LOOP \nwhile @i < @N begin\n select @car = FLOOR(rand()*@rooms)+1 , @origin = FLOOR(rand()*@rooms)+1\n select @alternative = FLOOR(rand()*(@rooms-1))+1\n select @alternative = case when @alternative < @origin then @alternative else @alternative + 1 end\n select @alternative = case when @origin = @car then @alternative else @car end\n\u00a0\n insert MONTY_HALL\n select @i,@car,@alternative,@origin,@origin,@alternative,case when rand() < 5e-1 then @origin else @alternative end\n\u00a0\n select @i = @i + 1\nend\n\u00a0\n-- RESULTS\nselect avg (case when [KEEP] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR KEEP],\n avg (case when [CHANGE] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR CHANGE],\n avg (case when [RANDOM] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR RANDOM]\nfrom MONTY_HALL\n---- END ------------\n\u00a0", "input": ""}, {"instruction": "Merge and aggregate datasets\n\n\n\nTask\n\nMerge and aggregate two datasets as provided in \u00a0 .csv \u00a0 files into a new resulting dataset.\n\nUse the appropriate methods and data structures depending on the programming language.\n\nUse the most common libraries only when built-in functionality is not sufficient.\n\n\n\nNote\n\nEither load the data from the \u00a0 .csv \u00a0 files or create the required data structures hard-coded.\n\n\npatients.csv \u00a0 file contents:\n\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\n\n\nvisits.csv \u00a0 file contents:\n\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\n\n\n\nCreate a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.\n\nMerge and group per patient id and last name, \u00a0 get the maximum visit date, \u00a0 and get the sum and average of the scores per patient to get the resulting dataset.\n\n\n\nNote that the visit date is purposefully provided as ISO format, \u00a0 so that it could also be processed as text and sorted alphabetically to determine the maximum date.\n\n| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |\n| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |\n| 3003 | Kemeny | 2020-11-12 | | |\n| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |\n| 5005 | Kurtz | | | |\n\n\n\nNote\n\nThis task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.\n\n\n\nRelated tasks\n\n CSV data manipulation\n CSV to HTML translation\n Read entire file\n Read a file line by line\n\n", "output": "-- drop tables\nDROP TABLE IF EXISTS tmp_patients;\nDROP TABLE IF EXISTS tmp_visits;\n\u00a0\n-- create tables\nCREATE TABLE tmp_patients(\n\tPATIENT_ID INT,\n\tLASTNAME VARCHAR(20)\n);\n\u00a0\nCREATE TABLE tmp_visits(\n\tPATIENT_ID INT,\n\tVISIT_DATE DATE,\n\tSCORE NUMERIC(4,1)\n);\n\u00a0\n-- load data from csv files\n/*\n-- Note: LOAD DATA LOCAL requires `local-infile` enabled on both the client and server else you get error \"#1148 command is not allowed..\"\nLOAD DATA LOCAL INFILE '/home/csv/patients.csv' INTO TABLE `tmp_patients` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' IGNORE 1 LINES;\nLOAD DATA LOCAL INFILE '/home/csv/visits.csv' INTO TABLE `tmp_visits` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' IGNORE 1 LINES;\n*/\n\u00a0\n-- load data hard coded\nINSERT INTO tmp_patients(PATIENT_ID, LASTNAME)\nVALUES\n(1001, 'Hopper'),\n(4004, 'Wirth'),\n(3003, 'Kemeny'),\n(2002, 'Gosling'),\n(5005, 'Kurtz');\n\u00a0\nINSERT INTO tmp_visits(PATIENT_ID, VISIT_DATE, SCORE)\nVALUES\n(2002, '2020-09-10', 6.8),\n(1001, '2020-09-17', 5.5),\n(4004, '2020-09-24', 8.4),\n(2002, '2020-10-08', NULL),\n(1001, NULL, 6.6),\n(3003, '2020-11-12', NULL),\n(4004, '2020-11-05', 7.0),\n(1001, '2020-11-19', 5.3);\n\u00a0\n-- join tables and group\nSELECT\n\tp.PATIENT_ID,\n\tp.LASTNAME,\n\tMAX(VISIT_DATE) AS LAST_VISIT,\n\tSUM(SCORE) AS SCORE_SUM,\n\tCAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG\nFROM\n\ttmp_patients p\n\tLEFT JOIN tmp_visits v\n\t\tON v.PATIENT_ID = p.PATIENT_ID\nGROUP BY\n\tp.PATIENT_ID,\n\tp.LASTNAME\nORDER BY\n\tp.PATIENT_ID;", "input": ""}, {"instruction": "Task\n\nWrite a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n\n\n", "output": ";WITH DATA \n AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum, \n NUMBER, \n LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum \n FROM TABLE1) \nSELECT CASE \n WHEN ( LCHARNUM >= 3 \n AND LCHARNUM\u00a0% 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3) \n ELSE 'Error!' \n END Output, \n NUMBER INPUT \nFROM DATA ", "input": ""}, {"instruction": "Create a simple version of the board game: \u00a0 Mastermind.\n\nIt must be possible to:\n\n \u00a0 choose the number of colors will be used in the game (2 - 20)\n \u00a0 choose the color code length (4 - 10)\n \u00a0 choose the maximum number of guesses the player has (7 - 20)\n \u00a0 choose whether or not colors may be repeated in the code\n\n\nThe (computer program) game should display all the player guesses and the results of that guess.\n\nDisplay (just an idea):\n\n\n\n Feature \n Graphic Version \n Text Version\n\n\n Player guess\n\n Colored circles\n\n Alphabet letters\n\n\nCorrect color & position\n\nBlack circle\n\nX\n\n\nCorrect color\n\nWhite circle\n\nO\n\n\nNone\n\nGray circle\n\n -\n\n\n\n\nA text version example: \u00a0 \u00a0 \u00a0 1. \u00a0 ADEF \u00a0 - \u00a0 XXO- \n\nTranslates to:\n\nthe first guess;\n\nthe four colors (ADEF);\n\nresult:\n\n two correct colors and spot, \n one correct color/wrong spot, one color isn't in the code.\nHappy coding!\n\n\n\nRelated tasks\n\n \u00a0 Bulls and cows\n \u00a0 Bulls and cows/Player\n \u00a0 Guess the number\n \u00a0 Guess the number/With Feedback\n\n", "output": "\u00a0\n -- Create Table\n -- Distinct combination\n --- R\u00a0:Red, B\u00a0:Blue, G: Green, V: Violet, O: Orange, Y: Yellow\n DROP TYPE IF EXISTS color cascade;CREATE TYPE color AS ENUM ('R', 'B', 'G', 'V', 'O', 'Y');\n\u00a0\n DROP TABLE IF EXISTS guesses cascade\u00a0; CREATE TABLE guesses (\n FIRST color,\n SECOND color,\n third color ,\n fourth color\n );\n CREATE TABLE mastermind () inherits (guesses);\n\u00a0\n INSERT INTO mastermind VALUES ('G', 'B', 'R', 'V');\n\u00a0\n\u00a0\n INSERT INTO guesses VALUES ('Y', 'Y', 'B', 'B');\n INSERT INTO guesses VALUES ('V', 'R', 'R', 'Y');\n INSERT INTO guesses VALUES ('G', 'V', 'G', 'Y');\n INSERT INTO guesses VALUES ('R', 'R', 'V', 'Y');\n INSERT INTO guesses VALUES ('B', 'R', 'G', 'V');\n INSERT INTO guesses VALUES ('G', 'B', 'R', 'V');\n\u00a0\n\u00a0\n --- Matches Black\n CREATE OR REPLACE FUNCTION check_black(guesses, mastermind) RETURNS INTEGER AS $$\n SELECT (\n ($1.FIRST = $2.FIRST)::INT +\n ($1.SECOND = $2.SECOND)::INT +\n ($1.third = $2.third)::INT +\n ($1.fourth = $2.fourth)::INT\n );\n $$ LANGUAGE SQL;\n\u00a0\n --- Matches White\n CREATE OR REPLACE FUNCTION check_white(guesses, mastermind) RETURNS INTEGER AS $$\n SELECT (\n CASE WHEN ($1.FIRST = $2.FIRST) THEN 0 ELSE 0 END +\n CASE WHEN ($1.SECOND = $2.SECOND) THEN 0 ELSE 0 END +\n CASE WHEN ($1.third = $2.third) THEN 0 ELSE 0 END +\n CASE WHEN ($1.fourth = $2.fourth) THEN 0 ELSE 0 END +\n CASE WHEN ($1.FIRST\u00a0!= $2.FIRST) THEN (\n $1.FIRST = $2.SECOND OR\n $1.FIRST = $2.third OR\n $1.FIRST = $2.fourth\n )::INT ELSE 0 END +\n CASE WHEN ($1.SECOND\u00a0!= $2.SECOND) THEN (\n $1.SECOND = $2.FIRST OR\n $1.SECOND = $2.third OR\n $1.SECOND = $2.fourth\n )::INT ELSE 0 END +\n CASE WHEN ($1.third\u00a0!= $2.third) THEN (\n $1.third = $2.FIRST OR\n $1.third = $2.SECOND OR\n $1.third = $2.fourth\n )::INT ELSE 0 END +\n CASE WHEN ($1.fourth\u00a0!= $2.fourth) THEN (\n $1.fourth = $2.FIRST OR\n $1.fourth = $2.SECOND OR\n $1.fourth = $2.third\n )::INT ELSE 0 END\n ) FROM guesses\n $$ LANGUAGE SQL;\n\u00a0\n\u00a0\n\u00a0\n SELECT guesses,\n check_black(guesses.*, mastermind.*),\n check_white(guesses.*, mastermind.*)\n FROM guesses, mastermind\n\u00a0", "input": ""}, {"instruction": "Man or boy test\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n\nBackground: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented \"recursion and non-local references\" from those that did not.\n\n\nI have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'\n \u2014 Donald Knuth\nTask: Imitate Knuth's example in Algol 60 in another language, as far as possible.\n\nDetails: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.\n\nIn Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also \"shifts\" the variables xi by one place, so eventually the argument B (still bound to its particular\nactivation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.\n\nSo all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior\nin completely different parts of the call tree.\n\nKnuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be \u221267.\n\nPerformance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.\n\nThe table below shows the result, call depths, and total calls for a range of k:\n\n\n\n k\n\n 0\n\n 1\n\n 2\n\n 3\n\n 4\n\n 5\n\n 6\n\n 7\n\n 8\n\n 9\n\n 10\n\n 11\n\n 12\n\n 13\n\n 14\n\n 15\n\n 16\n\n 17\n\n 18\n\n 19\n\n 20\n\n 21\n\n 22\n\n 23\n\n 24\n\n 25\n\n 26\n\n 27\n\n 28\n\n 29\n\n 30\n\n\n A\n\n 1\n\n 0\n\n -2\n\n 0\n\n 1\n\n 0\n\n 1\n\n -1\n\n -10\n\n -30\n\n -67\n\n -138\n\n -291\n\n -642\n\n -1,446\n\n -3,250\n\n -7,244\n\n -16,065\n\n -35,601\n\n -78,985\n\n -175,416\n\n -389,695\n\n -865,609\n\n -1,922,362\n\n -4,268,854\n\n -9,479,595\n\n -21,051,458\n\n -46,750,171\n\n -103,821,058\n\n -230,560,902\n\n -512,016,658\n\n\n A called\n\n 1\n\n 2\n\n 3\n\n 4\n\n 8\n\n 18\n\n 38\n\n 80\n\n 167\n\n 347\n\n 722\n\n 1,509\n\n 3,168\n\n 6,673\n\n 14,091\n\n 29,825\n\n 63,287\n\n 134,652\n\n 287,264\n\n 614,442\n\n 1,317,533\n\n 2,831,900\n\n 6,100,852\n\n 13,172,239\n\n 28,499,827\n\n 61,786,266\n\n 134,202,509\n\n 292,011,464\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\n A depth\n\n 1\n\n 2\n\n 3\n\n 4\n\n 8\n\n 16\n\n 32\n\n 64\n\n 128\n\n 256\n\n 512\n\n 1,024\n\n 2,048\n\n 4,096\n\n 8,192\n\n 16,384\n\n 32,768\n\n 65,536\n\n 131,072\n\n 262,144\n\n 524,288\n\n 1,048,576\n\n 2,097,152\n\n 4,194,304\n\n 8,388,608\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\n B called\n\n 0\n\n 1\n\n 2\n\n 3\n\n 7\n\n 17\n\n 37\n\n 79\n\n 166\n\n 346\n\n 721\n\n 1,508\n\n 3,167\n\n 6,672\n\n 14,090\n\n 29,824\n\n 63,286\n\n 134,651\n\n 287,263\n\n 614,441\n\n 1,317,532\n\n 2,831,899\n\n 6,100,851\n\n 13,172,238\n\n 28,499,826\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\n B depth\n\n 0\n\n 1\n\n 2\n\n 3\n\n 7\n\n 15\n\n 31\n\n 63\n\n 127\n\n 255\n\n 511\n\n 1,023\n\n 2,047\n\n 4,095\n\n 8,191\n\n 16,383\n\n 32,767\n\n 65,535\n\n 131,071\n\n 262,143\n\n 524,287\n\n 1,048,575\n\n 2,097,151\n\n 4,194,303\n\n 8,388,607\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\u00a0\n\n\n\nRelated tasks\n\n \u00a0 Jensen's Device\n\n", "output": "\u00a0\nCREATE PROCEDURE dbo.LAMBDA_WRAP_INTEGER\n\u00a0\n\t@v INT\n\u00a0\nAS\n\tDECLARE\t@name NVARCHAR(MAX) = 'LAMBDA_' + UPPER(REPLACE(NEWID(), '-', '_'))\n\tDECLARE @SQL NVARCHAR(MAX) = '\n\t\t\tCREATE PROCEDURE dbo.' + @name + '\n\t\t\t\tAS \n\u00a0\n\t\t\tRETURN ' + CAST(@v AS NVARCHAR(MAX))\n\u00a0\n\tEXEC(@SQL)\n\tRETURN OBJECT_ID(@name)\nGO\n\u00a0\nCREATE PROCEDURE dbo.LAMBDA_EXEC\n\t@id INT\n\u00a0\nAS\n\tDECLARE @name SYSNAME = OBJECT_NAME(@id)\n\t,\t@retval INT\n\tEXEC\t@retval = @name\n\tRETURN\t@retval\nGO\n\u00a0\n-- B-procedure\nCREATE PROCEDURE dbo.LAMBDA_B\n\t@name_out SYSNAME OUTPUT\n,\t@q INT\nAS\nBEGIN\n\u00a0\n\tDECLARE\t@SQL NVARCHAR(MAX)\n\t,\t@name NVARCHAR(MAX) = 'LAMBDA_B_' + UPPER(REPLACE(NEWID(), '-', '_'))\n\u00a0\n\tSELECT\t@SQL = N'\n\t\tCREATE PROCEDURE dbo.' + @name + N'\n\u00a0\n\t\t\tAS \n\u00a0\n\t\tDECLARE @retval INT, @k INT, @x1 INT, @x2 INT, @x3 INT, @x4 INT\n\u00a0\n\t\tSELECT\t@k = k - 1, @x1 = x1, @x2 = x2,\t@x3 = x3, @x4 = x4\n\t\tFROM\t#t_args t\n\t\tWHERE\tt.i = ' + CAST(@q AS NVARCHAR(MAX)) + '\n\u00a0\n\t\tUPDATE\tt\n\t\tSET\tk = k -1\n\t\tFROM\t#t_args t\n\t\tWHERE\tt.i = ' + CAST(@q AS NVARCHAR(MAX)) + '\n\u00a0\n\t\tEXEC\t@retval = LAMBDA_A @k, @@PROCID, @x1, @x2, @x3, @x4\n\t\tRETURN @retval'\n\tEXEC(@SQL)\n\u00a0\n\tSELECT\t@name_out = @name\nEND\n\u00a0\nGO\n-- A-procedure\nCREATE PROCEDURE dbo.LAMBDA_A \n(\n\u00a0\n\t@k INT\n,\t@x1 INT\n,\t@x2 INT\n,\t@x3 INT\n,\t@x4 INT\n,\t@x5 INT\n)\nAS\n\tSET NOCOUNT ON;\n\tDECLARE @res1 INT\n\t,\t@res2 INT\n\t,\t@Name SYSNAME\n\t,\t@q INT\n\u00a0\n\t-- First add the arguments to the \"stack\"\n\tINSERT INTO #t_args (k,\tx1, x2, x3, x4, x5\n\t)\n\tSELECT\t@k, @x1, @x2, @x3, @x4, @x5\n\u00a0\n\tSELECT\t@q = SCOPE_IDENTITY()\n\u00a0\n\tIF @k <= 0\n\tBEGIN\n\t\tEXEC\t@res1 = dbo.LAMBDA_EXEC @x4\n\t\tEXEC\t@res2 = dbo.LAMBDA_EXEC @x5\n\t\tRETURN\t@res1 + @res2\n\tEND\n\tELSE\n\tBEGIN\n\t\tEXEC\tdbo.LAMBDA_B @name_out = @Name OUTPUT, @q = @q\n\t\tEXEC\t@res1 = @Name\n\t\tRETURN\t@res1\n\tEND\n\u00a0\nGO\n\u00a0\n-------------------------------------------------------------\n-- Test script\n-------------------------------------------------------------\n\u00a0\nDECLARE\t@x1 INT\n,\t@x2 INT\n,\t@x0 INT\n,\t@x4 INT\n,\t@x5 INT\n,\t@K INT\n,\t@retval INT\n\u00a0\n-------------------------------------------------------------\n-- Create wrapped integers to pass as arguments\n-------------------------------------------------------------\nEXEC\t@x1 = LAMBDA_WRAP_INTEGER 1\nEXEC\t@x2 = LAMBDA_WRAP_INTEGER -1\nEXEC\t@x0 = LAMBDA_WRAP_INTEGER 0\n\u00a0\n-------------------------------------------------------------\n-- Argument storage table\n-------------------------------------------------------------\nCREATE TABLE #t_args (\n\tk INT\n,\tx1 INT\n,\tx2 INT\n,\tx3 INT\n,\tx4 INT\n,\tx5 INT\n,\ti INT IDENTITY\n)\n\u00a0\nSELECT\t@K = 1\n\u00a0\n-- Anything above 5 blows up the stack\nWHILE \t@K <= 4\nBEGIN\n\tEXEC\t@retval = dbo.LAMBDA_A @K, @x1, @x2, @x2, @x1, @x0\n\tPRINT\t'For k=' + CAST(@K AS VARCHAR) + ', result=' + CAST(@retval AS VARCHAR)\n\u00a0\n\tSELECT\t@K = @K + 1\nEND\n\u00a0\n\u00a0", "input": ""}, {"instruction": "Task\n\nEncode a string using an MD5 algorithm. \u00a0 The algorithm can be found on \u00a0 Wikipedia.\n\n\n\nOptionally, validate your implementation by running all of the test values in \u00a0 IETF RFC (1321) \u00a0 for MD5.\n\nAdditionally, \u00a0 RFC 1321 \u00a0 provides more precise information on the algorithm than the Wikipedia article.\n\n\n\n Warning: \u00a0 MD5 has known weaknesses, including collisions and forged signatures. \u00a0 Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.\n\nIf the solution on this page is a library solution, see \u00a0 MD5/Implementation \u00a0 for an implementation from scratch.\n\n\n\n", "output": "SELECT MD5('The quick brown fox jumped over the lazy dog\\'s back')", "input": ""}, {"instruction": "Mandelbrot set\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\n\n\nTask\n\nGenerate and draw the Mandelbrot set.\n\n\n\nNote that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .\n\n\n\n", "output": "\u00a0\n-- Table to contain all the data points\nCREATE TABLE points (\n c_re DOUBLE,\n c_im DOUBLE,\n z_re DOUBLE DEFAULT 0,\n z_im DOUBLE DEFAULT 0,\n znew_re DOUBLE DEFAULT 0,\n znew_im DOUBLE DEFAULT 0,\n steps INT DEFAULT 0,\n active CHAR DEFAULT 1\n);\n\u00a0\nDELIMITER |\n\u00a0\n-- Iterate over all the points in the table 'points'\nCREATE PROCEDURE itrt (IN n INT)\nBEGIN\n label: LOOP\n UPDATE points\n SET\n znew_re=POWER(z_re,2)-POWER(z_im,2)+c_re,\n znew_im=2*z_re*z_im+c_im,\n steps=steps+1\n WHERE active=1;\n UPDATE points SET\n z_re=znew_re,\n z_im=znew_im,\n active=IF(POWER(z_re,2)+POWER(z_im,2)>4,0,1)\n WHERE active=1;\n SET n = n - 1;\n IF n > 0 THEN\n ITERATE label;\n END IF;\n LEAVE label;\n END LOOP label;\nEND|\n\u00a0\n-- Populate the table 'points'\nCREATE PROCEDURE populate (\n r_min DOUBLE,\n r_max DOUBLE,\n r_step DOUBLE,\n i_min DOUBLE,\n i_max DOUBLE,\n i_step DOUBLE)\nBEGIN\n DELETE FROM points;\n SET @rl = r_min;\n SET @a = 0;\n rloop: LOOP\n SET @im = i_min;\n SET @b = 0;\n iloop: LOOP\n INSERT INTO points (c_re, c_im)\n VALUES (@rl, @im);\n SET @b=@b+1;\n SET @im=i_min + @b * i_step;\n IF @im < i_max THEN\n ITERATE iloop;\n END IF;\n LEAVE iloop;\n END LOOP iloop;\n SET @a=@a+1;\n SET @rl=r_min + @a * r_step;\n IF @rl < r_max THEN\n ITERATE rloop;\n END IF;\n LEAVE rloop;\n END LOOP rloop;\nEND|\n\u00a0\nDELIMITER ;\n\u00a0\n-- Choose size and resolution of graph\n-- R_min, R_max, R_step, I_min, I_max, I_step\nCALL populate( -2.5, 1.5, 0.005, -2, 2, 0.005 );\n\u00a0\n-- Calculate 50 iterations\nCALL itrt( 50 );\n\u00a0\n-- Create the image (/tmp/image.ppm)\n-- Note, MySQL will not over-write an existing file and you may need\n-- administrator access to delete or move it\nSELECT @xmax:=COUNT(c_re) INTO @xmax FROM points GROUP BY c_im LIMIT 1;\nSELECT @ymax:=COUNT(c_im) INTO @ymax FROM points GROUP BY c_re LIMIT 1;\nSET group_concat_max_len=11*@xmax*@ymax;\nSELECT\n 'P3', @xmax, @ymax, 200,\n GROUP_CONCAT(\n CONCAT(\n IF( active=1, 0, 55+MOD(steps, 200) ), ' ',\n IF( active=1, 0, 55+MOD(POWER(steps,3), 200) ), ' ',\n IF( active=1, 0, 55+MOD(POWER(steps,2), 200) ) )\n ORDER BY c_im ASC, c_re ASC SEPARATOR ' ' )\n INTO OUTFILE '/tmp/image.ppm'\n FROM points;\n\u00a0", "input": ""}, {"instruction": "Task\n\nMultiply two matrices together.\n\nThey can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.\n\n\n\n", "output": "CREATE TABLE a (x INTEGER, y INTEGER, e REAL);\nCREATE TABLE b (x INTEGER, y INTEGER, e REAL);\n\u00a0\n-- test data\n-- A is a 2x2 matrix\nINSERT INTO a VALUES(0,0,1); INSERT INTO a VALUES(1,0,2);\nINSERT INTO a VALUES(0,1,3); INSERT INTO a VALUES(1,1,4);\n\u00a0\n-- B is a 2x3 matrix\nINSERT INTO b VALUES(0,0,-3); INSERT INTO b VALUES(1,0,-8); INSERT INTO b VALUES(2,0,3);\nINSERT INTO b VALUES(0,1,-2); INSERT INTO b VALUES(1,1, 1); INSERT INTO b VALUES(2,1,4);\n\u00a0\n-- C is 2x2 * 2x3 so will be a 2x3 matrix\nSELECT rhs.x, lhs.y, (SELECT SUM(a.e*b.e) FROM a, b\n WHERE a.y = lhs.y\n AND b.x = rhs.x\n AND a.x = b.y)\n INTO TABLE c\n FROM a AS lhs, b AS rhs\n WHERE lhs.x = 0 AND rhs.y = 0;", "input": ""}, {"instruction": "Ludic numbers \u00a0 are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.\n\nThe first ludic number is \u00a0 1.\n\nTo generate succeeding ludic numbers create an array of increasing integers starting from \u00a0 2.\n\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...\n(Loop)\n\n Take the first member of the resultant array as the next ludic number \u00a0 2.\n Remove every \u00a0 2nd \u00a0 indexed item from the array (including the first).\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...\n (Unrolling a few loops...)\n Take the first member of the resultant array as the next ludic number \u00a0 3.\n Remove every \u00a0 3rd \u00a0 indexed item from the array (including the first).\n3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...\n Take the first member of the resultant array as the next ludic number \u00a0 5.\n Remove every \u00a0 5th \u00a0 indexed item from the array (including the first).\n5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...\n Take the first member of the resultant array as the next ludic number \u00a0 7.\n Remove every \u00a0 7th \u00a0 indexed item from the array (including the first).\n7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...\n ... \n Take the first member of the current array as the next ludic number \u00a0 L.\n Remove every \u00a0 Lth \u00a0 indexed item from the array (including the first).\n ... \n\n\nTask\n\n Generate and show here the first 25 ludic numbers.\n How many ludic numbers are there less than or equal to 1000?\n Show the 2000..2005th ludic numbers.\n\n\nStretch goal\n\nShow all triplets of ludic numbers < 250.\n\n A triplet is any three numbers \u00a0 \u00a0 \n\n\n\nx\n,\n\n\n{\\displaystyle x,}\n\n \u00a0 \n\n\n\nx\n+\n2\n,\n\n\n{\\displaystyle x+2,}\n\n \u00a0 \n\n\n\nx\n+\n6\n\n\n{\\displaystyle x+6}\n\n \u00a0 \u00a0 where all three numbers are also ludic numbers. \n\n", "output": "SET SERVEROUTPUT ON\nDECLARE\n c_limit CONSTANT PLS_INTEGER := 25000;\n TYPE t_nums IS TABLE OF PLS_INTEGER INDEX BY PLS_INTEGER;\n v_nums t_nums;\n v_ludic t_nums;\n v_count_ludic PLS_INTEGER;\n v_count_pos PLS_INTEGER;\n v_pos PLS_INTEGER;\n v_next_ludic PLS_INTEGER;\n\u00a0\n FUNCTION is_ludic(p_num PLS_INTEGER) RETURN BOOLEAN IS\n BEGIN\n FOR i IN 1..v_ludic.COUNT LOOP\n EXIT WHEN v_ludic(i) > p_num;\n IF v_ludic(i) = p_num THEN\n RETURN TRUE;\n END IF;\n END LOOP;\n RETURN FALSE;\n END;\n\u00a0\nBEGIN\n FOR i IN 1..c_limit LOOP\n v_nums(i) := i;\n END LOOP;\n\u00a0\n v_count_ludic := 1;\n v_next_ludic := 1;\n v_ludic(v_count_ludic) := v_next_ludic;\n v_nums.DELETE(1);\n\u00a0\n WHILE v_nums.COUNT > 0 LOOP\n v_pos := v_nums.FIRST;\n v_next_ludic := v_nums(v_pos);\n v_count_ludic := v_count_ludic + 1;\n v_ludic(v_count_ludic) := v_next_ludic;\n v_count_pos := 0;\n WHILE v_pos IS NOT NULL LOOP\n IF MOD(v_count_pos, v_next_ludic) = 0 THEN\n v_nums.DELETE(v_pos);\n END IF;\n v_pos := v_nums.NEXT(v_pos);\n v_count_pos := v_count_pos + 1;\n END LOOP;\n END LOOP;\n\u00a0\n DBMS_OUTPUT.put_line('Generate and show here the first 25 ludic numbers.');\n FOR i IN 1..25 LOOP\n DBMS_OUTPUT.put(v_ludic(i) || ' ');\n END LOOP;\n DBMS_OUTPUT.put_line('');\n\u00a0\n DBMS_OUTPUT.put_line('How many ludic numbers are there less than or equal to 1000?');\n v_count_ludic := 0;\n FOR i IN 1..v_ludic.COUNT LOOP\n EXIT WHEN v_ludic(i) > 1000;\n v_count_ludic := v_count_ludic + 1;\n END LOOP;\n DBMS_OUTPUT.put_line(v_count_ludic);\n\u00a0\n DBMS_OUTPUT.put_line('Show the 2000..2005''th ludic numbers.');\n FOR i IN 2000..2005 LOOP\n DBMS_OUTPUT.put(v_ludic(i) || ' ');\n END LOOP;\n DBMS_OUTPUT.put_line('');\n\u00a0\n DBMS_OUTPUT.put_line('A triplet is any three numbers x, x + 2, x + 6 where all three numbers are also ludic numbers.');\n DBMS_OUTPUT.put_line('Show all triplets of ludic numbers < 250 (Stretch goal)');\n FOR i IN 1..v_ludic.COUNT LOOP\n EXIT WHEN (v_ludic(i)+6) >= 250;\n IF is_ludic(v_ludic(i)+2) AND is_ludic(v_ludic(i)+6) THEN\n DBMS_OUTPUT.put_line(v_ludic(i) || ', ' || (v_ludic(i)+2) || ', ' || (v_ludic(i)+6));\n END IF;\n END LOOP;\n\u00a0\nEND;\n/\n\u00a0", "input": ""}, {"instruction": "Task\n\nStart an integer value at \u00a0 1024.\n\nLoop while it is greater than zero.\n\nPrint the value (with a newline) and divide it by two each time through the loop.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreachbas\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\nSET serveroutput ON\nDECLARE\n n NUMBER := 1024;\nBEGIN\n WHILE n > 0 LOOP\n DBMS_OUTPUT.put_line(n);\n n := TRUNC(n / 2);\n END LOOP;\nEND;\n/\n\u00a0", "input": ""}, {"instruction": "The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.\n\nThose companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:\n\n Reverse the order of the digits in the number.\n Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1\n Taking the second, fourth ... and every other even digit in the reversed digits:\n Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits\n Sum the partial sums of the even digits to form s2\n If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.\n\n\nFor example, if the trial number is 49927398716:\n\nReverse the digits:\n 61789372994\nSum the odd digits:\n 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1\nThe even digits:\n 1, 8, 3, 2, 9\n Two times each even digit:\n 2, 16, 6, 4, 18\n Sum the digits of each multiplication:\n 2, 7, 6, 4, 9\n Sum the last:\n 2 + 7 + 6 + 4 + 9 = 28 = s2\n\ns1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test\n\n\nTask\n\nWrite a function/method/procedure/subroutine that will validate a number with the Luhn test, and\n\nuse it to validate the following numbers:\n\n 49927398716\n 49927398717\n 1234567812345678\n 1234567812345670\n\n\n\nRelated tasks\n\n \u00a0 SEDOL\n \u00a0 ISIN\n\n", "output": "FUNCTION algoLuhn ( p_numeroVerif VARCHAR2 )\n RETURN NUMBER\n IS\n i NUMBER;\n v_NBi SMALLINT;\n v_retour SMALLINT;\n v_somme NUMBER := 0;\n v_nbCar NUMBER;\n\u00a0\n BEGIN \n v_nbCar := LENGTH(p_numeroVerif); \n\u00a0\n FOR i IN 1..v_nbCar\n LOOP\n v_NBi := TO_NUMBER(SUBSTR(p_numeroVerif,v_nbCar+1-i,1));\n\u00a0\n v_somme := v_somme\n + MOD(i,2) * v_NBi\n + MOD(i+1,2) * SIGN(-SIGN(v_Nbi-4)+1) * (2*v_NBi)\n + MOD(i+1,2) * SIGN( SIGN(v_Nbi-5)+1) * (2*v_NBi-9);\n\u00a0\n END LOOP;\n\u00a0\n v_retour := SIGN(MOD(v_somme,10));\n\u00a0\n RETURN v_retour;\n\u00a0\n EXCEPTION\n WHEN OTHERS\n THEN\n RETURN 1;\n\u00a0\n END algoLuhn;", "input": ""}, {"instruction": "Task\n\nPrint out \u00a0 \u00a0 \u00a0 SPAM \u00a0 \u00a0 \u00a0 followed by a \u00a0 newline \u00a0 in an infinite loop.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON@\n\u00a0\nBEGIN\n DECLARE I SMALLINT DEFAULT 1;\n WHILE (I = I) DO\n CALL DBMS_OUTPUT.PUT_LINE('SPAM');\n END WHILE;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nPrint out \u00a0 \u00a0 \u00a0 SPAM \u00a0 \u00a0 \u00a0 followed by a \u00a0 newline \u00a0 in an infinite loop.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "WHILE 1=1 BEGIN\n PRINT \"SPAM\"\nEND", "input": ""}, {"instruction": "Task\n\nStart an integer value at \u00a0 1024.\n\nLoop while it is greater than zero.\n\nPrint the value (with a newline) and divide it by two each time through the loop.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreachbas\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE I SMALLINT DEFAULT 1024;\n\u00a0\n Loop: WHILE (I > 0) DO\n CALL DBMS_OUTPUT.PUT_LINE(I);\n SET I = I / 2;\n END WHILE Loop;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nStart an integer value at \u00a0 1024.\n\nLoop while it is greater than zero.\n\nPrint the value (with a newline) and divide it by two each time through the loop.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreachbas\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\nDECLARE @i INT = 1024;\nWHILE @i >0\nBEGIN\n PRINT @i;\n SET @i = @i / 2;\nEND;\n\u00a0", "input": ""}, {"instruction": "The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.\n\nThose companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:\n\n Reverse the order of the digits in the number.\n Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1\n Taking the second, fourth ... and every other even digit in the reversed digits:\n Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits\n Sum the partial sums of the even digits to form s2\n If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.\n\n\nFor example, if the trial number is 49927398716:\n\nReverse the digits:\n 61789372994\nSum the odd digits:\n 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1\nThe even digits:\n 1, 8, 3, 2, 9\n Two times each even digit:\n 2, 16, 6, 4, 18\n Sum the digits of each multiplication:\n 2, 7, 6, 4, 9\n Sum the last:\n 2 + 7 + 6 + 4 + 9 = 28 = s2\n\ns1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test\n\n\nTask\n\nWrite a function/method/procedure/subroutine that will validate a number with the Luhn test, and\n\nuse it to validate the following numbers:\n\n 49927398716\n 49927398717\n 1234567812345678\n 1234567812345670\n\n\n\nRelated tasks\n\n \u00a0 SEDOL\n \u00a0 ISIN\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nCREATE OR REPLACE FUNCTION LUHN_TEST (\n IN NUMBER VARCHAR(24)\n ) RETURNS SMALLINT\n --) RETURNS BOOLEAN\n BEGIN\n DECLARE TYPE CARD_NUMBER AS VARCHAR(1) ARRAY [24];\n DECLARE LENGTH SMALLINT;\n DECLARE REVERSE CARD_NUMBER;\n DECLARE I SMALLINT;\n DECLARE POS SMALLINT;\n DECLARE S1 SMALLINT;\n DECLARE S2 SMALLINT;\n DECLARE TEMP SMALLINT;\n DECLARE RET SMALLINT;\n --DECLARE RET BOOLEAN;\n DECLARE INVALID_CHAR CONDITION FOR SQLSTATE 'LUHN1';\n\u00a0\n -- Reverse the order of the digits in the number.\n SET LENGTH = LENGTH(NUMBER);\n SET I = 1;\n WHILE (I <= LENGTH) DO\n SET POS = LENGTH - I + 1;\n SET REVERSE[POS] = SUBSTR(NUMBER, I, 1);\n IF (ASCII(REVERSE[POS]) < 48 OR 57 < ASCII(REVERSE[POS])) THEN\n SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Invalid character, not a digit';\n END IF;\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1\n SET S1 = 0;\n SET I = 1;\n WHILE (I <= LENGTH) DO\n IF (MOD(I, 2) = 1) THEN\n SET S1 = S1 + REVERSE[I];\n END IF;\n -- CALL DBMS_OUTPUT.PUT_LINE('I ' || I || ', S1 ' || S1 || ', val ' || REVERSE[I]);\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- Taking the second, fourth ... and every other even digit in the reversed digits:\n SET S2 = 0;\n SET TEMP = 0;\n SET I = 1;\n WHILE (I <= LENGTH) DO\n IF (MOD(I, 2) = 0) THEN\n -- Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits\n SET TEMP = REVERSE[I] * 2;\n IF (TEMP > 9) THEN\n SET TEMP = (TEMP / 10) + (MOD(TEMP, 10));\n END IF;\n -- Sum the partial sums of the even digits to form s2\n SET S2 = S2 + TEMP;\n END IF;\n -- CALL DBMS_OUTPUT.PUT_LINE('I ' || I || ', S2 ' || S2 || ', TEMP ' || TEMP || ' val ' || REVERSE[I]);\n SET I = I + 1;\n END WHILE;\n\u00a0\n -- If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.\n SET RET = 1;\n --SET RET = FALSE;\n SET TEMP = S1 + S2;\n IF (MOD(TEMP, 10) = 0) THEN\n SET RET = 0;\n --SET RET = TRUE;\n CALL DBMS_OUTPUT.PUT_LINE('It is a valid number ' || S1 || '+' || S2 || '=' || TEMP);\n ELSE\n CALL DBMS_OUTPUT.PUT_LINE('It is NOT a valid number ' || S1 || '+' || S2 || '=' || TEMP);\n END IF;\n RETURN RET;\n END\n@\n\u00a0", "input": ""}, {"instruction": "The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.\n\nThose companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:\n\n Reverse the order of the digits in the number.\n Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1\n Taking the second, fourth ... and every other even digit in the reversed digits:\n Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits\n Sum the partial sums of the even digits to form s2\n If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.\n\n\nFor example, if the trial number is 49927398716:\n\nReverse the digits:\n 61789372994\nSum the odd digits:\n 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1\nThe even digits:\n 1, 8, 3, 2, 9\n Two times each even digit:\n 2, 16, 6, 4, 18\n Sum the digits of each multiplication:\n 2, 7, 6, 4, 9\n Sum the last:\n 2 + 7 + 6 + 4 + 9 = 28 = s2\n\ns1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test\n\n\nTask\n\nWrite a function/method/procedure/subroutine that will validate a number with the Luhn test, and\n\nuse it to validate the following numbers:\n\n 49927398716\n 49927398717\n 1234567812345678\n 1234567812345670\n\n\n\nRelated tasks\n\n \u00a0 SEDOL\n \u00a0 ISIN\n\n", "output": "\u00a0\nCREATE FUNCTION dbo._CreditCardNumCheck( @strCCNum VarChar(40) )\nRETURNS VarChar(7)\nAS\nBEGIN\n\tDECLARE @string\t\t\tVarChar(40) = REVERSE(@strCCNum); -- usage: set once, never changed\n\tDECLARE @strS2Values\t\tVarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values\n\tDECLARE @table\t\t\tTABLE (ID INT, Value INT, S_Value INT); -- ID=digit position. S_Value is used for SUM().\n\tDECLARE @p\t\t\tINT = 0; -- loop counter: position in string\n\t-- Convert the reversed string's digits into rows in a table variable, S_Values to be updated afterwards\n\tWHILE @p < LEN(@string)\n\t\tBEGIN\n\t\t\tSET @p = @p+1;\n\t\t\tINSERT INTO @table (ID,Value,S_Value) VALUES (@p, CONVERT(INT,SUBSTRING(@string,@p,1)), 0);\n\t\tEND\n\t-- Update S_Value column\u00a0: the digit's value to be summed (for even-positioned digits this is mapped via @strS2Values)\n\tUPDATE @table SET S_Value = CASE WHEN ID\u00a0% 2 = 1 THEN Value ELSE CONVERT(INT,SUBSTRING(@strS2Values,Value+1,1)) END\n\t-- If the SUM of S_Values ends in 0 (modulo 10 = 0) then the CC Number is valid\n\tRETURN CASE WHEN (SELECT SUM(S_Value) FROM @table)\u00a0% 10 = 0 THEN 'Valid' ELSE 'Invalid' END\nEND\n\u00a0", "input": ""}, {"instruction": "Task\n\nShow the following output using one loop.\n\n1, 2, 3, 4, 5\n6, 7, 8, 9, 10\n\n\n\nTry to achieve the result by forcing the next iteration within the loop\nupon a specific condition, if your language allows it.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE I SMALLINT DEFAULT 1;\n\u00a0\n Loop: WHILE (I <= 10) DO\n CALL DBMS_OUTPUT.PUT(I);\n SET I = I + 1;\n IF (MOD(I - 1, 5) = 0) THEN\n CALL DBMS_OUTPUT.PUT_LINE(' ');\n ITERATE Loop;\n END IF;\n CALL DBMS_OUTPUT.PUT(', ');\n END WHILE Loop;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nShow literal specification of characters and strings.\n\nIf supported, show how the following work:\n\n \u00a0 verbatim strings \u00a0 (quotes where escape sequences are quoted literally)\n \u00a0 here-strings \u00a0 \n\n\nAlso, discuss which quotes expand variables.\n\n\n\nRelated tasks\n \n \u00a0 Special characters\n \u00a0 Here document\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "SELECT 'The boy said ''hello''.';", "input": ""}, {"instruction": "Task\n\nShow the following output using one loop.\n\n1, 2, 3, 4, 5\n6, 7, 8, 9, 10\n\n\n\nTry to achieve the result by forcing the next iteration within the loop\nupon a specific condition, if your language allows it.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n \u00a0 Loops/Wrong ranges\n\n", "output": "\u00a0\nDECLARE @i INT = 0;\nDECLARE @str VarChar(40) = '';\nWHILE @i<10\n BEGIN\n SET @i = @i + 1;\n SET @str = @str + CONVERT(varchar(2),@i);\n IF @i\u00a0% 5 = 0\n BEGIN\n PRINT @str;\n SET @str =''\n CONTINUE;\n END\n SET @str = @str +', ';\n END;\n\u00a0", "input": ""}, {"instruction": "Task\n\nShow a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).\n\nIf a number is 10, stop the loop after printing it, and do not generate any further numbers.\n\nOtherwise, generate and print a second random number before restarting the loop.\n\nIf the number 10 is never generated as the first number in a loop, loop forever.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON@\n\u00a0\nBEGIN\n DECLARE VAL INTEGER;\n LOOP: WHILE (TRUE = TRUE) DO\n SET VAL = INTEGER(RAND() * 20);\n CALL DBMS_OUTPUT.PUT_LINE(VAL);\n IF (VAL = 10) THEN\n LEAVE LOOP;\n END IF;\n SET VAL = INTEGER(RAND() * 20);\n CALL DBMS_OUTPUT.PUT_LINE(VAL);\n END WHILE LOOP;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nShow a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).\n\nIf a number is 10, stop the loop after printing it, and do not generate any further numbers.\n\nOtherwise, generate and print a second random number before restarting the loop.\n\nIf the number 10 is never generated as the first number in a loop, loop forever.\n\n\n\nRelated tasks\n\n \u00a0 Loop over multiple arrays simultaneously\n \u00a0 Loops/Break\n \u00a0 Loops/Continue\n \u00a0 Loops/Do-while\n \u00a0 Loops/Downward for\n \u00a0 Loops/For\n \u00a0 Loops/For with a specified step\n \u00a0 Loops/Foreach\n \u00a0 Loops/Increment loop index within loop body\n \u00a0 Loops/Infinite\n \u00a0 Loops/N plus one half\n \u00a0 Loops/Nested\n \u00a0 Loops/While\n \u00a0 Loops/with multiple ranges\n\n", "output": "\u00a0\nDECLARE @i INT;\nWHILE 1=1\nBEGIN\n SET @i = ABS(CHECKSUM(NewId()))\u00a0% 20;\n PRINT @i;\n IF @i=10 BREAK;\n PRINT ABS(CHECKSUM(NewId()))\u00a0% 20;\nEND;\n\u00a0", "input": ""}, {"instruction": "The \u00a0 Look and say sequence \u00a0 is a recursively defined sequence of numbers studied most notably by \u00a0 John Conway.\n\n\n\nThe \u00a0 look-and-say sequence \u00a0 is also known as the \u00a0 Morris Number Sequence, \u00a0 after cryptographer Robert Morris, \u00a0 and the puzzle \u00a0 What is the next number in the sequence 1, \u00a0 11, \u00a0 21, \u00a0 1211, \u00a0 111221? \u00a0 is sometimes referred to as the Cuckoo's Egg, \u00a0 from a description of Morris in Clifford Stoll's book \u00a0 The Cuckoo's Egg.\n\n\nSequence Definition\n\n Take a decimal number\n Look at the number, visually grouping consecutive runs of the same digit.\n Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.\n This becomes the next number of the sequence.\n\nAn example:\n\n Starting with the number 1, \u00a0 you have one 1 which produces 11\n Starting with 11, \u00a0 you have two 1's. \u00a0 I.E.: \u00a0 21\n Starting with 21, \u00a0 you have one 2, then one 1. \u00a0 I.E.: \u00a0 (12)(11) which becomes 1211\n Starting with 1211, \u00a0 you have one 1, one 2, then two 1's. \u00a0 I.E.: \u00a0 (11)(12)(21) which becomes 111221\n\n\nTask\n\nWrite a program to generate successive members of the look-and-say sequence.\n\n\n\nRelated tasks\n\n \u00a0 Fours is the number of letters in the ...\n \u00a0 Number names\n \u00a0 Self-describing numbers\n \u00a0 Self-referential sequence\n \u00a0 Spelling of ordinal numbers\n\n\nSee also\n\n \u00a0 Look-and-Say Numbers (feat John Conway), A Numberphile Video.\n \u00a0 This task is related to, and an application of, the Run-length encoding task.\n \u00a0 Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.\n\n", "output": "DROP VIEW delta;\nCREATE VIEW delta AS\n SELECT sequence1.v AS x,\n (sequence1.v<>sequence2.v)*sequence1.c AS v,\n sequence1.c AS c\n FROM SEQUENCE AS sequence1,\n SEQUENCE AS sequence2\n WHERE sequence1.c = sequence2.c+1;\n\u00a0\nDROP VIEW rle0;\nCREATE VIEW rle0 AS\n SELECT delta2.x AS x,\n SUM(delta2.v) AS v,\n delta2.c AS c\n FROM delta AS delta1,\n delta AS delta2\n WHERE delta1.c >= delta2.c\n GROUP BY delta1.c;\n\u00a0\nDROP VIEW rle1;\nCREATE VIEW rle1 AS\n SELECT SUM(x)/x AS a,\n x AS b,\n c AS c\n FROM rle0\n GROUP BY v;\n\u00a0\nDROP VIEW rle2;\nCREATE VIEW rle2 AS\n SELECT a AS v, 1 AS o, 2*c+0 AS c FROM rle1 UNION\n SELECT b AS v, 1 AS o, 2*c+1 AS c FROM rle1;\n\u00a0\nDROP VIEW normed;\nCREATE VIEW normed AS\n SELECT r1.v AS v, SUM(r2.o) AS c\n FROM rle2 AS r1,\n rle2 AS r2\n WHERE r1.c >= r2.c\n GROUP BY r1.c;\n\u00a0\nDROP TABLE rle;\nCREATE TABLE rle(v INT, c INT);\nINSERT INTO rle SELECT * FROM normed ORDER BY c;\n\u00a0\nDELETE FROM SEQUENCE;\nINSERT INTO SEQUENCE VALUES(-1,0);\nINSERT INTO SEQUENCE SELECT * FROM rle;", "input": ""}, {"instruction": "The \u00a0 Look and say sequence \u00a0 is a recursively defined sequence of numbers studied most notably by \u00a0 John Conway.\n\n\n\nThe \u00a0 look-and-say sequence \u00a0 is also known as the \u00a0 Morris Number Sequence, \u00a0 after cryptographer Robert Morris, \u00a0 and the puzzle \u00a0 What is the next number in the sequence 1, \u00a0 11, \u00a0 21, \u00a0 1211, \u00a0 111221? \u00a0 is sometimes referred to as the Cuckoo's Egg, \u00a0 from a description of Morris in Clifford Stoll's book \u00a0 The Cuckoo's Egg.\n\n\nSequence Definition\n\n Take a decimal number\n Look at the number, visually grouping consecutive runs of the same digit.\n Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.\n This becomes the next number of the sequence.\n\nAn example:\n\n Starting with the number 1, \u00a0 you have one 1 which produces 11\n Starting with 11, \u00a0 you have two 1's. \u00a0 I.E.: \u00a0 21\n Starting with 21, \u00a0 you have one 2, then one 1. \u00a0 I.E.: \u00a0 (12)(11) which becomes 1211\n Starting with 1211, \u00a0 you have one 1, one 2, then two 1's. \u00a0 I.E.: \u00a0 (11)(12)(21) which becomes 111221\n\n\nTask\n\nWrite a program to generate successive members of the look-and-say sequence.\n\n\n\nRelated tasks\n\n \u00a0 Fours is the number of letters in the ...\n \u00a0 Number names\n \u00a0 Self-describing numbers\n \u00a0 Self-referential sequence\n \u00a0 Spelling of ordinal numbers\n\n\nSee also\n\n \u00a0 Look-and-Say Numbers (feat John Conway), A Numberphile Video.\n \u00a0 This task is related to, and an application of, the Run-length encoding task.\n \u00a0 Sequence A005150 on The On-Line Encyclopedia of Integer Sequences.\n\n", "output": "\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE NMBR VARCHAR(100) DEFAULT '1';\n DECLARE J SMALLINT DEFAULT 1;\n\u00a0\n CALL DBMS_OUTPUT.PUT_LINE(NMBR);\n WHILE (J < 10) DO\n BEGIN\n DECLARE I SMALLINT;\n DECLARE SIZE SMALLINT;\n DECLARE ACTUAL CHAR(1);\n DECLARE REPEAT CHAR(1);\n DECLARE RESULT VARCHAR(100);\n DECLARE TIMES SMALLINT;\n\u00a0\n SET REPEAT = SUBSTR(NMBR, 1, 1);\n SET NMBR = SUBSTR(NMBR, 2) || ' ';\n SET TIMES = 1;\n SET I = 1;\n SET SIZE = LENGTH(NMBR);\n\u00a0\n WHILE (I <= SIZE) DO\n SET ACTUAL = SUBSTR(NMBR, I, 1);\n IF (ACTUAL <> REPEAT) THEN\n SET RESULT = COALESCE(RESULT, '') || TIMES || '' || REPEAT;\n SET TIMES = 1;\n SET REPEAT = ACTUAL;\n ELSE\n SET TIMES = TIMES + 1;\n END IF;\n SET I = I + 1;\n END WHILE;\n\u00a0\n CALL DBMS_OUTPUT.PUT_LINE(RESULT);\n SET NMBR = RESULT;\n END\u00a0;\n SET J = J + 1;\n END WHILE;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nWrite a program or a script that returns the date of the last Fridays of each month of a given year.\n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\n\nExample of an expected output:\n\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n\nRelated tasks\n Five weekends\n Day of the week\n Find the last Sunday of each month\n\n", "output": "\u00a0\nSELECT to_char( next_day( last_day( add_months( to_date(\n \u00a0:yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday\nFROM dual\nCONNECT BY level <= 12;\n\u00a0", "input": ""}, {"instruction": "Imperative programs\nconditional structures\nloops\nlocal jumps\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.\nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes.\nYou may also defer to more specific tasks, like Exceptions or Generator.\nThis task provides a \"grab bag\" for several types of jumps. There are non-local jumps across function calls, or long jumps to anywhere within a program. Anywhere means not only to the tops of functions!\n\n Some languages can go to any global label in a program.\n Some languages can break multiple function calls, also known as unwinding the call stack.\n Some languages can save a continuation. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike.\nA simple goto never touches the call stack.\nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n\nTask\n\nUse your language to demonstrate the various types of jumps that it supports.\n\nBecause the possibilities vary by language, this task is not specific.\nYou have the freedom to use these jumps for different purposes.\nYou may also defer to more specific tasks, like Exceptions or Generator.\n\n\n\n", "output": "DECLARE\n i number\u00a0:= 5;\n divide_by_zero EXCEPTION;\n PRAGMA exception_init(divide_by_zero, -20000);\nBEGIN\n DBMS_OUTPUT.put_line( 'startLoop' );\n <<startLoop>>\n BEGIN \n if i = 0 then\n raise divide_by_zero;\n end if;\n DBMS_OUTPUT.put_line( 100/i );\n i\u00a0:= i - 1;\n GOTO startLoop;\n EXCEPTION\n WHEN divide_by_zero THEN\n DBMS_OUTPUT.put_line( 'Oops!' );\n GOTO finally;\n END;\n <<endLoop>>\n DBMS_OUTPUT.put_line( 'endLoop' ); \n\u00a0\n <<finally>>\n DBMS_OUTPUT.put_line( 'Finally' );\nEND;\n/", "input": ""}, {"instruction": "A tourist wants to make a good trip at the weekend with his friends.\n\nThey will go to the mountains to see the wonders of nature, so he needs to pack well for the trip.\n\nHe has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, \u00a0 and it will have to last the whole day.\n\nHe creates a list of what he wants to bring for the trip but the total weight of all items is too much.\n\nHe then decides to add columns to his initial list detailing their weights and a numerical value representing how important the item is for the trip.\n\n\n\nHere is the list:\n\n\n Table of potential knapsack items\n\n\n item \n weight (dag) \n value\n\n\n map \n 9 \n 150\n\n\n compass \n 13 \n 35\n\n\n water \n 153 \n 200\n\n\n sandwich \n 50 \n 160\n\n\n glucose \n 15 \n 60\n\n\n tin \n 68 \n 45\n\n\n banana \n 27 \n 60\n\n\n apple \n 39 \n 40\n\n\n cheese \n 23 \n 30\n\n\n beer \n 52 \n 10\n\n\n suntan cream \n 11 \n 70\n\n\n camera \n 32 \n 30\n\n\n T-shirt \n 24 \n 15\n\n\n trousers \n 48 \n 10\n\n\n umbrella \n 73 \n 40\n\n\n waterproof trousers \n 42 \n 70\n\n\n waterproof overclothes \n 43 \n 75\n\n\n note-case \n 22 \n 80\n\n\n sunglasses \n 7 \n 20\n\n\n towel \n 18 \n 12\n\n\n socks \n 4 \n 50\n\n\n book \n 30 \n 10\n\n\n knapsack \n \u2264400 dag \n\u00a0?\n\n\n\nThe tourist can choose to take any combination of items from the list,\nbut only one of each item is available.\n\nHe may not cut or diminish the items, so he can only take whole units of any item.\n\n\n\nTask\n\nShow which items the tourist can carry in his knapsack so that their total weight does not\nexceed 400 dag [4 kg], \u00a0 and their total value is maximized.\n\n[dag = decagram = 10 grams]\n\n\n\nRelated tasks\n\n \u00a0 Knapsack problem/Bounded\n \u00a0 Knapsack problem/Unbounded\n \u00a0 Knapsack problem/Continuous\n \u00a0 A* search algorithm\n\n", "output": "\u00a0\nWITH KnapsackItems (item, [weight], VALUE) AS\n(\n SELECT 'map',9, 150 \n UNION ALL SELECT 'compass',13, 35 \n UNION ALL SELECT 'water',153, 200 \n UNION ALL SELECT 'sandwich',50, 160 \n UNION ALL SELECT 'glucose',15, 60 \n UNION ALL SELECT 'tin',68, 45 \n UNION ALL SELECT 'banana',27, 60 \n UNION ALL SELECT 'apple',39, 40 \n UNION ALL SELECT 'cheese',23, 30 \n UNION ALL SELECT 'beer',52, 10 \n UNION ALL SELECT 'suntan cream',11, 70 \n UNION ALL SELECT 'camera',32, 30 \n UNION ALL SELECT 'T-shirt',24, 15 \n UNION ALL SELECT 'trousers',48, 10 \n UNION ALL SELECT 'umbrella',73, 40 \n UNION ALL SELECT 'waterproof trousers',42, 70 \n UNION ALL SELECT 'waterproof overclothes',43, 75 \n UNION ALL SELECT 'note-case',22, 80 \n UNION ALL SELECT 'sunglasses',7, 20 \n UNION ALL SELECT 'towel',18, 12 \n UNION ALL SELECT 'socks',4, 50 \n UNION ALL SELECT 'book',30, 10 \n)\nSELECT *\nINTO #KnapsackItems\nFROM KnapsackItems;\n\u00a0\nWITH UNIQUEnTuples (n, Tuples, ID, [weight], VALUE) AS (\n SELECT 1, CAST(item AS VARCHAR(8000)), item, [weight], VALUE\n FROM #KnapsackItems\n UNION ALL\n SELECT 1 + n.n, t.item + ',' + n.Tuples, item, n.[weight] + t.[weight], n.VALUE + t.VALUE\n FROM UNIQUEnTuples n \n CROSS APPLY (\n SELECT item, [weight], VALUE \n FROM #KnapsackItems t \n WHERE t.item < n.ID AND n.[weight] + t.[weight] < 400) t\n )\nSELECT TOP 5 *\nFROM UNIQUEnTuples\nORDER BY VALUE DESC, n, Tuples;\n\u00a0\nGO\nDROP TABLE #KnapsackItems;\n\u00a0", "input": ""}, {"instruction": "Jewels and stones\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nCreate a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\n\nNote that:\n\n Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a'\u00a0!= 'A'.\n The parameters do not need to have exactly the same names.\n Validating the arguments is unnecessary. \nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "-- See how many jewels are among the stones\nDECLARE @S VARCHAR(1024) \t=\t'AaBbCcAa'\n,\t@J VARCHAR(1024)\t=\t'aA';\n\u00a0\nDECLARE @SLEN\tINT = len(@S);\nDECLARE @JLEN\tINT = len(@J);\nDECLARE @TCNT\tINT = 0;\n\u00a0\nDECLARE @SPOS\tINT = 1;\t-- curr position in @S\nDECLARE @JPOS\tINT = 1;\t-- curr position in @J\nDECLARE @FCHR\tCHAR(1);\t-- char to find\n\u00a0\nwhile @JPOS <= @JLEN\nBEGIN\n\u00a0\n\tSET @FCHR = SUBSTRING(@J, @JPOS, 1);\n\u00a0\n\tSET @SPOS = 1;\n\u00a0\n\twhile @SPOS > 0 AND @SPOS <= @SLEN\n\tBEGIN\n\u00a0\n\t\tSET @SPOS = charindex(@FCHR, @S COLLATE Latin1_General_CS_AS, @SPOS);\n\u00a0\n\t\tIF @SPOS > 0 BEGIN\n\t\t\tSET @TCNT = @TCNT + 1;\n\t\t\tSET @SPOS = @SPOS + 1;\n\t\tEND\n\tEND\n\u00a0\n\tSET @JPOS = @JPOS + 1;\nEND\nprint 'J='+@J+' S='+@S+' TOTAL = '+CAST(@TCNT AS VARCHAR(8));\n\u00a0", "input": ""}, {"instruction": "Task\n\nFind the name of the host on which the routine is running.\n\n\n\n", "output": "SET serveroutput ON\nBEGIN\n DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME); \nEND;", "input": ""}, {"instruction": "Task\n\nFind the name of the host on which the routine is running.\n\n\n\n", "output": "\u00a0\nSELECT host_name FROM v$instance;\n\u00a0", "input": ""}, {"instruction": "Task\n\nFind the name of the host on which the routine is running.\n\n\n\n", "output": "\u00a0\nSELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO\n\u00a0", "input": ""}, {"instruction": "\nBasic Data Operation\n\nThis is a basic data operation. It represents a fundamental action on a basic data type.\nYou may see other such operations in the Basic Data Operations category, or:\n\n\nInteger Operations\nArithmetic |\nComparison\nBoolean Operations\nBitwise |\nLogical\nString Operations\nConcatenation |\nInterpolation |\nComparison |\nMatching\nMemory Operations\nPointers & references |\nAddresses\n\n\nGet two integers from the user.\n\nThen, \u00a0 display a message if the first integer is:\n\n \u00a0 less than, \n \u00a0 equal to, \u00a0 or \n \u00a0 greater than\nthe second integer.\n\n\n\nTest the condition \u00a0 for each case separately, \u00a0 so that \u00a0 all three comparison operators are used \u00a0 in the code.\n\n\n\nRelated task\n\n \u00a0 String comparison\n\n", "output": "\u00a0\nDROP TABLE test;\n\u00a0\nCREATE TABLE test(a INTEGER, b INTEGER);\n\u00a0\nINSERT INTO test VALUES (1,2);\n\u00a0\nINSERT INTO test VALUES (2,2);\n\u00a0\nINSERT INTO test VALUES (2,1);\n\u00a0\nSELECT to_char(a)||' is less than '||to_char(b) less_than\nFROM test\nWHERE a < b;\n\u00a0\nSELECT to_char(a)||' is equal to '||to_char(b) equal_to\nFROM test\nWHERE a = b;\n\u00a0\nSELECT to_char(a)||' is greater than '||to_char(b) greater_than\nFROM test\nWHERE a > b;\n\u00a0", "input": ""}, {"instruction": "\nBasic Data Operation\n\nThis is a basic data operation. It represents a fundamental action on a basic data type.\nYou may see other such operations in the Basic Data Operations category, or:\n\n\nInteger Operations\nArithmetic |\nComparison\nBoolean Operations\nBitwise |\nLogical\nString Operations\nConcatenation |\nInterpolation |\nComparison |\nMatching\nMemory Operations\nPointers & references |\nAddresses\n\n\nGet two integers from the user.\n\nThen, \u00a0 display a message if the first integer is:\n\n \u00a0 less than, \n \u00a0 equal to, \u00a0 or \n \u00a0 greater than\nthe second integer.\n\n\n\nTest the condition \u00a0 for each case separately, \u00a0 so that \u00a0 all three comparison operators are used \u00a0 in the code.\n\n\n\nRelated task\n\n \u00a0 String comparison\n\n", "output": "\u00a0\nCREATE TABLE TEST (\n VAL1 INT,\n VAL2 INT\n);\nINSERT INTO TEST (VAL1, VAL2) VALUES\n (1, 2),\n (2, 2),\n (2, 1);\nSELECT\n CASE\n WHEN VAL1 < VAL2 THEN VAL1 || ' less than ' || VAL2\n WHEN VAL1 = VAL2 THEN VAL1 || ' equal to ' || VAL2\n WHEN VAL1 > VAL2 THEN VAL1 || ' greater than ' || VAL2\n END COMPARISON\nFROM TEST;\n\u00a0", "input": ""}, {"instruction": "A \u00a0 here document \u00a0 (or \"heredoc\") \u00a0 is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.\n\nDepending on the language being used, a \u00a0 here document \u00a0 is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string.\n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n\nTask\n\nDemonstrate the use of \u00a0 here documents \u00a0 within the language.\n\nRelated task\n\n \u00a0 Documentation\n\n", "output": "\u00a0\ndb2 \"select 'This is the first line.\nThis is the second line.\nThis is the third line.' from sysibm.sysdummy1\"\n\u00a0", "input": ""}, {"instruction": "Hello world/Standard error is part of Short Circuit's Console Program Basics selection.\nA common practice in computing is to send error messages\nto a different output stream than normal text console messages.\n\nThe normal messages print to what is called \"standard output\" or \"standard out\".\n\nThe error messages print to \"standard error\".\n\nThis separation can be used to redirect error messages to a different place than normal messages.\n\n\n\nTask\n\nShow how to print a message to standard error by printing \u00a0 \u00a0 Goodbye, World! \u00a0 \u00a0 on that stream.\n\n\n\n", "output": " RAISERROR 'Goodbye, World!', 16, 1 ", "input": ""}, {"instruction": "Task\n\nGuide a new user of a language through the steps necessary\nto install the programming language and selection of a text editor if needed,\nto run the languages' example in the Hello world/Text task.\n\n Assume the language-newbie is a programmer in another language.\n Assume the language-newbie is competent in installing software for the platform.\n Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).\n Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).\n Remember to state where to view the output.\n If particular IDE's or editors are required that are not standard, then point to/explain their installation too.\n\n\nNote:\n If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.\n You may use sub-headings if giving instructions for multiple platforms.\n\n", "output": "tar -xvf v11.1_linuxx64_expc.tar.gz", "input": ""}, {"instruction": "An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.\n\nTask[edit]\nImplement the \"hash join\" algorithm, and demonstrate that it passes the test-case listed below.\n\nYou should represent the tables as data structures that feel natural in your programming language.\n\nGuidance\nThe \"hash join\" algorithm consists of two steps:\n\n Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.\n\n The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.\n Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.\n Join phase: Scan the other table, and find matching rows by looking in the multimap created before.\n\n\nIn pseudo-code, the algorithm could be expressed as follows:\n\nlet A = the first input table (or ideally, the larger one)\nlet B = the second input table (or ideally, the smaller one)\nlet jA = the join column ID of table A\nlet jB = the join column ID of table B\nlet MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)\nlet C = the output table (starts out empty)\n\nfor each row b in table B:\n place b in multimap MB under key b(jB)\n\nfor each row a in table A:\n for each row b in multimap MB under key a(jA):\n let c = the concatenation of row a and row b\n place row c in table C\n\nTest-case\n\n\n Input\n\n Output\n\n\n\n\n\n A =\n\n\n\n\n Age \n Name\n\n\n 27 \n Jonah\n\n\n 18 \n Alan\n\n\n 28 \n Glory\n\n\n 18 \n Popeye\n\n\n 28 \n Alan\n\n\n\n\n B =\n\n\n\n\n Character \n Nemesis\n\n\n Jonah \n Whales\n\n\n Jonah \n Spiders\n\n\n Alan \n Ghosts\n\n\n Alan \n Zombies\n\n\n Glory \n Buffy\n\n\n\n jA =\n\n Name (i.e. column 1)\n\n jB =\n\n Character (i.e. column 0)\n\n\n\n\n\n A.Age \n A.Name \n B.Character \n B.Nemesis\n\n\n 27 \n Jonah \n Jonah \n Whales\n\n\n 27 \n Jonah \n Jonah \n Spiders\n\n\n 18 \n Alan \n Alan \n Ghosts\n\n\n 18 \n Alan \n Alan \n Zombies\n\n\n 28 \n Glory \n Glory \n Buffy\n\n\n 28 \n Alan \n Alan \n Ghosts\n\n\n 28 \n Alan \n Alan \n Zombies\n\n\nThe order of the rows in the output table is not significant.\n\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n\n", "output": "-- setting up the test data\n\u00a0\nCREATE TABLE people (age NUMBER(3), name varchar2(30));\nINSERT INTO people (age, name)\n SELECT 27, 'Jonah' FROM dual UNION ALL\n SELECT 18, 'Alan' FROM dual UNION ALL\n SELECT 28, 'Glory' FROM dual UNION ALL\n SELECT 18, 'Popeye' FROM dual UNION ALL\n SELECT 28, 'Alan' FROM dual\n;\n\u00a0\nCREATE TABLE nemesises (name varchar2(30), nemesis varchar2(30));\nINSERT INTO nemesises (name, nemesis) \n SELECT 'Jonah', 'Whales' FROM dual UNION ALL\n SELECT 'Jonah', 'Spiders' FROM dual UNION ALL\n SELECT 'Alan' , 'Ghosts' FROM dual UNION ALL\n SELECT 'Alan' , 'Zombies' FROM dual UNION ALL\n SELECT 'Glory', 'Buffy' FROM dual\n;", "input": ""}, {"instruction": "Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.\n\n\n\nTask\n\nDisplay the string \u00a0 Goodbye, World! \u00a0 without a trailing newline.\n\n\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Text\n\n", "output": " PRINT 'Goodbye, World!'", "input": ""}, {"instruction": "\n\n This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)\n\n\n\nThe haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.\n\nIt is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical \"triangles\".\n\n\n\nTask\n\nImplement a great-circle distance function, or use a library function,\nto show the great-circle distance between:\n\n Nashville International Airport (BNA) \u00a0 in Nashville, TN, USA, \u00a0 which is: \n N 36\u00b07.2', W 86\u00b040.2' (36.12, -86.67) -and-\n\n Los Angeles International Airport (LAX) \u00a0in Los Angeles, CA, USA, \u00a0 which is:\n N 33\u00b056.4', W 118\u00b024.0' (33.94, -118.40) \n\n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' \u2248 1.0621333 km and .001\" \u2248 .00177 km,\n practical precision required is certainly no greater than about\n .0000001\u2014\u2014i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n\n\n\n\n", "output": "DELIMITER $$\n\u00a0\nCREATE FUNCTION haversine (\n\t\tlat1 FLOAT, lon1 FLOAT,\n\t\tlat2 FLOAT, lon2 FLOAT\n\t) RETURNS FLOAT\n\tNO SQL DETERMINISTIC\nBEGIN\n\tDECLARE r FLOAT unsigned DEFAULT 6372.8;\n\tDECLARE dLat FLOAT unsigned;\n\tDECLARE dLon FLOAT unsigned;\n\tDECLARE a FLOAT unsigned;\n\tDECLARE c FLOAT unsigned;\n\u00a0\n\tSET dLat = ABS(RADIANS(lat2 - lat1));\n\tSET dLon = ABS(RADIANS(lon2 - lon1));\n\tSET lat1 = RADIANS(lat1);\n\tSET lat2 = RADIANS(lat2);\n\u00a0\n\tSET a = POW(SIN(dLat / 2), 2) + COS(lat1) * COS(lat2) * POW(SIN(dLon / 2), 2);\n\tSET c = 2 * ASIN(SQRT(a));\n\u00a0\n\tRETURN (r * c);\nEND$$\n\u00a0\nDELIMITER ;", "input": ""}, {"instruction": "\n\n This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)\n\n\n\nThe haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.\n\nIt is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical \"triangles\".\n\n\n\nTask\n\nImplement a great-circle distance function, or use a library function,\nto show the great-circle distance between:\n\n Nashville International Airport (BNA) \u00a0 in Nashville, TN, USA, \u00a0 which is: \n N 36\u00b07.2', W 86\u00b040.2' (36.12, -86.67) -and-\n\n Los Angeles International Airport (LAX) \u00a0in Los Angeles, CA, USA, \u00a0 which is:\n N 33\u00b056.4', W 118\u00b024.0' (33.94, -118.40) \n\n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' \u2248 1.0621333 km and .001\" \u2248 .00177 km,\n practical precision required is certainly no greater than about\n .0000001\u2014\u2014i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n\n\n\n\n", "output": "CREATE FUNCTION [dbo].[Haversine](@Lat1 AS DECIMAL(9,7), @Lon1 AS DECIMAL(10,7), @Lat2 AS DECIMAL(9,7), @Lon2 AS DECIMAL(10,7))\nRETURNS DECIMAL(12,7)\nAS\nBEGIN\n\tDECLARE @R\tDECIMAL(11,7);\n\tDECLARE @dLat\tDECIMAL(9,7);\n\tDECLARE @dLon\tDECIMAL(10,7);\n\tDECLARE @a\tDECIMAL(10,7);\n\tDECLARE @c\tDECIMAL(10,7);\n\u00a0\n\tSET @R\t\t= 6372.8;\n\tSET @dLat\t= RADIANS(@Lat2 - @Lat1);\n\tSET @dLon\t= RADIANS(@Lon2 - @Lon1);\n\tSET @Lat1\t= RADIANS(@Lat1);\n\tSET @Lat2\t= RADIANS(@Lat2);\n\tSET @a\t\t= SIN(@dLat / 2) * SIN(@dLat / 2) + SIN(@dLon / 2) * SIN(@dLon / 2) * COS(@Lat1) * COS(@Lat2);\n\tSET @c\t\t= 2 * ASIN(SQRT(@a));\n\u00a0\n\tRETURN @R * @c;\nEND\nGO\n\u00a0\nSELECT dbo.Haversine(36.12,-86.67,33.94,-118.4)\n\u00a0", "input": ""}, {"instruction": "Task\n\nGiven a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.\n\n\n\nAn empty subsequence is considered to have the sum of \u00a0 0; \u00a0 thus if all elements are negative, the result must be the empty sequence.\n\n\n\n", "output": "\u00a0\n/*\nThis is a code implementation for finding one or more contiguous subsequences in a general sequence with the maximum sum of its elements.\np_list -- List of elements of the general sequence of integers separated by a delimiter.\np_delimiter -- proper delimiter\n*/\n\u00a0\nWITH \n FUNCTION greatest_subsequential_sum(p_list IN varchar2, p_delimiter IN varchar2) RETURN varchar2 IS \n -- Variablen\n v_list varchar2(32767)\u00a0:= TRIM(BOTH p_delimiter FROM p_list);\n v_substr_i varchar2(32767);\n v_substr_j varchar2(32767);\n v_substr_out varchar2(32767);\n v_res INTEGER\u00a0:= 0;\n v_res_out INTEGER\u00a0:= 0;\n --\n BEGIN\n --\n v_list\u00a0:= regexp_replace(v_list,''||chr(92)||p_delimiter||'{2,}',p_delimiter);\n --\n FOR i IN 1..nvl(regexp_count(v_list,'[^'||p_delimiter||']+'),0)\n loop\n v_substr_i\u00a0:= substr(v_list,regexp_instr(v_list,'[^'||p_delimiter||']+',1,i));\n --\n FOR j IN reverse 1..regexp_count(v_substr_i,'[^'||p_delimiter||']+')\n loop\n --\n v_substr_j\u00a0:= TRIM(BOTH p_delimiter FROM substr(v_substr_i,1,regexp_instr(v_substr_i,'[^'||p_delimiter||']+',1,j,1)));\n EXECUTE immediate 'select sum('||REPLACE(v_substr_j,p_delimiter,'+')||') from dual' INTO v_res;\n --\n IF v_res > v_res_out THEN\n v_res_out\u00a0:= v_res;\n v_substr_out\u00a0:= '{'||v_substr_j||'}';\n elsif v_res = v_res_out THEN\n v_res_out\u00a0:= v_res;\n v_substr_out\u00a0:= v_substr_out||',{'||v_substr_j||'}';\n END IF;\n --\n END loop;\n --\n END loop;\n -- \n v_substr_out\u00a0:= TRIM(BOTH ',' FROM nvl(v_substr_out,'{}'));\n v_substr_out\u00a0:= CASE WHEN regexp_count(v_substr_out,'},{')>0 THEN 'subsequences '||v_substr_out ELSE 'a subsequence '||v_substr_out END;\n RETURN 'The maximum sum '||v_res_out||' belongs to '||v_substr_out||' of the main sequence {'||p_list||'}';\nEND;\n\u00a0\n--Test\nSELECT greatest_subsequential_sum('-1|-2|-3|-4|-5|', '|') AS \"greatest subsequential sum\" FROM dual\nUNION ALL\nSELECT greatest_subsequential_sum('', '') FROM dual\nUNION ALL\nSELECT greatest_subsequential_sum(' ', ' ') FROM dual\nUNION ALL\nSELECT greatest_subsequential_sum(';;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;', ';') FROM dual\nUNION ALL\nSELECT greatest_subsequential_sum('-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1', ',') FROM dual\nUNION ALL\nSELECT greatest_subsequential_sum(',+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,', ',') FROM dual\nUNION ALL \nSELECT greatest_subsequential_sum('01 +2 3 +4 05 -8 -9 -20 40 25 -5', ' ') FROM dual\nUNION ALL \nSELECT greatest_subsequential_sum('1 2 3 0 0 -99 02 03 00001 -99 3 2 1 -99 3 1 2 0', ' ') FROM dual\nUNION ALL \nSELECT greatest_subsequential_sum('0,0,1,0', ',') FROM dual\nUNION ALL \nSELECT greatest_subsequential_sum('0,0,0', ',') FROM dual\nUNION ALL \nSELECT greatest_subsequential_sum('1,-1,+1', ',') FROM dual; \n\u00a0\n\u00a0", "input": ""}, {"instruction": "Gray code\nKarnaugh maps\nCreate functions to encode a number to and decode a number from Gray code.\n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\nOr:\n\ng = b xor (b logically right shifted 1 time)\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\nReference\n Converting Between Gray and Binary Codes. It includes step-by-step animations.", "output": "\u00a0\nDECLARE @BINARY AS NVARCHAR(MAX) = '001010111' \nDECLARE @gray AS NVARCHAR(MAX) = '' \n\u00a0\n--Encoder \nSET @gray = LEFT(@BINARY, 1) \n\u00a0\nWHILE LEN(@BINARY) > 1 \n BEGIN \n IF LEFT(@BINARY, 1)\u00a0!= SUBSTRING(@BINARY, 2, 1) \n SET @gray = @gray + '1' \n ELSE \n SET @gray = @gray + '0' \n\u00a0\n SET @BINARY = RIGHT(@BINARY, LEN(@BINARY) - 1) \n END \n\u00a0\nSELECT @gray \n\u00a0\n--Decoder \nSET @BINARY = LEFT(@gray, 1) \n\u00a0\nWHILE LEN(@gray) > 1 \n BEGIN \n IF RIGHT(@BINARY, 1)\u00a0!= SUBSTRING(@gray, 2, 1) \n SET @BINARY = @BINARY + '1' \n ELSE \n SET @BINARY = @BINARY + '0' \n\u00a0\n SET @gray = RIGHT(@gray, LEN(@gray) - 1) \n END \n\u00a0\nSELECT @BINARY \n\u00a0", "input": ""}, {"instruction": "Hamming numbers are numbers of the form \u00a0\n\n H = 2i \u00d7 3j \u00d7 5k\n where \n i, j, k \u2265 0 \n\nHamming numbers \u00a0 are also known as \u00a0 ugly numbers \u00a0 and also \u00a0 5-smooth numbers \u00a0 (numbers whose prime divisors are less or equal to 5).\n\n\n\nTask\n\nGenerate the sequence of Hamming numbers, in increasing order. \u00a0 In particular:\n\n Show the \u00a0 first twenty \u00a0 Hamming numbers.\n Show the \u00a0 1691st \u00a0 Hamming number (the last one below \u00a0 231).\n Show the \u00a0 one millionth \u00a0 Hamming number (if the language \u2013 or a convenient library \u2013 supports arbitrary-precision integers).\n\n\nRelated tasks\n\n Humble numbers\n N-smooth numbers\n\n\nReferences\n\n Wikipedia entry: \u00a0 Hamming numbers \u00a0 \u00a0 (this link is re-directed to \u00a0 Regular number).\n Wikipedia entry: \u00a0 Smooth number\n OEIS entry: \u00a0 A051037 \u00a0 5-smooth \u00a0 or \u00a0 Hamming numbers\n Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).\n\n", "output": "\u00a0\nCREATE TEMPORARY TABLE factors(n INT);\nINSERT INTO factors VALUES(2);\nINSERT INTO factors VALUES(3);\nINSERT INTO factors VALUES(5);\n\u00a0\nCREATE TEMPORARY TABLE hamming AS\n WITH RECURSIVE ham AS (\n SELECT 1 AS h\n UNION\n SELECT h*n x FROM ham JOIN factors ORDER BY x\n LIMIT 1700\n )\n SELECT h FROM ham;\n\u00a0\nsqlite> SELECT h FROM hamming ORDER BY h LIMIT 20;\n1\n2\n3\n4\n5\n6\n8\n9\n10\n12\n15\n16\n18\n20\n24\n25\n27\n30\n32\n36\nsqlite> SELECT h FROM hamming ORDER BY h LIMIT 1 OFFSET 1690;\n2125764000\n\u00a0", "input": ""}, {"instruction": "Greatest common divisor\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nFind the greatest common divisor \u00a0 (GCD) \u00a0 of two integers.\n\n\nGreatest common divisor \u00a0 is also known as \u00a0 greatest common factor (gcf) \u00a0 and \u00a0 greatest common measure.\n\n\n\nRelated task\n\n \u00a0 least common multiple.\n\n\nSee also\n\n \u00a0 MathWorld entry: \u00a0 greatest common divisor.\n \u00a0 Wikipedia entry: \u00a0 \u00a0 greatest common divisor.\n\n", "output": "\u00a0\nDROP FUNCTION IF EXISTS gcd;\nDELIMITER |\n\u00a0\nCREATE FUNCTION gcd(x INT, y INT)\nRETURNS INT\nBEGIN\n SET @dividend=GREATEST(ABS(x),ABS(y));\n SET @divisor=LEAST(ABS(x),ABS(y));\n IF @divisor=0 THEN\n RETURN @dividend;\n END IF;\n SET @gcd=NULL;\n SELECT gcd INTO @gcd FROM\n (SELECT @tmp:=@dividend,\n @dividend:=@divisor AS gcd,\n @divisor:=@tmp % @divisor AS remainder\n FROM mysql.help_relation WHERE @divisor>0) AS x\n WHERE remainder=0;\n RETURN @gcd;\nEND;|\n\u00a0\nDELIMITER ;\n\u00a0\nSELECT gcd(12345, 9876);\n\u00a0", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": "SELECT 'Hello world!';", "input": ""}, {"instruction": "Greatest common divisor\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nFind the greatest common divisor \u00a0 (GCD) \u00a0 of two integers.\n\n\nGreatest common divisor \u00a0 is also known as \u00a0 greatest common factor (gcf) \u00a0 and \u00a0 greatest common measure.\n\n\n\nRelated task\n\n \u00a0 least common multiple.\n\n\nSee also\n\n \u00a0 MathWorld entry: \u00a0 greatest common divisor.\n \u00a0 Wikipedia entry: \u00a0 \u00a0 greatest common divisor.\n\n", "output": "DROP TABLE tbl;\nCREATE TABLE tbl\n(\n u NUMBER,\n v NUMBER\n);\n\u00a0\nINSERT INTO tbl ( u, v ) VALUES ( 20, 50 );\nINSERT INTO tbl ( u, v ) VALUES ( 21, 50 );\nINSERT INTO tbl ( u, v ) VALUES ( 21, 51 );\nINSERT INTO tbl ( u, v ) VALUES ( 22, 50 );\nINSERT INTO tbl ( u, v ) VALUES ( 22, 55 );\n\u00a0\ncommit;\n\u00a0\nWITH\n FUNCTION gcd ( ui IN NUMBER, vi IN NUMBER )\n RETURN NUMBER\n IS\n u NUMBER\u00a0:= ui;\n v NUMBER\u00a0:= vi;\n t NUMBER;\n BEGIN\n while v > 0\n loop\n t\u00a0:= u;\n u\u00a0:= v;\n v:= MOD(t, v );\n END loop;\n RETURN abs(u);\n END gcd;\n SELECT u, v, gcd ( u, v )\n FROM tbl\n/\n\u00a0", "input": ""}, {"instruction": "Greatest common divisor\n\nYou are encouraged to solve this task according to the task description, using any language you may know.\nTask\n\nFind the greatest common divisor \u00a0 (GCD) \u00a0 of two integers.\n\n\nGreatest common divisor \u00a0 is also known as \u00a0 greatest common factor (gcf) \u00a0 and \u00a0 greatest common measure.\n\n\n\nRelated task\n\n \u00a0 least common multiple.\n\n\nSee also\n\n \u00a0 MathWorld entry: \u00a0 greatest common divisor.\n \u00a0 Wikipedia entry: \u00a0 \u00a0 greatest common divisor.\n\n", "output": "\u00a0\nCREATE OR ALTER FUNCTION [dbo].[PGCD]\n ( @a BigInt\n , @b BigInt\n )\nRETURNS BigInt\nWITH RETURNS NULL ON NULL INPUT\n-- Calculates the Greatest Common Denominator of two numbers (1 if they are coprime).\nBEGIN\nDECLARE @PGCD BigInt;\n\u00a0\nWITH Vars(A, B)\nAs ( SELECT Max(V.N) As A\n , Min(V.N) As B\n FROM ( VALUES ( Abs(@a) , Abs(@b)) ) Params(A, B)\n -- First, get absolute value\n Cross APPLY ( VALUES (Params.A) , (Params.B) ) V(N)\n -- Then, order parameters without Greatest/Least functions\n WHERE Params.A > 0\n And Params.B > 0 -- If 0 passed in, NULL shall be the output\n )\n , Calc(A, B)\nAs ( SELECT A\n , B\n FROM Vars\n\u00a0\n UNION ALL\n\u00a0\n SELECT B As A\n , A\u00a0% B As B -- Self-ordering\n FROM Calc\n WHERE Calc.A > 0\n And Calc.B > 0\n )\nSELECT @PGCD = Min(A)\nFROM Calc\nWHERE Calc.B = 0\n;\n\u00a0\nRETURN @PGCD;\n\u00a0\nEND\n\u00a0", "input": ""}, {"instruction": "Numbers \u00a0 (positive integers expressed in base ten) \u00a0 that are (evenly) divisible by the number formed by the\nfirst and last digit are known as \u00a0 gapful numbers.\n\n\nEvenly divisible \u00a0 means divisible with \u00a0 no \u00a0 remainder.\n\n\n\nAll \u00a0 one\u2500 \u00a0 and two\u2500digit \u00a0 numbers have this property and are trivially excluded. \u00a0 Only\nnumbers \u00a0 \u2265 100 \u00a0 will be considered for this Rosetta Code task.\n\n\n\nExample\n\n187 \u00a0 is a \u00a0 gapful \u00a0 number because it is evenly divisible by the\nnumber \u00a0 17 \u00a0 which is formed by the first and last decimal digits\nof \u00a0 187. \n\n\n\nAbout \u00a0 7.46% \u00a0 of positive integers are \u00a0 gapful.\n\n\n\nTask\n\n \u00a0 Generate and show all sets of numbers (below) on one line (horizontally) with a title, \u00a0 here on this page\n \u00a0 Show the first \u00a0 30 \u00a0 gapful numbers\n \u00a0 Show the first \u00a0 15 \u00a0 gapful numbers \u00a0 \u2265 \u00a0 \u00a0 \u00a0 \u00a0 \u00a01,000,000\n \u00a0 Show the first \u00a0 10 \u00a0 gapful numbers \u00a0 \u2265 \u00a0 1,000,000,000\n\n\nRelated tasks\n\n \u00a0 Harshad or Niven series.\n \u00a0 palindromic gapful numbers.\n \u00a0 largest number divisible by its digits.\n\n\nAlso see\n\n \u00a0 The OEIS entry: \u00a0 A108343 gapful numbers.\n \u00a0 numbersaplenty gapful numbers\n\n", "output": "\u00a0\n/*\nThis code is an implementation of gapful numbers in SQL ORACLE 19c \np_start -- start point\np_count -- total number to be found\n*/\nWITH\n FUNCTION gapful_numbers(p_start IN INTEGER, p_count IN INTEGER) RETURN varchar2 IS\n v_start INTEGER\u00a0:= p_start;\n v_count INTEGER\u00a0:= 0;\n v_res varchar2(32767); \n BEGIN\n v_res\u00a0:= 'First '||p_count||' gapful numbers starting from '||p_start||': ';\n -- main cycle\n while TRUE loop\n IF MOD(v_start,to_number(substr(v_start,1,1)||substr(v_start,-1))) = 0 THEN \n v_res\u00a0:= v_res || v_start; \n v_count\u00a0:= v_count + 1;\n exit WHEN v_count = p_count;\n v_res\u00a0:= v_res || ', '; \n END IF;\n v_start\u00a0:= v_start + 1; \n END loop;\n --\n RETURN v_res;\n --\n END;\n\u00a0\n--Test\nSELECT gapful_numbers(100,30) AS res FROM dual\nUNION ALL \nSELECT gapful_numbers(1000000,15) AS res FROM dual\nUNION ALL \nSELECT gapful_numbers(1000000000,10) AS res FROM dual;\n/\n\u00a0", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": "\u00a0\nSET serveroutput ON\n\u00a0\nBEGIN\n DBMS_OUTPUT.PUT_LINE('Hello world!');\nEND;\n/\n\u00a0", "input": ""}, {"instruction": "Task\n\nGenerate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.\n\nFor this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.\n\nDuring code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:\n\nset alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}\n\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "Declare\n sbAlphabet varchar2(100);\nBegin\n For nuI in 97..122 loop\n if sbAlphabet is null then\n sbAlphabet:=chr(nuI);\n Else\n sbAlphabet:=sbAlphabet||','||chr(nuI);\n End if;\n End loop;\n Dbms_Output.Put_Line(sbAlphabet);\nEnd;", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": " EXECUTE BLOCK\n RETURNS(S VARCHAR(40))\n AS\n BEGIN\n S = 'Hello world!';\n SUSPEND;\n END\n", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": "\u00a0\nSELECT 'Hello world!' text FROM dual;\n\u00a0", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": "\u00a0\nSELECT 'Hello world!' AS text FROM sysibm.sysdummy1;\n\u00a0", "input": ""}, {"instruction": "Hello world/Text is part of Short Circuit's Console Program Basics selection.\nTask\n\nDisplay the string Hello world! on a text console.\n\nRelated tasks\n\n \u00a0 Hello world/Graphical\n \u00a0 Hello world/Line Printer\n \u00a0 Hello world/Newbie\n \u00a0 Hello world/Newline omission\n \u00a0 Hello world/Standard error\n \u00a0 Hello world/Web server\n\n", "output": "PRINT \"Hello world!\"", "input": ""}, {"instruction": "A function is a body of code that returns a value.\n\nThe value returned may depend on arguments provided to the function.\n\n\n\nTask\n\nWrite a definition of a function called \"multiply\" that takes two arguments and returns their product.\n\n(Argument types should be chosen so as not to distract from showing how functions are created and values returned).\n\n\n\nRelated task\n\n \u00a0 Function prototype\n\n", "output": "FUNCTION multiply(p_arg1 NUMBER, p_arg2 NUMBER) RETURN NUMBER \nIS\n v_product NUMBER;\nBEGIN\n v_product := p_arg1 * p_arg2;\n RETURN v_product;\nEND;", "input": ""}, {"instruction": "Task\n\nExpress a number in decimal as a fixed-length string with leading zeros.\n\n\n\nFor example, the number \u00a0 7.125 \u00a0 could be expressed as \u00a0 00007.125.\n\n\n\n", "output": "DECLARE @n INT\nSELECT @n=123\nSELECT SUBSTRING(CONVERT(CHAR(5), 10000+@n),2,4) AS FourDigits\n\u00a0\nSET @n=5\nprint \"TwoDigits: \" + SUBSTRING(CONVERT(CHAR(3), 100+@n),2,2)\n--Output: 05", "input": ""}, {"instruction": "Task\n\nProvide code that produces a list of numbers which is the \u00a0 nth \u00a0order forward difference, given a non-negative integer (specifying the order) and a list of numbers.\n\n\n\nThe first-order forward difference of a list of numbers \u00a0 A \u00a0 is a new list \u00a0 B, \u00a0 where \u00a0 Bn = An+1 - An.\n\nList \u00a0 B \u00a0 should have one fewer element as a result.\n\nThe second-order forward difference of \u00a0 A \u00a0 will be:\n\ntdefmodule Diff do\n\tdef forward(arr,i\\\\1) do\n\t\tforward(arr,[],i)\n\tend\n\n\tdef forward([_|[]],diffs,i) do\n\t\tif i == 1 do\n\t\t\tIO.inspect diffs\n\t\telse \n\t\t\tforward(diffs,[],i-1)\n\t\tend\n\tend\n\n\tdef forward([val1|[val2|vals]],diffs,i) do\n\t\tforward([val2|vals],diffs++[val2-val1],i) \n\tend\nend \n\nThe same as the first-order forward difference of \u00a0 B.\n\nThat new list will have two fewer elements than \u00a0 A \u00a0 and one less than \u00a0 B.\n\nThe goal of this task is to repeat this process up to the desired order.\n\nFor a more formal description, see the related \u00a0 Mathworld article.\n\n\n\nAlgorithmic options\n\n Iterate through all previous forward differences and re-calculate a new array each time.\n Use this formula (from Wikipedia):\n\n\n \n\n\n\n\n\u0394\n\nn\n\n\n[\nf\n]\n(\nx\n)\n=\n\n\u2211\n\nk\n=\n0\n\n\nn\n\n\n\n\n\n(\n\n\nn\nk\n\n\n)\n\n\n\n(\n\u2212\n1\n\n)\n\nn\n\u2212\nk\n\n\nf\n(\nx\n+\nk\n)\n\n\n{\\displaystyle \\Delta ^{n}[f](x)=\\sum _{k=0}^{n}{n \\choose k}(-1)^{n-k}f(x+k)}\n\n\n\n\n (Pascal's Triangle \u00a0 may be useful for this option.)\n\n", "output": "WITH RECURSIVE\nT0 (N, ITEM, LIST, NEW_LIST) AS\n(\n SELECT 1,\n NULL, \n '90,47,58,29,22,32,55,5,55,73' || ',',\n NULL\n UNION ALL\n SELECT CASE\n WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''\n THEN N + 1\n ELSE N\n END,\n CASE\n WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''\n THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1)\n ELSE NULL\n END,\n CASE\n WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''\n THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')\n ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST))\n END,\n CASE\n WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''\n THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')\n ELSE NULL\n END\n FROM T0\n WHERE INSTR(LIST, ',') > 0\n)\nSELECT N,\n TRIM(LIST, ',') LIST\n FROM T0\n WHERE NEW_LIST IS NULL\n AND LIST <> ''\n ORDER BY N;", "input": ""}, {"instruction": "Task\n\nSelect certain elements from an Array into a new Array in a generic way.\n\n\n\nTo demonstrate, select all even numbers from an Array.\n\nAs an option, give a second solution which filters destructively,\nby modifying the original Array rather than creating a new Array.\n\n\n\n", "output": "--Create the original array (table #nos) with numbers from 1 to 10\nCREATE TABLE #nos (v INT)\nDECLARE @n INT SET @n=1\nwhile @n<=10 BEGIN INSERT INTO #nos VALUES (@n) SET @n=@n+1 END\n\u00a0\n--Select the subset that are even into the new array (table #evens)\nSELECT v INTO #evens FROM #nos WHERE v\u00a0% 2 = 0\n\u00a0\n-- Show #evens\nSELECT * FROM #evens\n\u00a0\n-- Clean up so you can edit and repeat:\nDROP TABLE #nos\nDROP TABLE #evens", "input": ""}, {"instruction": "Task\n\nWrite a program that prints the integers from \u00a0 1 \u00a0 to \u00a0 100 \u00a0 (inclusive).\n\n\n\nBut:\n\n \u00a0 for multiples of three, \u00a0 print \u00a0 Fizz \u00a0 \u00a0 (instead of the number)\n \u00a0 for multiples of five, \u00a0 print \u00a0 Buzz \u00a0 \u00a0 (instead of the number)\n \u00a0 for multiples of both three and five, \u00a0 print \u00a0 FizzBuzz \u00a0 \u00a0 (instead of the number) \n\n\nThe \u00a0 FizzBuzz \u00a0 problem was presented as the lowest level of comprehension required to illustrate adequacy.\n\n\n\nAlso see\n\n \u00a0 (a blog) \u00a0 dont-overthink-fizzbuzz\n \u00a0 (a blog) \u00a0 fizzbuzz-the-programmers-stairway-to-heaven\n\n", "output": "BEGIN\n FOR i IN 1 .. 100\n LOOP\n CASE\n WHEN MOD(i, 15) = 0 THEN\n DBMS_OUTPUT.put_line('FizzBuzz');\n WHEN MOD(i, 5) = 0 THEN\n DBMS_OUTPUT.put_line('Buzz');\n WHEN MOD(i, 3) = 0 THEN\n DBMS_OUTPUT.put_line('Fizz');\n ELSE\n DBMS_OUTPUT.put_line(i);\n END CASE;\n END LOOP;\nEND;", "input": ""}, {"instruction": "Task\n\nWrite a program that prints the integers from \u00a0 1 \u00a0 to \u00a0 100 \u00a0 (inclusive).\n\n\n\nBut:\n\n \u00a0 for multiples of three, \u00a0 print \u00a0 Fizz \u00a0 \u00a0 (instead of the number)\n \u00a0 for multiples of five, \u00a0 print \u00a0 Buzz \u00a0 \u00a0 (instead of the number)\n \u00a0 for multiples of both three and five, \u00a0 print \u00a0 FizzBuzz \u00a0 \u00a0 (instead of the number) \n\n\nThe \u00a0 FizzBuzz \u00a0 problem was presented as the lowest level of comprehension required to illustrate adequacy.\n\n\n\nAlso see\n\n \u00a0 (a blog) \u00a0 dont-overthink-fizzbuzz\n \u00a0 (a blog) \u00a0 fizzbuzz-the-programmers-stairway-to-heaven\n\n", "output": "SELECT CASE\n WHEN MOD(level,15)=0 THEN 'FizzBuzz'\n WHEN MOD(level,3)=0 THEN 'Fizz'\n WHEN MOD(level,5)=0 THEN 'Buzz'\n ELSE TO_CHAR(level)\n END FizzBuzz\n FROM dual\n CONNECT BY LEVEL <= 100;", "input": ""}, {"instruction": "Control Structures\nThese are examples of control structures. You may also be interested in:\n\n Conditional structures\n Exceptions\n Flow-control structures\n Loops\n\nThis task is to give an example of an exception handling routine\nand to \"throw\" a new exception.\n\n\n\nRelated task\n\n \u00a0 Exceptions Through Nested Calls\n\n", "output": "\u00a0\nBEGIN\n raise exception 'this is a generic user exception';\n raise exception division_by_zero;\nEND;\n\u00a0", "input": ""}, {"instruction": "Control Structures\nThese are examples of control structures. You may also be interested in:\n\n Conditional structures\n Exceptions\n Flow-control structures\n Loops\n\nThis task is to give an example of an exception handling routine\nand to \"throw\" a new exception.\n\n\n\nRelated task\n\n \u00a0 Exceptions Through Nested Calls\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nBEGIN\n DECLARE numerator INTEGER DEFAULT 12;\n DECLARE denominator INTEGER DEFAULT 0;\n DECLARE RESULT INTEGER;\n DECLARE overflow CONDITION FOR SQLSTATE '22003'\u00a0;\n DECLARE CONTINUE HANDLER FOR overflow\n RESIGNAL SQLSTATE '22375'\n SET MESSAGE_TEXT = 'Zero division';\n IF denominator = 0 THEN\n SIGNAL overflow;\n ELSE\n SET RESULT = numerator / denominator;\n END IF;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nRun either the \u00a0 ls \u00a0 system command \u00a0 (dir \u00a0 on Windows), \u00a0 or the \u00a0 pause \u00a0 system command.\n\n\n\n\nRelated task\n Get system command output\n\n", "output": "\u00a0\n!ls\n\u00a0", "input": ""}, {"instruction": "The Fibonacci sequence is a sequence \u00a0 Fn \u00a0 of natural numbers defined recursively:\n\n F0 = 0 \n F1 = 1 \n Fn = Fn-1 + Fn-2, if n>1 \n\n\n\nTask\n\nWrite a function to generate the \u00a0 nth \u00a0 Fibonacci number.\n\nSolutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).\n\nThe sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:\n\n Fn = Fn+2 - Fn+1, if n<0 \n\nsupport for negative \u00a0 \u00a0 n \u00a0 \u00a0 in the solution is optional.\n\n\n\nRelated tasks\n\n \u00a0 Fibonacci n-step number sequences\u200e\n \u00a0 Leonardo numbers\n\n\nReferences\n\n \u00a0 Wikipedia, Fibonacci number\n \u00a0 Wikipedia, Lucas number\n \u00a0 MathWorld, Fibonacci Number\n \u00a0 Some identities for r-Fibonacci numbers\n \u00a0 OEIS Fibonacci numbers\n \u00a0 OEIS Lucas numbers\n\n", "output": "CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$\nBEGIN\n IF (n < 2) THEN\n RETURN n;\n END IF;\n RETURN fib(n - 1) + fib(n - 2);\nEND;\n$$ LANGUAGE plpgsql;", "input": ""}, {"instruction": "The Fibonacci sequence is a sequence \u00a0 Fn \u00a0 of natural numbers defined recursively:\n\n F0 = 0 \n F1 = 1 \n Fn = Fn-1 + Fn-2, if n>1 \n\n\n\nTask\n\nWrite a function to generate the \u00a0 nth \u00a0 Fibonacci number.\n\nSolutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).\n\nThe sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:\n\n Fn = Fn+2 - Fn+1, if n<0 \n\nsupport for negative \u00a0 \u00a0 n \u00a0 \u00a0 in the solution is optional.\n\n\n\nRelated tasks\n\n \u00a0 Fibonacci n-step number sequences\u200e\n \u00a0 Leonardo numbers\n\n\nReferences\n\n \u00a0 Wikipedia, Fibonacci number\n \u00a0 Wikipedia, Lucas number\n \u00a0 MathWorld, Fibonacci Number\n \u00a0 Some identities for r-Fibonacci numbers\n \u00a0 OEIS Fibonacci numbers\n \u00a0 OEIS Lucas numbers\n\n", "output": "\u00a0\nCREATE OR REPLACE FUNCTION fnu_fibonacci(p_num INTEGER) RETURN INTEGER IS\n f INTEGER;\n p INTEGER;\n q INTEGER;\nBEGIN\n CASE WHEN p_num < 0 OR p_num != TRUNC(p_num) \n THEN raise_application_error(-20001, 'Invalid input: ' || p_num, TRUE);\n WHEN p_num IN (0, 1) THEN f := p_num;\n ELSE\n p := 0;\n q := 1;\n FOR i IN 2 .. p_num LOOP\n f := p + q;\n p := q;\n q := f;\n END LOOP;\n END CASE;\n RETURN(f);\nEND fnu_fibonacci;\n/\n\u00a0", "input": ""}, {"instruction": "The Fibonacci sequence is a sequence \u00a0 Fn \u00a0 of natural numbers defined recursively:\n\n F0 = 0 \n F1 = 1 \n Fn = Fn-1 + Fn-2, if n>1 \n\n\n\nTask\n\nWrite a function to generate the \u00a0 nth \u00a0 Fibonacci number.\n\nSolutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).\n\nThe sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:\n\n Fn = Fn+2 - Fn+1, if n<0 \n\nsupport for negative \u00a0 \u00a0 n \u00a0 \u00a0 in the solution is optional.\n\n\n\nRelated tasks\n\n \u00a0 Fibonacci n-step number sequences\u200e\n \u00a0 Leonardo numbers\n\n\nReferences\n\n \u00a0 Wikipedia, Fibonacci number\n \u00a0 Wikipedia, Lucas number\n \u00a0 MathWorld, Fibonacci Number\n \u00a0 Some identities for r-Fibonacci numbers\n \u00a0 OEIS Fibonacci numbers\n \u00a0 OEIS Lucas numbers\n\n", "output": "\u00a0\nSELECT round ( EXP ( SUM (ln ( ( 1 + SQRT( 5 ) ) / 2)\n ) OVER ( ORDER BY level ) ) / SQRT( 5 ) ) fibo\nFROM dual\nCONNECT BY level <= 10;\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate the simplest possible program that is still considered \"correct.\"\n\n\n\n", "output": "CREATE COMPUTE MODULE ESQL_Compute\n CREATE FUNCTION Main() RETURNS BOOLEAN\n BEGIN\n RETURN TRUE;\n END;\nEND MODULE;", "input": ""}, {"instruction": "Definitions\n\n \u00a0 The factorial of \u00a0 0 \u00a0 (zero) \u00a0 is defined as being \u00a0 1 \u00a0 (unity).\n \u00a0 The \u00a0 Factorial Function \u00a0 of a positive integer, \u00a0 n, \u00a0 is defined as the product of the sequence:\n n, \u00a0 n-1, \u00a0 n-2, \u00a0 ... \u00a0 1 \n\n\n\nTask\n\nWrite a function to return the factorial of a number.\n\nSolutions can be iterative or recursive.\n\nSupport for trapping negative \u00a0 n \u00a0 errors is optional.\n\n\n\nRelated task\n\n \u00a0 Primorial numbers\n\n", "output": "\u00a0\nDECLARE\n /*====================================================================================================\n -- For \u00a0: https://rosettacode.org/\n -- --\n -- Task \u00a0: Factorial\n -- Method \u00a0: iterative\n -- Language: PL/SQL\n --\n -- 2020-12-30 by alvalongo\n ====================================================================================================*/\n --\n FUNCTION fnuFactorial(inuValue INTEGER)\n RETURN NUMBER\n IS\n nuFactorial NUMBER;\n BEGIN\n IF inuValue IS NOT NULL THEN\n nuFactorial:=1;\n --\n IF inuValue>=1 THEN\n --\n FOR nuI IN 1..inuValue LOOP\n nuFactorial:=nuFactorial*nuI;\n END LOOP;\n --\n END IF;\n --\n END IF;\n --\n RETURN(nuFactorial);\n END fnuFactorial;\nBEGIN\n FOR nuJ IN 0..100 LOOP\n DBMS_OUTPUT.Put_Line('Factorial('||nuJ||')='||fnuFactorial(nuJ));\n END LOOP;\nEND;\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate the simplest possible program that is still considered \"correct.\"\n\n\n\n", "output": "BEGIN\n NULL;\nEND;", "input": ""}, {"instruction": "Task\n\nCreate the simplest possible program that is still considered \"correct.\"\n\n\n\n", "output": "EXECUTE BLOCK\nAS\nBEGIN\nEND", "input": ""}, {"instruction": "Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.\n\n\nMethod:\n\n Take two numbers to be multiplied and write them down at the top of two columns.\n In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.\n In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.\n Examine the table produced and discard any row where the value in the left column is even.\n Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together\n\nFor example: \u00a0 17 \u00d7 34\n\n 17 34\n\nHalving the first column:\n\n 17 34\n 8\n 4\n 2\n 1\n\nDoubling the second column:\n\n 17 34\n 8 68\n 4 136 \n 2 272\n 1 544\n\nStrike-out rows whose first cell is even:\n\n 17 34\n 8 68 \n 4 136 \n 2 272 \n 1 544\n\nSum the remaining numbers in the right-hand column:\n\n 17 34\n 8 -- \n 4 --- \n 2 --- \n 1 544\n ====\n 578\n\nSo 17 multiplied by 34, by the Ethiopian method is 578.\n\n\n\nTask\n\nThe task is to define three named functions/methods/procedures/subroutines:\n\n one to halve an integer,\n one to double an integer, and\n one to state if an integer is even.\n\n\nUse these functions to create a function that does Ethiopian multiplication.\n\n\n\nReferences\n\nEthiopian multiplication explained (BBC Video clip)\nA Night Of Numbers - Go Forth And Multiply (Video)\nRussian Peasant Multiplication\nProgramming Praxis: Russian Peasant Multiplication\n\n", "output": "CREATE OR REPLACE PACKAGE ethiopian IS\n\u00a0\n FUNCTION multiply\n ( left IN INTEGER,\n right IN INTEGER)\n RETURN INTEGER;\n\u00a0\nEND ethiopian;\n/\n\u00a0\nCREATE OR REPLACE PACKAGE BODY ethiopian IS\n\u00a0\n FUNCTION is_even(item IN INTEGER) RETURN BOOLEAN IS\n BEGIN\n RETURN item MOD 2 = 0;\n END is_even;\n\u00a0\n FUNCTION double(item IN INTEGER) RETURN INTEGER IS\n BEGIN\n RETURN item * 2;\n END double;\n\u00a0\n FUNCTION half(item IN INTEGER) RETURN INTEGER IS\n BEGIN\n RETURN TRUNC(item / 2);\n END half;\n\u00a0\n FUNCTION multiply\n ( left IN INTEGER,\n right IN INTEGER)\n RETURN INTEGER\n IS\n temp INTEGER := 0;\n plier INTEGER := left;\n plicand INTEGER := right;\n BEGIN\n\u00a0\n LOOP\n IF NOT is_even(plier) THEN\n temp := temp + plicand;\n END IF;\n EXIT WHEN plier <= 1;\n plier := half(plier);\n plicand := double(plicand);\n END LOOP;\n\u00a0\n RETURN temp;\n\u00a0\n END multiply;\n\u00a0\nEND ethiopian;\n/\n\u00a0\n/* example call */\nBEGIN\n DBMS_OUTPUT.put_line(ethiopian.multiply(17, 34));\nEND;\n/", "input": ""}, {"instruction": "Task\n\nTest whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n Use the even and odd predicates, if the language provides them.\n Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.\n Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.\n Use modular congruences:\n i \u2261 0 (mod 2) iff i is even.\n i \u2261 1 (mod 2) iff i is odd.\n\n", "output": "-- Setup a table with some integers\nCREATE TABLE ints(INT INTEGER);\nINSERT INTO ints VALUES (-1);\nINSERT INTO ints VALUES (0);\nINSERT INTO ints VALUES (1);\nINSERT INTO ints VALUES (2);\n\u00a0\n-- Are they even or odd?\nSELECT\n INT,\n CASE MOD(INT, 2) WHEN 0 THEN 'Even' ELSE 'Odd' END\nFROM\n ints;", "input": ""}, {"instruction": "Task\n\nCreate the simplest possible program that is still considered \"correct.\"\n\n\n\n", "output": "\u00a0\nSELECT 1 FROM sysibm.sysdummy1;\n\u00a0", "input": ""}, {"instruction": "\nThe Dutch national flag is composed of three coloured bands in the order:\n\n \u00a0 red \u00a0 \u00a0 (top)\n \u00a0 then white, \u00a0 and\n \u00a0 lastly blue \u00a0 (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n\nGiven a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n\nTask\n Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.\n Sort the balls in a way idiomatic to your language.\n Check the sorted balls are in the order of the Dutch national flag.\n\n\nC.f.\n\n Dutch national flag problem\n Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "output": "-- Create and populate tables\nCREATE TABLE colours (id INTEGER PRIMARY KEY, name VARCHAR(5));\nINSERT INTO colours (id, name) VALUES ( 1, 'red' );\nINSERT INTO colours (id, name) VALUES ( 2, 'white');\nINSERT INTO colours (id, name) VALUES ( 3, 'blue' );\n\u00a0\nCREATE TABLE balls ( colour INTEGER REFERENCES colours );\nINSERT INTO balls ( colour ) VALUES ( 2 );\nINSERT INTO balls ( colour ) VALUES ( 2 );\nINSERT INTO balls ( colour ) VALUES ( 3 );\nINSERT INTO balls ( colour ) VALUES ( 2 );\nINSERT INTO balls ( colour ) VALUES ( 1 );\nINSERT INTO balls ( colour ) VALUES ( 3 );\nINSERT INTO balls ( colour ) VALUES ( 3 );\nINSERT INTO balls ( colour ) VALUES ( 2 );\n\u00a0\n-- Show the balls are unsorted\nSELECT\n\tcolours.name\nFROM\n\tballs\n\tJOIN colours ON balls.colour = colours.id;\n\u00a0\n-- Show the balls in dutch flag order\nSELECT\n\tcolours.name\nFROM\n\tballs\n\tJOIN colours ON balls.colour = colours.id\nORDER BY\n\tcolours.id;\n\u00a0\n-- Tidy up\nDROP TABLE balls;\nDROP TABLE colours;", "input": ""}, {"instruction": "\n\nSee also\n\n Related task: Comments\n Related task: Here_document\n\n", "output": "\u00a0\nCREATE TABLESPACE myTs;\n\u00a0\nCOMMENT ON TABLESPACE myTs IS 'Description of the tablespace.';\n\u00a0\nCREATE SCHEMA mySch;\n\u00a0\nCOMMENT ON SCHEMA mySch IS 'Description of the schema.';\n\u00a0\nCREATE TYPE myType AS (col1 INT) MODE DB2SQL;\n\u00a0\nCOMMENT ON TYPE mytype IS 'Description of the type.';\n\u00a0\nCREATE TABLE myTab (\n myCol1 INT NOT NULL,\n myCol2 INT\n);\n\u00a0\nCOMMENT ON TABLE myTab IS 'Description of the table.';\nCOMMENT ON myTab (\n myCol1 IS 'Description of the column.',\n myCol2 IS 'Description of the column.'\n);\n\u00a0\nALTER TABLE myTab ADD CONSTRAINT myConst PRIMARY KEY (myCol1);\n\u00a0\nCOMMENT ON CONSTRAINT myTab.myConst IS 'Description of the constraint.';\n\u00a0\nCREATE INDEX myInd ON\n myTab (myCol2);\n\u00a0\nCOMMENT ON INDEX myInd IS 'Description of the index.';\n\u00a0\n-- V11.1\nCREATE USAGE LIST myUsList FOR TABLE myTab;\n\u00a0\nCOMMENT ON USAGE LISTmyUsList IS 'Description of the usage list.';\n\u00a0\n/**\n * Detailed description of the trigger.\n */\nCREATE TRIGGER myTrig\n AFTER INSERT ON myTab\n REFERENCING NEW AS N\n FOR EACH ROW\n BEGIN\n END;\n\u00a0\nCOMMENT ON TRIGGER myTrig IS 'General description of the trigger.';\n\u00a0\nCREATE VARIABLE myVar INT;\n\u00a0\nCOMMENT ON VARIABLE myVar IS 'General description of the variable.';\n\u00a0\n/**\n * General description of the function (reads until the first dot).\n * Detailed description of the function, until the first empty line.\n *\n * IN VAR1\n * Description of IN parameter in variable VAR1.\n * OUT VAR2\n * Description of OUT parameter in variable VAR2.\n * INOUT VAR3\n * Description of INOUT parameter in variable VAR3.\n * RETURNS Description of what it returns.\n */\nCREATE FUNCTION myfun (\n IN VAR1 INT,\n OUT VAR2 INT,\n INOUT VAR3 INT)\n RETURNS INT\n BEGIN\n END;\n\u00a0\n/**\n * General description of the procedure (reads until the first dot).\n * Detailed description of the procedure, until the first empty line.\n *\n * IN VAR1\n * Description of IN parameter in variable VAR1.\n * OUT VAR2\n * Description of OUT parameter in variable VAR2.\n * INOUT VAR3\n * Description of INOUT parameter in variable VAR3.\n */\nCREATE PROCEDURE myProc (\n IN VAR1 INT,\n OUT VAR2 INT,\n INOUT VAR3 INT)\n BEGIN\n END;\n\u00a0\nCREATE MODULE myMod;\n\u00a0\nCOMMENT ON MODULE myMod IS 'General description of the module.';\n\u00a0\n/**\n * General description of the procedure (reads until the first dot).\n * Detailed description of the procedure, until the first empty line.\n *\n * IN VAR1\n * Description of IN parameter in variable VAR1.\n * OUT VAR2\n * Description of OUT parameter in variable VAR2.\n * INOUT VAR3\n * Description of INOUT parameter in variable VAR3.\n */\nALTER MODULE myMod\n ADD PROCEDURE myProc (\n IN VAR1 INT,\n OUT VAR2 INT,\n INOUT VAR3 INT)\n BEGIN\n END;\n\u00a0\nCREATE ROLE myRole;\n\u00a0\nCOMMENT ON ROLE myRole IS 'Description of the role.';\n\u00a0\nCREATE SEQUENCE mySeq;\n\u00a0\nCOMMENT ON ROLE mySeq IS 'Description of the sequence.';\n\u00a0", "input": ""}, {"instruction": "Task\n\nGiven a character string \u00a0 (which may be empty, or have a length of zero characters):\n\n \u00a0 create a function/procedure/routine to:\n \u00a0 determine if all the characters in the string are the same\n \u00a0 indicate if or which character is different from the previous character\n \u00a0 display each string and its length \u00a0 (as the strings are being examined)\n \u00a0 a zero\u2500length (empty) string shall be considered as all the same character(s)\n \u00a0 process the strings from left\u2500to\u2500right\n \u00a0 if \u00a0 \u00a0 \u00a0 all the same character, \u00a0 display a message saying such\n \u00a0 if not all the same character, \u00a0 then:\n \u00a0 display a message saying such\n \u00a0 display what character is different\n \u00a0 only the 1st different character need be displayed\n \u00a0 display where the different character is in the string\n \u00a0 the above messages can be part of a single message\n \u00a0 display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values \u00a0 (strings):\n\n \u00a0 a string of length \u00a0 0 \u00a0 (an empty string)\n \u00a0 a string of length \u00a0 3 \u00a0 which contains three blanks\n \u00a0 a string of length \u00a0 1 \u00a0 which contains: \u00a0 2\n \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 333\n \u00a0 a string of length \u00a0 3 \u00a0 which contains: \u00a0 .55\n \u00a0 a string of length \u00a0 6 \u00a0 which contains: \u00a0 tttTTT\n \u00a0 a string of length \u00a0 9 \u00a0 with a blank in the middle: \u00a0 4444 \u00a0 444k\n\n\nShow all output here on this page.\n\n\nOther tasks related to string operations:\n\nMetrics\n Array length\n String length\n Copy a string\n Empty string \u00a0(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 \u00a0(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", "output": "\u00a0\n/*\nThis code is an implementation of \"Determination if a string has all the same characters\" in SQL ORACLE 19c \np_in_str -- input string\n*/\nWITH\n FUNCTION same_characters_in_string(p_in_str IN varchar2) RETURN varchar2 IS\n v_que varchar2(32767)\u00a0:= p_in_str;\n v_res varchar2(32767);\n v_first varchar2(1);\n v_next varchar2(1);\nBEGIN\n v_first\u00a0:= substr(v_que,1,1);\n IF v_first IS NULL THEN \n v_res\u00a0:= '\"\" length:0 all characters are the same';\n ELSE\n FOR i IN 2..LENGTH(v_que)\n loop\n v_next\u00a0:= substr(v_que,i,1); \n IF v_first\u00a0!= v_next THEN\n v_res\u00a0:= '\"'||v_que||'\" length:'||LENGTH(v_que)||', first different character \"'||v_next||'\"(0x'||rawtohex(utl_raw.cast_to_raw(v_next))||') at position:'|| i;\n exit; \n END IF; \n END loop;\n v_res\u00a0:= nvl(v_res,'\"'||v_que||'\" length:'||LENGTH(v_que)||' all characters are the same');\n END IF; \n RETURN v_res;\nEND;\n\u00a0\n--Test\nSELECT same_characters_in_string('') AS res FROM dual\nUNION ALL \nSELECT same_characters_in_string(' ') AS res FROM dual\nUNION ALL \nSELECT same_characters_in_string('2') AS res FROM dual\nUNION ALL \nSELECT same_characters_in_string('333') AS res FROM dual\nUNION ALL\nSELECT same_characters_in_string('.55') AS res FROM dual\nUNION ALL\nSELECT same_characters_in_string('tttTTT') AS res FROM dual\nUNION ALL \nSELECT same_characters_in_string('4444 444k') AS res FROM dual\n;\n\u00a0", "input": ""}, {"instruction": "Task\n\nWrite a function to detect a \u00a0 divide by zero error \u00a0 without checking if the denominator is zero.\n\n\n\n", "output": "FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)\nRETURN BOOLEAN\nIS\n result NUMBER;\nBEGIN\n result := n1/n2;\n RETURN(FALSE);\nEXCEPTION\n WHEN ZERO_DIVIDE THEN\n RETURN(TRUE);\nEND divide;", "input": ""}, {"instruction": "Task\n\nWrite a function to detect a \u00a0 divide by zero error \u00a0 without checking if the denominator is zero.\n\n\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON@\n\u00a0\nCREATE OR REPLACE FUNCTION DIVISION(\n IN NUMERATOR DECIMAL(5, 3),\n IN DENOMINATOR DECIMAL(5, 3)\n ) RETURNS SMALLINT\n BEGIN\n DECLARE RET SMALLINT DEFAULT 1;\n DECLARE TMP DECIMAL(5, 3);\n DECLARE CONTINUE HANDLER FOR SQLSTATE '22012'\n SET RET = 1;\n\u00a0\n SET RET = 0;\n SET TMP = NUMERATOR / DENOMINATOR;\n RETURN RET;\n END @\n\u00a0\nVALUES DIVISION(10, 2)@\nVALUES DIVISION(10, 3)@\nVALUES DIVISION(10, 0)@\n\u00a0", "input": ""}, {"instruction": "Task\n\nCreate a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.\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 \u00a0(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 \u00a0(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", "output": "FUNCTION IsNumeric( VALUE IN VARCHAR2 )\nRETURN BOOLEAN\nIS\n help NUMBER;\nBEGIN\n help := TO_NUMBER( VALUE );\n RETURN( TRUE );\nEXCEPTION\n WHEN OTHERS THEN\n RETURN( FALSE );\nEND;", "input": ""}, {"instruction": "Task\n\nCreate a function/use an in-built function, to compute the \u00a0 dot product, \u00a0 also known as the \u00a0 scalar product \u00a0 of two vectors.\n\nIf possible, make the vectors of arbitrary length.\n\n\n\nAs an example, compute the dot product of the vectors:\n\n \u00a0 [1, \u00a03, -5] \u00a0 \u00a0 and \n \u00a0 [4, -2, -1] \n\n\nIf implementing the dot product of two vectors directly:\n\n \u00a0 each vector must be the same length\n \u00a0 multiply corresponding terms from each vector\n \u00a0 sum the products \u00a0 (to produce the answer)\n\n\nRelated task\n\n \u00a0 Vector products\n\n", "output": "SELECT i, k, SUM(A.N*B.N) AS N\n FROM A INNER JOIN B ON A.j=B.j\n GROUP BY i, k", "input": ""}, {"instruction": "Task\n\nCreate a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.\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 \u00a0(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 \u00a0(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", "output": "DECLARE @s VARCHAR(10)\nSET @s = '1234.56'\n\u00a0\nprint isnumeric(@s) --prints 1 if numeric, 0 if not.\n\u00a0\nIF isnumeric(@s)=1 BEGIN print 'Numeric' END \nELSE print 'Non-numeric'", "input": ""}, {"instruction": "Task\n\nCreate a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.\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 \u00a0(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 \u00a0(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", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nCREATE OR REPLACE FUNCTION IS_NUMERIC (\n IN STRING VARCHAR(10)\n ) RETURNS SMALLINT\n -- ) RETURNS BOOLEAN\n BEGIN\n DECLARE RET SMALLINT;\n -- DECLARE RET BOOLEAN;\n DECLARE TMP INTEGER;\n DECLARE CONTINUE HANDLER FOR SQLSTATE '22018'\n SET RET = 1;\n -- SET RET = FALSE;\n\u00a0\n SET RET = 0;\n --SET RET = TRUE;\n SET TMP = INTEGER(STRING);\n RETURN RET;\n END @\n\u00a0\nVALUES IS_NUMERIC('5')@\nVALUES IS_NUMERIC('0')@\nVALUES IS_NUMERIC('-1')@\nVALUES IS_NUMERIC('A')@\nVALUES IS_NUMERIC('-')@\nVALUES IS_NUMERIC('z')@\nVALUES IS_NUMERIC('')@\nVALUES IS_NUMERIC(' ')@\n\u00a0", "input": ""}, {"instruction": "Task\n\nGiven the date string \"March 7 2009 7:30pm EST\", \n\noutput the time 12 hours later in any human-readable format.\n\nAs extra credit, display the resulting time in a time zone different from your own.\n\n\n\n", "output": "\u00a0\n-- March 7 2009 7:30pm EST\n\u00a0\nSELECT \nTO_TIMESTAMP_TZ(\n'March 7 2009 7:30pm EST',\n'MONTH DD YYYY HH:MIAM TZR'\n)\nat TIME zone 'US/Eastern' orig_dt_time\nFROM dual;\n\u00a0\n-- 12 hours later DST change\n\u00a0\nSELECT \n(TO_TIMESTAMP_TZ(\n'March 7 2009 7:30pm EST',\n'MONTH DD YYYY HH:MIAM TZR'\n)+\nINTERVAL '12' HOUR)\nat TIME zone 'US/Eastern' plus_12_dst\nFROM dual;\n\u00a0\n-- 12 hours later no DST change\n-- Arizona time, always MST\n\u00a0\nSELECT \n(TO_TIMESTAMP_TZ(\n'March 7 2009 7:30pm EST',\n'MONTH DD YYYY HH:MIAM TZR'\n)+\nINTERVAL '12' HOUR)\nat TIME zone 'US/Arizona' plus_12_nodst\nFROM dual;\n\u00a0", "input": ""}, {"instruction": "A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).\n\n\n\nTask\n\nIn what years between 2008 and 2121 will the 25th of December be a Sunday?\n\nUsing any standard date handling libraries of your programming language;\ncompare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to \u00a0 y2k \u00a0 type problems.\n\n\n\n", "output": "SELECT EXTRACT(YEAR FROM dt) AS year_with_xmas_on_sunday\nFROM ( \n SELECT add_months(DATE '2008-12-25', 12 * (level - 1)) AS dt\n FROM dual\n CONNECT BY level <= 2121 - 2008 + 1\n ) \nWHERE to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'\nORDER BY 1\n;", "input": ""}, {"instruction": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\n\nTask\n\nDisplay the \u00a0 current date \u00a0 in the formats of:\n\n \u00a0 2007-11-23 \u00a0 \u00a0 and \n \u00a0 Friday, November 23, 2007\n\n", "output": "\u00a0\nSELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;\n\u00a0\nSELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual;\n\u00a0", "input": ""}, {"instruction": "In this task, the job is to create a new empty file called \"output.txt\" of size 0 bytes\nand an empty directory called \"docs\". This should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root.\n", "output": "\u00a0\nBEGIN\n DECLARE UTL_FILE_HANDLER UTL_FILE.FILE_TYPE;\n DECLARE DIR_ALIAS_CURRENT VARCHAR(128);\n DECLARE DIR_ALIAS_ROOT VARCHAR(128);\n DECLARE DIRECTORY VARCHAR(1024);\n DECLARE FILENAME VARCHAR(255);\n\u00a0\n SET DIR_ALIAS_CURRENT = 'outputFileCurrent';\n SET DIRECTORY = '/home/db2inst1/doc';\n SET FILENAME = 'output.txt';\n\u00a0\n CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_CURRENT, DIRECTORY);\n SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_CURRENT, FILENAME, 'a');\n CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);\n CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);\n\u00a0\n SET DIR_ALIAS_ROOT = 'outputFileRoot';\n SET DIRECTORY = '/doc';\n\u00a0\n CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_ROOT, DIRECTORY);\n SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_ROOT, FILENAME, 'a');\n CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);\n CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);\nEND @\n\u00a0", "input": ""}, {"instruction": "Task[edit]\nWrite a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.\n\nThe task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.\n\nDo not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.\n\n\n\nTest case\n\nUse this to compute the standard deviation of this demonstration set, \n\n\n\n{\n2\n,\n4\n,\n4\n,\n4\n,\n5\n,\n5\n,\n7\n,\n9\n}\n\n\n{\\displaystyle \\{2,4,4,4,5,5,7,9\\}}\n\n, which is \n\n\n\n2\n\n\n{\\displaystyle 2}\n\n.\n\n\n\nRelated tasks\n\n Random numbers\n\n\nTasks for calculating statistical measures\n\n\n\nin one go\nmoving (sliding window)\nmoving (cumulative)\n\nMean\nArithmetic\n\nStatistics/Basic\nAverages/Arithmetic mean\nAverages/Pythagorean means\n\n\nAverages/Simple moving average\n\n\n\n\nGeometric\n\nAverages/Pythagorean means\n\n\n\n\nHarmonic\n\nAverages/Pythagorean means\n\n\n\n\nQuadratic\n\nAverages/Root mean square\n\n\n\n\nCircular\n\nAverages/Mean angle\nAverages/Mean time of day\n\n\n\n\nMedian\n\nAverages/Median\n\n\n\n\nMode\n\nAverages/Mode\n\n\n\n\nStandard deviation\n\nStatistics/Basic\n\n\n\nCumulative standard deviation\n\n\n\n", "output": "-- the minimal table\nCREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL);\n\u00a0\n-- code modularity with view, we could have used a common table expression instead\nCREATE VIEW vteststd AS\n SELECT COUNT(n) AS cnt,\n SUM(n) AS tsum,\n SUM(POWER(n,2)) AS tsqr\nFROM teststd;\n\u00a0\n-- you can of course put this code into every query\nCREATE OR REPLACE FUNCTION std_dev() RETURNS DOUBLE PRECISION AS $$\n SELECT SQRT(tsqr/cnt - (tsum/cnt)^2) FROM vteststd;\n$$ LANGUAGE SQL;\n\u00a0\n-- test data is: 2,4,4,4,5,5,7,9\nINSERT INTO teststd VALUES (2);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (4);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (4);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (4);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (5);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (5);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (7);\nSELECT std_dev() AS std_deviation;\nINSERT INTO teststd VALUES (9);\nSELECT std_dev() AS std_deviation;\n-- cleanup test data\nDELETE FROM teststd;\n\u00a0", "input": ""}, {"instruction": "In this task, the job is to create a new empty file called \"output.txt\" of size 0 bytes\nand an empty directory called \"docs\". This should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root.\n", "output": "\u00a0\n/*\n*Use '/' for *nix. Use whatever your root directory is on Windows. \n*Must be run as admin.\n*/\n.shell mkdir \"docs\";\n.shell mkdir \"/docs\";\n.output output.txt\n.output /output.txt\n\u00a0", "input": ""}, {"instruction": "The Game of Life is a \u00a0 cellular automaton \u00a0 devised by the British mathematician \u00a0 John Horton Conway \u00a0 in 1970. \u00a0 It is the best-known example of a cellular automaton.\n\nConway's game of life is described \u00a0 here:\n\nA cell \u00a0 C \u00a0 is represented by a \u00a0 1 \u00a0 when alive, \u00a0 or \u00a0 0 \u00a0 when dead, \u00a0 in an \u00a0 m-by-m \u00a0 (or m\u00d7m) \u00a0 square array of cells.\n\nWe calculate \u00a0 N \u00a0 - the sum of live cells in C's \u00a0 eight-location neighbourhood, \u00a0 then cell \u00a0 C \u00a0 is alive or dead in the next generation based on the following table:\n\n C N new C\n 1 0,1 -> 0 # Lonely\n 1 4,5,6,7,8 -> 0 # Overcrowded\n 1 2,3 -> 1 # Lives\n 0 3 -> 1 # It takes three to give birth!\n 0 0,1,2,4,5,6,7,8 -> 0 # Barren\n\nAssume cells beyond the boundary are always dead.\n\nThe \"game\" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. \u00a0 One interacts with the Game of Life by creating an initial configuration and observing how it evolves.\n\n\n\nTask\n\nAlthough you should test your implementation on more complex examples such as the \u00a0 glider \u00a0 in a larger universe, \u00a0 show the action of the blinker \u00a0 (three adjoining cells in a row all alive), \u00a0 over three generations, in a 3 by 3 grid.\n\n\n\nReferences\n\n \u00a0 Its creator John Conway, explains \u00a0 the game of life. \u00a0 Video from numberphile on youtube.\n \u00a0 John Conway \u00a0 Inventing Game of Life \u00a0 - Numberphile video.\n\n\nRelated task\n\n \u00a0 Langton's ant \u00a0 - another well known cellular automaton.\n\n", "output": "\u00a0\n-- save these lines in a file called\n-- setupworld.sql\n\u00a0\n-- turn off feedback for cleaner display\n\u00a0\nSET feedback off\n\u00a0\n-- 3 x 3 world\n\u00a0\n-- alive has coordinates of living cells\n\u00a0\nDROP TABLE alive;\n\u00a0\nCREATE TABLE alive (x NUMBER,y NUMBER);\n\u00a0\n-- three alive up the middle\n-- * \n-- * \n-- *\n\u00a0\nINSERT INTO alive VALUES (2,1);\nINSERT INTO alive VALUES (2,2);\nINSERT INTO alive VALUES (2,3);\n\u00a0\ncommit;\n\u00a0\n-- save these lines in a file called\nnewgeneration.SQL\n\u00a0\n-- adjact contains one row for each pair of \n-- coordinates that is adjacent to a living cell\n\u00a0\nDROP TABLE adjacent;\n\u00a0\nCREATE TABLE adjacent (x NUMBER,y NUMBER);\n\u00a0\n-- add row for each of the 8 adjacent squares\n\u00a0\nINSERT INTO adjacent SELECT x-1,y-1 FROM alive; \nINSERT INTO adjacent SELECT x-1,y FROM alive;\nINSERT INTO adjacent SELECT x-1,y+1 FROM alive;\nINSERT INTO adjacent SELECT x,y-1 FROM alive; \nINSERT INTO adjacent SELECT x,y+1 FROM alive;\nINSERT INTO adjacent SELECT x+1,y-1 FROM alive; \nINSERT INTO adjacent SELECT x+1,y FROM alive;\nINSERT INTO adjacent SELECT x+1,y+1 FROM alive;\n\u00a0\ncommit;\n\u00a0\n-- delete rows for squares that are outside the world\n\u00a0\nDELETE FROM adjacent WHERE x<1 OR y<1 OR x>3 OR y>3;\n\u00a0\ncommit;\n\u00a0\n-- table counts is the number of live cells\n-- adjacent to that point\n\u00a0\nDROP TABLE counts;\n\u00a0\nCREATE TABLE counts AS \nSELECT x,y,COUNT(*) n\nFROM adjacent a\nGROUP BY x,y;\n\u00a0\n-- C N new C\n-- 1 0,1 -> 0 # Lonely\n-- 1 4,5,6,7,8 -> 0 # Overcrowded\n-- 1 2,3 -> 1 # Lives\n-- 0 3 -> 1 # It takes three to give birth!\n-- 0 0,1,2,4,5,6,7,8 -> 0 # Barren\n\u00a0\n-- delete the ones who die\n\u00a0\nDELETE FROM alive a\nWHERE\n((a.x,a.y) NOT IN (SELECT x,y FROM counts)) OR\n((SELECT c.n FROM counts c WHERE a.x=c.x AND a.y=c.y) IN \n(1,4,5,6,7,8));\n\u00a0\n-- insert the ones that are born\n\u00a0\nINSERT INTO alive a\nSELECT x,y FROM counts c\nWHERE c.n=3 AND\n((c.x,c.y) NOT IN (SELECT x,y FROM alive));\n\u00a0\ncommit;\n\u00a0\n-- create output table\n\u00a0\nDROP TABLE output;\n\u00a0\nCREATE TABLE output AS\nSELECT rownum y,' ' x1,' ' x2,' ' x3\nFROM dba_tables WHERE rownum < 4;\n\u00a0\nUPDATE output SET x1='*'\nWHERE (1,y) IN\n(SELECT x,y FROM alive);\n\u00a0\nUPDATE output SET x2='*'\nWHERE (2,y) IN\n(SELECT x,y FROM alive);\n\u00a0\nUPDATE output SET x3='*'\nWHERE (3,y) IN\n(SELECT x,y FROM alive);\n\u00a0\ncommit\n\u00a0\n-- output configuration\n\u00a0\nSELECT x1||x2||x3 WLD\nFROM output\nORDER BY y DESC;\n\u00a0", "input": ""}, {"instruction": "Task\n\nShow all ways to include text in a language source file\nthat's completely ignored by the compiler or interpreter.\n\n\n\nRelated tasks\n\n \u00a0 Documentation\n \u00a0 Here_document\n\n\nSee also\n\n \u00a0 Wikipedia\n \u00a0 xkcd (Humor: hand gesture denoting // for \"commenting out\" people.)\n\n", "output": "--this is a single line comment", "input": ""}, {"instruction": "Task\n\nShow all ways to include text in a language source file\nthat's completely ignored by the compiler or interpreter.\n\n\n\nRelated tasks\n\n \u00a0 Documentation\n \u00a0 Here_document\n\n\nSee also\n\n \u00a0 Wikipedia\n \u00a0 xkcd (Humor: hand gesture denoting // for \"commenting out\" people.)\n\n", "output": "SELECT * FROM mytable -- Selects all columns and rows", "input": ""}, {"instruction": "Task\n\nShow all ways to include text in a language source file\nthat's completely ignored by the compiler or interpreter.\n\n\n\nRelated tasks\n\n \u00a0 Documentation\n \u00a0 Here_document\n\n\nSee also\n\n \u00a0 Wikipedia\n \u00a0 xkcd (Humor: hand gesture denoting // for \"commenting out\" people.)\n\n", "output": "\u00a0\n--This is a single line comment.\n\u00a0", "input": ""}, {"instruction": "Control Structures\nThese are examples of control structures. You may also be interested in:\n\n Conditional structures\n Exceptions\n Flow-control structures\n Loops\n\nTask\n\nList the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.\n\nCommon conditional structures include if-then-else and switch.\n\nLess common are arithmetic if, ternary operator and Hash-based conditionals.\n\nArithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.\n\n\n", "output": "CASE WHEN a THEN b ELSE c END\n\u00a0\nDECLARE @n INT\nSET @n=124\nprint CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END\n\u00a0\n--If/ElseIf expression\nSET @n=5\nprint CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END", "input": ""}, {"instruction": "Suppose \u00a0 \n\n\n\n\nn\n\n1\n\n\n\n\n{\\displaystyle n_{1}}\n\n, \u00a0 \n\n\n\n\nn\n\n2\n\n\n\n\n{\\displaystyle n_{2}}\n\n, \u00a0 \n\n\n\n\u2026\n\n\n{\\displaystyle \\ldots }\n\n, \u00a0 \n\n\n\n\nn\n\nk\n\n\n\n\n{\\displaystyle n_{k}}\n\n \u00a0 are positive integers that are pairwise co-prime. \u00a0\n\nThen, for any given sequence of integers \u00a0 \n\n\n\n\na\n\n1\n\n\n\n\n{\\displaystyle a_{1}}\n\n, \u00a0 \n\n\n\n\na\n\n2\n\n\n\n\n{\\displaystyle a_{2}}\n\n, \u00a0 \n\n\n\n\u2026\n\n\n{\\displaystyle \\dots }\n\n, \u00a0 \n\n\n\n\na\n\nk\n\n\n\n\n{\\displaystyle a_{k}}\n\n, \u00a0 there exists an integer \u00a0 \n\n\n\nx\n\n\n{\\displaystyle x}\n\n \u00a0 solving the following system of simultaneous congruences:\n\n \n\n\n\n\n\n\n\nx\n\n\n\n\u2261\n\na\n\n1\n\n\n\n\n(\nmod\n\n\nn\n\n1\n\n\n)\n\n\n\n\n\nx\n\n\n\n\u2261\n\na\n\n2\n\n\n\n\n(\nmod\n\n\nn\n\n2\n\n\n)\n\n\n\n\n\n\n\n\n\u00a0\n\u00a0\n\u22ee\n\n\n\n\nx\n\n\n\n\u2261\n\na\n\nk\n\n\n\n\n(\nmod\n\n\nn\n\nk\n\n\n)\n\n\n\n\n\n\n\n{\\displaystyle {\\begin{aligned}x&\\equiv a_{1}{\\pmod {n_{1}}}\\\\x&\\equiv a_{2}{\\pmod {n_{2}}}\\\\&{}\\ \\ \\vdots \\\\x&\\equiv a_{k}{\\pmod {n_{k}}}\\end{aligned}}}\n\n\nFurthermore, all solutions \u00a0 \n\n\n\nx\n\n\n{\\displaystyle x}\n\n \u00a0 of this system are congruent modulo the product, \u00a0 \n\n\n\nN\n=\n\nn\n\n1\n\n\n\nn\n\n2\n\n\n\u2026\n\nn\n\nk\n\n\n\n\n{\\displaystyle N=n_{1}n_{2}\\ldots n_{k}}\n\n.\n\n\n\nTask\n\nWrite a program to solve a system of linear congruences by applying the \u00a0 Chinese Remainder Theorem.\n\nIf the system of equations cannot be solved, your program must somehow indicate this.\n\n(It may throw an exception or return a special false value.)\n\nSince there are infinitely many solutions, the program should return the unique solution \u00a0 \n\n\n\ns\n\n\n{\\displaystyle s}\n\n \u00a0 where \u00a0 \n\n\n\n0\n\u2264\ns\n\u2264\n\nn\n\n1\n\n\n\nn\n\n2\n\n\n\u2026\n\nn\n\nk\n\n\n\n\n{\\displaystyle 0\\leq s\\leq n_{1}n_{2}\\ldots n_{k}}\n\n.\n\n\nShow the functionality of this program by printing the result such that the \u00a0 \n\n\n\nn\n\n\n{\\displaystyle n}\n\n's \u00a0 are \u00a0 \n\n\n\n[\n3\n,\n5\n,\n7\n]\n\n\n{\\displaystyle [3,5,7]}\n\n \u00a0 and the \u00a0 \n\n\n\na\n\n\n{\\displaystyle a}\n\n's \u00a0 are \u00a0 \n\n\n\n[\n2\n,\n3\n,\n2\n]\n\n\n{\\displaystyle [2,3,2]}\n\n.\n\n\nAlgorithm: \u00a0 The following algorithm only applies if the \u00a0 \n\n\n\n\nn\n\ni\n\n\n\n\n{\\displaystyle n_{i}}\n\n's \u00a0 are pairwise co-prime.\n\nSuppose, as above, that a solution is required for the system of congruences:\n\n \n\n\n\nx\n\u2261\n\na\n\ni\n\n\n\n\n(\nmod\n\n\nn\n\ni\n\n\n)\n\n\n\nf\no\nr\n\n\ni\n=\n1\n,\n\u2026\n,\nk\n\n\n{\\displaystyle x\\equiv a_{i}{\\pmod {n_{i}}}\\quad \\mathrm {for} \\;i=1,\\ldots ,k}\n\n\nAgain, to begin, the product \u00a0 \n\n\n\nN\n=\n\nn\n\n1\n\n\n\nn\n\n2\n\n\n\u2026\n\nn\n\nk\n\n\n\n\n{\\displaystyle N=n_{1}n_{2}\\ldots n_{k}}\n\n \u00a0 is defined.\n\nThen a solution \u00a0 \n\n\n\nx\n\n\n{\\displaystyle x}\n\n \u00a0 can be found as follows:\n\nFor each \u00a0 \n\n\n\ni\n\n\n{\\displaystyle i}\n\n, \u00a0 the integers \u00a0 \n\n\n\n\nn\n\ni\n\n\n\n\n{\\displaystyle n_{i}}\n\n \u00a0 and \u00a0 \n\n\n\nN\n\n/\n\n\nn\n\ni\n\n\n\n\n{\\displaystyle N/n_{i}}\n\n \u00a0 are co-prime.\n\nUsing the \u00a0 Extended Euclidean algorithm, \u00a0 we can find integers \u00a0 \n\n\n\n\nr\n\ni\n\n\n\n\n{\\displaystyle r_{i}}\n\n \u00a0 and \u00a0 \n\n\n\n\ns\n\ni\n\n\n\n\n{\\displaystyle s_{i}}\n\n \u00a0 such that \u00a0 \n\n\n\n\nr\n\ni\n\n\n\nn\n\ni\n\n\n+\n\ns\n\ni\n\n\nN\n\n/\n\n\nn\n\ni\n\n\n=\n1\n\n\n{\\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1}\n\n.\n\nThen, one solution to the system of simultaneous congruences is:\n\n \n\n\n\nx\n=\n\n\u2211\n\ni\n=\n1\n\n\nk\n\n\n\na\n\ni\n\n\n\ns\n\ni\n\n\nN\n\n/\n\n\nn\n\ni\n\n\n\n\n{\\displaystyle x=\\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}}\n\n\nand the minimal solution,\n\n \n\n\n\nx\n\n\n(\nmod\n\nN\n)\n\n\n\n{\\displaystyle x{\\pmod {N}}}\n\n.\n\n", "output": "CREATE TEMPORARY TABLE inputs(remainder INT, modulus INT);\n\u00a0\nINSERT INTO inputs VALUES (2, 3), (3, 5), (2, 7);\n\u00a0\nWITH recursive\n\u00a0\n-- Multiply out the product of moduli\nmultiplication(idx, product) AS (\n SELECT 1, 1\n\u00a0\n UNION ALL\n\u00a0\n SELECT\n multiplication.idx+1,\n multiplication.product * inputs.modulus\n FROM\n multiplication,\n inputs\n WHERE\n inputs.rowid = multiplication.idx\n),\n\u00a0\n-- Take the final value from the product table\nproduct(final_value) AS (\n SELECT MAX(product) FROM multiplication\n),\n\u00a0\n-- Calculate the multiplicative inverse from each equation\nmultiplicative_inverse(id, a, b, x, y) AS (\n SELECT\n inputs.modulus,\n product.final_value / inputs.modulus,\n inputs.modulus,\n 0,\n 1\n FROM\n inputs,\n product\n\u00a0\n UNION ALL\n\u00a0\n SELECT\n id,\n b, a%b,\n y - (a/b)*x, x\n FROM\n multiplicative_inverse\n WHERE\n a>0\n)\n-- Combine residues into final answer\nSELECT\n SUM(\n (y\u00a0% inputs.modulus) * inputs.remainder * (product.final_value / inputs.modulus)\n )\u00a0% product.final_value\n FROM\n multiplicative_inverse, product, inputs\n WHERE\n a=1 AND multiplicative_inverse.id = inputs.modulus;\n\u00a0", "input": ""}, {"instruction": "In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.\n\nShow how to call a static or class method, and an instance method of a class.\n", "output": "CREATE OR REPLACE TYPE myClass AS OBJECT (\n -- A class needs at least one member even though we don't use it\n dummy NUMBER,\n STATIC FUNCTION static_method RETURN VARCHAR2,\n MEMBER FUNCTION instance_method RETURN VARCHAR2\n);\n/\nCREATE OR REPLACE TYPE BODY myClass AS\n STATIC FUNCTION static_method RETURN VARCHAR2 IS\n BEGIN\n RETURN 'Called myClass.static_method';\n END static_method;\n\u00a0\n MEMBER FUNCTION instance_method RETURN VARCHAR2 IS\n BEGIN\n RETURN 'Called myClass.instance_method';\n END instance_method;\nEND;\n/\n\u00a0\nDECLARE\n myInstance myClass;\nBEGIN\n myInstance := myClass(NULL);\n DBMS_OUTPUT.put_line( myClass.static_method() );\n DBMS_OUTPUT.put_line( myInstance.instance_method() );\nEND;/", "input": ""}, {"instruction": "Task\n\nShow one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n\n{1, 2} \u00d7 {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\nand, in contrast:\n\n{3, 4} \u00d7 {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n\n {1, 2} \u00d7 {} = {}\n {} \u00d7 {1, 2} = {}\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n\n {1776, 1789} \u00d7 {7, 12} \u00d7 {4, 14, 23} \u00d7 {0, 1}\n {1, 2, 3} \u00d7 {30} \u00d7 {500, 100}\n {1, 2, 3} \u00d7 {} \u00d7 {500, 100}\n\n", "output": "-- set up list 1\nCREATE TABLE L1 (VALUE INTEGER);\nINSERT INTO L1 VALUES (1);\nINSERT INTO L1 VALUES (2);\n-- set up list 2\nCREATE TABLE L2 (VALUE INTEGER);\nINSERT INTO L2 VALUES (3);\nINSERT INTO L2 VALUES (4);\n-- get the product\nSELECT * FROM L1, L2;", "input": ""}, {"instruction": "\n\n This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)\n\n\nBenford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.\n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.\n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit \n\n\n\nd\n\n\n{\\displaystyle d}\n\n\u00a0\u00a0(\n\n\n\nd\n\u2208\n{\n1\n,\n\u2026\n,\n9\n}\n\n\n{\\displaystyle d\\in \\{1,\\ldots ,9\\}}\n\n) occurs with probability\n\n \n\n\n\nP\n(\nd\n)\n=\n\nlog\n\n10\n\n\n\u2061\n(\nd\n+\n1\n)\n\u2212\n\nlog\n\n10\n\n\n\u2061\n(\nd\n)\n=\n\nlog\n\n10\n\n\n\u2061\n\n(\n1\n+\n\n\n1\nd\n\n\n)\n\n\n\n{\\displaystyle P(d)=\\log _{10}(d+1)-\\log _{10}(d)=\\log _{10}\\left(1+{\\frac {1}{d}}\\right)}\n\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.\n\nYou can generate them or load them from a file; whichever is easiest.\n\nDisplay your actual vs expected distribution.\n\n\nFor extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n\nSee also:\n numberphile.com.\n A starting page on Wolfram Mathworld is Benfords Law .\n\n", "output": "\u00a0\nWITH recursive \nconstant(val) AS\n(\nSELECT 1000.\n)\n,\nfib(a,b) AS\n(\nSELECT CAST(0 AS NUMERIC), CAST(1 AS NUMERIC)\nUNION ALL\nSELECT b,a+b\nFROM fib\n)\n,\nbenford(first_digit, probability_real, probability_theoretical) AS\n(\nSELECT *, \n\tCAST(log(1. + 1./CAST(first_digit AS INT)) AS NUMERIC(5,4)) probability_theoretical\nFROM (\n\tSELECT first_digit, CAST(COUNT(1)/(SELECT val FROM constant) AS NUMERIC(5,4)) probability_real FROM\n\t(\n\t\tSELECT SUBSTRING(CAST(a AS VARCHAR(100)),1,1) first_digit\n\t\tFROM fib\n\t\tWHERE SUBSTRING(CAST(a AS VARCHAR(100)),1,1) <> '0'\n\t\tLIMIT (SELECT val FROM constant)\n\t) t\n\tGROUP BY first_digit\n) f\nORDER BY first_digit ASC\n)\nSELECT *\nFROM benford CROSS JOIN\n (SELECT CAST(corr(probability_theoretical,probability_real) AS NUMERIC(5,4)) correlation\n FROM benford) c\n\u00a0", "input": ""}, {"instruction": "\n\n This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)\n\n\nBenford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.\n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.\n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit \n\n\n\nd\n\n\n{\\displaystyle d}\n\n\u00a0\u00a0(\n\n\n\nd\n\u2208\n{\n1\n,\n\u2026\n,\n9\n}\n\n\n{\\displaystyle d\\in \\{1,\\ldots ,9\\}}\n\n) occurs with probability\n\n \n\n\n\nP\n(\nd\n)\n=\n\nlog\n\n10\n\n\n\u2061\n(\nd\n+\n1\n)\n\u2212\n\nlog\n\n10\n\n\n\u2061\n(\nd\n)\n=\n\nlog\n\n10\n\n\n\u2061\n\n(\n1\n+\n\n\n1\nd\n\n\n)\n\n\n\n{\\displaystyle P(d)=\\log _{10}(d+1)-\\log _{10}(d)=\\log _{10}\\left(1+{\\frac {1}{d}}\\right)}\n\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.\n\nYou can generate them or load them from a file; whichever is easiest.\n\nDisplay your actual vs expected distribution.\n\n\nFor extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n\nSee also:\n numberphile.com.\n A starting page on Wolfram Mathworld is Benfords Law .\n\n", "output": "-- Create table\nCREATE TABLE benford (num INTEGER);\n\u00a0\n-- Seed table\nINSERT INTO benford (num) VALUES (1);\nINSERT INTO benford (num) VALUES (1);\nINSERT INTO benford (num) VALUES (2);\n\u00a0\n-- Populate table\nINSERT INTO benford (num)\n SELECT\n ult + penult\n FROM\n (SELECT MAX(num) AS ult FROM benford),\n (SELECT MAX(num) AS penult FROM benford WHERE num NOT IN (SELECT MAX(num) FROM benford))\n\u00a0\n-- Repeat as many times as desired\n-- in Oracle SQL*Plus, press \"Slash, Enter\" a lot of times\n-- or wrap this in a loop, but that will require something db-specific...\n\u00a0\n-- Do sums\nSELECT\n digit,\n COUNT(digit) / numbers AS actual,\n log(10, 1 + 1 / digit) AS expected\nFROM\n (\n SELECT\n FLOOR(num/POWER(10,LENGTH(num)-1)) AS digit\n FROM\n benford\n ),\n (\n SELECT\n COUNT(*) AS numbers\n FROM\n benford\n )\nGROUP BY digit, numbers\nORDER BY digit;\n\u00a0\n-- Tidy up\nDROP TABLE benford;", "input": ""}, {"instruction": "\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n\n What is the smallest positive integer whose square ends in the digits 269,696?\n\n\u2014 Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n\nTask[edit]\nThe task is to find out if Babbage had the right answer \u2014 and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.\nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n\nMotivation\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n\n\n", "output": "\u00a0\n/*\nThis code is an implementation of Babbage Problem in SQL ORACLE 19c \np_ziel -- the substring to search for, which can start with leading zeros\np_max -- upper bound of the cycle\nv_max -- safe determination of the upper bound of the cycle\nv_start -- safe starting point\n*/\nWITH\n FUNCTION babbage(p_ziel IN varchar2, p_max INTEGER) RETURN varchar2 IS\n v_max INTEGER\u00a0:= greatest(p_max,to_number('1E+'||LENGTH(to_char(p_ziel))));\n v_start NUMBER\u00a0:= CASE WHEN substr(p_ziel,1,1)='0' THEN CEIL(SQRT('1'||p_ziel)) ELSE CEIL(SQRT(p_ziel)) END;\n v_length NUMBER\u00a0:= to_number('1E+'||LENGTH(to_char(p_ziel))); \n BEGIN\n -- first check\n IF substr(p_ziel,-1) IN (2,3,7,8) THEN \n RETURN 'The exact square of an integer cannot end with '''||substr(p_ziel,-1)||''', so there is no such smallest number whose square ends in '''||p_ziel||'''';\n END IF; \n -- second check\n IF regexp_count(p_ziel,'([^0]0{1,}$)')=1 AND MOD(regexp_count(regexp_substr(p_ziel,'(0{1,}$)'),'0'),2)=1 THEN\n RETURN 'An exact square of an integer cannot end with an odd number of zeros, so there is no such smallest number whose square ends in '''||p_ziel||'''';\n END IF; \n -- main cycle\n while v_start < v_max loop\n exit WHEN MOD(v_start**2,v_length) = p_ziel; \n v_start\u00a0:= v_start + 1; \n END loop;\n -- output \n IF v_start = v_max THEN\n RETURN 'There is no such smallest number before '||v_max||' whose square ends in '''||p_ziel||'''';\n ELSE \n RETURN ''||v_start||' is the smallest number, whose square '||regexp_replace(to_char(v_start**2),'(\\d{1,})('||p_ziel||')','\\1''\\2''')||' ends in '''||p_ziel||''''; \n END IF; \n --\n END;\n\u00a0\n--Test\nSELECT babbage('222',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('33',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('17',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('888',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('1000',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('000',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('269696',100000) AS res FROM dual -- strict Babbage Problem\nUNION ALL \nSELECT babbage('269696',10) AS res FROM dual\nUNION ALL \nSELECT babbage('169696',10) AS res FROM dual\nUNION ALL\nSELECT babbage('19696',100000) AS res FROM dual\nUNION ALL \nSELECT babbage('04',100000) AS res FROM dual;\n\u00a0", "input": ""}, {"instruction": "Task[edit]\nA particular activity of bats occurs at these times of the day:\n\n23:00:17, 23:40:20, 00:12:45, 00:17:19\nUsing the idea that there are twenty-four hours in a day,\nwhich is analogous to there being 360 degrees in a circle,\nmap times of day to and from angles;\nand using the ideas of Averages/Mean angle\ncompute and show the average time of the nocturnal activity\nto an accuracy of one second of time.\n\nSee also\nTasks for calculating statistical measures\n\n\n\nin one go\nmoving (sliding window)\nmoving (cumulative)\n\nMean\nArithmetic\n\nStatistics/Basic\nAverages/Arithmetic mean\nAverages/Pythagorean means\n\n\nAverages/Simple moving average\n\n\n\n\nGeometric\n\nAverages/Pythagorean means\n\n\n\n\nHarmonic\n\nAverages/Pythagorean means\n\n\n\n\nQuadratic\n\nAverages/Root mean square\n\n\n\n\nCircular\n\nAverages/Mean angle\nAverages/Mean time of day\n\n\n\n\nMedian\n\nAverages/Median\n\n\n\n\nMode\n\nAverages/Mode\n\n\n\n\nStandard deviation\n\nStatistics/Basic\n\n\n\nCumulative standard deviation\n\n\n\n", "output": "\u00a0\n--Setup table for testing\nCREATE TABLE time_table(times TIME);\nINSERT INTO time_table VALUES ('23:00:17'::TIME),('23:40:20'::TIME),('00:12:45'::TIME),('00:17:19'::TIME)\n\u00a0\n--Compute mean time\nSELECT to_timestamp((degrees(atan2(AVG(sin),AVG(cos))))* (24*60*60)/360)::TIME\nFROM\n\t(SELECT\n\tcos(radians(t*360/(24*60*60))),sin(radians(t*360/(24*60*60)))\n\tFROM\n\t\t(SELECT EXTRACT(epoch FROM times) t\n\t\tFROM time_table) T1\n\t)T2", "input": ""}, {"instruction": "Task[edit]\nWrite a program to find the mode value of a collection.\n\nThe case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.\n\nIf it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.\n\nSee also\nTasks for calculating statistical measures\n\n\n\nin one go\nmoving (sliding window)\nmoving (cumulative)\n\nMean\nArithmetic\n\nStatistics/Basic\nAverages/Arithmetic mean\nAverages/Pythagorean means\n\n\nAverages/Simple moving average\n\n\n\n\nGeometric\n\nAverages/Pythagorean means\n\n\n\n\nHarmonic\n\nAverages/Pythagorean means\n\n\n\n\nQuadratic\n\nAverages/Root mean square\n\n\n\n\nCircular\n\nAverages/Mean angle\nAverages/Mean time of day\n\n\n\n\nMedian\n\nAverages/Median\n\n\n\n\nMode\n\nAverages/Mode\n\n\n\n\nStandard deviation\n\nStatistics/Basic\n\n\n\nCumulative standard deviation\n\n\n\n", "output": "-- setup\nCREATE TABLE averages (val INTEGER);\nINSERT INTO averages VALUES (1);\nINSERT INTO averages VALUES (2);\nINSERT INTO averages VALUES (3);\nINSERT INTO averages VALUES (1);\nINSERT INTO averages VALUES (2);\nINSERT INTO averages VALUES (4);\nINSERT INTO averages VALUES (2);\nINSERT INTO averages VALUES (5);\nINSERT INTO averages VALUES (2);\nINSERT INTO averages VALUES (3);\nINSERT INTO averages VALUES (3);\nINSERT INTO averages VALUES (1);\nINSERT INTO averages VALUES (3);\nINSERT INTO averages VALUES (6);\n-- find the mode\nWITH\n counts AS\n (\n SELECT\n val,\n COUNT(*) AS num\n FROM\n averages\n GROUP BY\n val\n )\nSELECT\n val AS mode_val\nFROM\n counts\nWHERE\n num IN (SELECT MAX(num) FROM counts);", "input": ""}, {"instruction": "Task[edit]\nCompute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).\n\nShow that \n\n\n\nA\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n\u2265\nG\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n\u2265\nH\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n\n\n{\\displaystyle A(x_{1},\\ldots ,x_{n})\\geq G(x_{1},\\ldots ,x_{n})\\geq H(x_{1},\\ldots ,x_{n})}\n\n for this set of positive integers.\n\n The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:\n \n\n\n\nA\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n=\n\n\n\n\nx\n\n1\n\n\n+\n\u22ef\n+\n\nx\n\nn\n\n\n\nn\n\n\n\n\n{\\displaystyle A(x_{1},\\ldots ,x_{n})={\\frac {x_{1}+\\cdots +x_{n}}{n}}}\n\n\n The geometric mean is the \n\n\n\nn\n\n\n{\\displaystyle n}\n\nth root of the product of the list:\n \n\n\n\nG\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n=\n\n\n\n\nx\n\n1\n\n\n\u22ef\n\nx\n\nn\n\n\n\n\nn\n\n\n\n\n\n{\\displaystyle G(x_{1},\\ldots ,x_{n})={\\sqrt[{n}]{x_{1}\\cdots x_{n}}}}\n\n\n The harmonic mean is \n\n\n\nn\n\n\n{\\displaystyle n}\n\n divided by the sum of the reciprocal of each item in the list:\n \n\n\n\nH\n(\n\nx\n\n1\n\n\n,\n\u2026\n,\n\nx\n\nn\n\n\n)\n=\n\n\nn\n\n\n\n1\n\nx\n\n1\n\n\n\n\n+\n\u22ef\n+\n\n\n1\n\nx\n\nn\n\n\n\n\n\n\n\n\n\n{\\displaystyle H(x_{1},\\ldots ,x_{n})={\\frac {n}{{\\frac {1}{x_{1}}}+\\cdots +{\\frac {1}{x_{n}}}}}}\n\n\n\n\nSee also\nTasks for calculating statistical measures\n\n\n\nin one go\nmoving (sliding window)\nmoving (cumulative)\n\nMean\nArithmetic\n\nStatistics/Basic\nAverages/Arithmetic mean\nAverages/Pythagorean means\n\n\nAverages/Simple moving average\n\n\n\n\nGeometric\n\nAverages/Pythagorean means\n\n\n\n\nHarmonic\n\nAverages/Pythagorean means\n\n\n\n\nQuadratic\n\nAverages/Root mean square\n\n\n\n\nCircular\n\nAverages/Mean angle\nAverages/Mean time of day\n\n\n\n\nMedian\n\nAverages/Median\n\n\n\n\nMode\n\nAverages/Mode\n\n\n\n\nStandard deviation\n\nStatistics/Basic\n\n\n\nCumulative standard deviation\n\n\n\n\n\n", "output": "\u00a0\n--setup\nCREATE TABLE averages (val INTEGER);\nINSERT INTO averages VALUES (1);\nINSERT INTO averages VALUES (2);\nINSERT INTO averages VALUES (3);\nINSERT INTO averages VALUES (4);\nINSERT INTO averages VALUES (5);\nINSERT INTO averages VALUES (6);\nINSERT INTO averages VALUES (7);\nINSERT INTO averages VALUES (8);\nINSERT INTO averages VALUES (9);\nINSERT INTO averages VALUES (10);\n-- calculate means\nSELECT\n 1/avg(1/val) AS harm,\n avg(val) AS arith\nFROM\n averages;\n\u00a0", "input": ""}, {"instruction": "Task\n\nTake a combined set of elements and apply a function to each element.\n\n\n\n", "output": "-- Let's create a generic class with one method to be used as an interface:\nCREATE OR REPLACE\nTYPE callback AS OBJECT (\n -- A class needs at least one member even though we don't use it\n -- There's no generic OBJECT type, so let's call it NUMBER\n dummy NUMBER,\n -- Here's our function, and since PL/SQL doesn't have generics,\n -- let's use type NUMBER for our params\n MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER\n) NOT FINAL NOT instantiable;\n/\n\u00a0\n-- Now let's inherit from that, defining a class with one method. We'll have ours square a number.\n-- We can pass this class into any function that takes type callback:\nCREATE OR REPLACE TYPE CB_SQUARE under callback (\n OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER\n)\n/\nCREATE OR REPLACE\nTYPE BODY CB_SQUARE AS\n OVERRIDING MEMBER FUNCTION exec(n NUMBER) RETURN NUMBER IS\n BEGIN\n RETURN n * n;\n END exec;\nEND;\n/\n\u00a0\n-- And a package to hold our test\nCREATE OR REPLACE \nPACKAGE PKG_CALLBACK AS \n myCallback cb_square;\n TYPE intTable IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;\n ints intTable;\n i PLS_INTEGER;\n\u00a0\n PROCEDURE test_callback;\nEND PKG_CALLBACK;\n/\n\u00a0\nCREATE OR REPLACE PACKAGE BODY PKG_CALLBACK AS\n -- Our generic mapping function that takes a \"method\" and a collection\n -- Note that it takes the generic callback type \n -- that doesn't know anything about squaring\n PROCEDURE do_callback(myCallback IN callback, ints IN OUT intTable) IS\n i PLS_INTEGER;\n myInt NUMBER;\n BEGIN\n FOR i IN 1 .. ints.COUNT LOOP\n myInt := ints(i);\n -- PL/SQL call's the child's method\n ints(i) := myCallback.exec(myInt);\n END LOOP;\n END do_callback;\n\u00a0\n PROCEDURE test_callback IS\n BEGIN\n myCallback := cb_square(NULL);\n FOR i IN 1..5 LOOP\n ints(i) := i;\n END LOOP;\n\u00a0\n do_callback(myCallback, ints);\n\u00a0\n i := ints.FIRST;\n WHILE i IS NOT NULL LOOP\n DBMS_OUTPUT.put_line(ints(i));\n i := ints.next(i);\n END LOOP;\n END test_callback;\nEND PKG_CALLBACK;\n/\n\u00a0\nBEGIN\n PKG_CALLBACK.TEST_CALLBACK();\nEND;\n/", "input": ""}, {"instruction": "Task[edit]\nWrite a program to find the mean (arithmetic average) of a numeric vector.\n\nIn case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.\n\nSee also\nTasks for calculating statistical measures\n\n\n\nin one go\nmoving (sliding window)\nmoving (cumulative)\n\nMean\nArithmetic\n\nStatistics/Basic\nAverages/Arithmetic mean\nAverages/Pythagorean means\n\n\nAverages/Simple moving average\n\n\n\n\nGeometric\n\nAverages/Pythagorean means\n\n\n\n\nHarmonic\n\nAverages/Pythagorean means\n\n\n\n\nQuadratic\n\nAverages/Root mean square\n\n\n\n\nCircular\n\nAverages/Mean angle\nAverages/Mean time of day\n\n\n\n\nMedian\n\nAverages/Median\n\n\n\n\nMode\n\nAverages/Mode\n\n\n\n\nStandard deviation\n\nStatistics/Basic\n\n\n\nCumulative standard deviation\n\n\n\n\n\n", "output": "\u00a0\nCREATE TABLE \"numbers\" (\"datapoint\" INTEGER);\n\u00a0\nINSERT INTO \"numbers\" SELECT rownum FROM tab;\n\u00a0\nSELECT SUM(\"datapoint\")/COUNT(*) FROM \"numbers\";\n\u00a0", "input": ""}, {"instruction": "Task\n\nTake a combined set of elements and apply a function to each element.\n\n\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE TYPE NUMBERS AS SMALLINT ARRAY[5];\n DECLARE NUMBERS NUMBERS;\n DECLARE I SMALLINT;\n\u00a0\n SET I = 1;\n WHILE (I <= 5) DO\n SET NUMBERS[I] = I;\n SET I = I + 1;\n END WHILE;\n\u00a0\n BEGIN\n DECLARE PROCEDURE PRINT_SQUARE (\n IN VALUE SMALLINT\n )\n BEGIN\n CALL DBMS_OUTPUT.PUT(VALUE * VALUE || ' ');\n END;\n\u00a0\n SET I = 1;\n WHILE (I <= 5) DO\n CALL PRINT_SQUARE(NUMBERS[I]);\n SET I = I + 1;\n END WHILE;\n CALL DBMS_OUTPUT.PUT_LINE('');\n END;\nEND @\n\u00a0", "input": ""}, {"instruction": "Task\n\nThe goal is to create an associative array (also known as a dictionary, map, or hash).\n\n\n\nRelated tasks:\n\n Associative arrays/Iteration\n Hash from two arrays\n\n\nSee also\n\n Array\n Associative array: Creation, Iteration\n Collections\n Compound data type\n Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n Linked list\n Queue: Definition, Usage\n Set\n Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n Stack\n\n", "output": "DECLARE\n type ThisIsNotAnAssocArrayType is record (\n myShape VARCHAR2(20),\n mySize number,\n isActive BOOLEAN\n );\n assocArray ThisIsNotAnAssocArrayType\u00a0;\nBEGIN\n assocArray.myShape\u00a0:= 'circle';\n\u00a0\n dbms_output.put_line ('assocArray.myShape: ' || assocArray.myShape);\n dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize);\nEND;\n/", "input": ""}, {"instruction": "Task\n\nThe goal is to create an associative array (also known as a dictionary, map, or hash).\n\n\n\nRelated tasks:\n\n Associative arrays/Iteration\n Hash from two arrays\n\n\nSee also\n\n Array\n Associative array: Creation, Iteration\n Collections\n Compound data type\n Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n Linked list\n Queue: Definition, Usage\n Set\n Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n Stack\n\n", "output": "\u00a0\nREM CREATE a TABLE TO associate KEYS WITH VALUES\nCREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .\nREM INSERT a KEY VALUE Pair\nINSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');.\nREM Retrieve a KEY VALUE pair\nSELECT aa.value_column FROM associative_array aa WHERE aa.key_column = 'KEY';\n\u00a0", "input": ""}, {"instruction": "Task\n\nThe goal is to create an associative array (also known as a dictionary, map, or hash).\n\n\n\nRelated tasks:\n\n Associative arrays/Iteration\n Hash from two arrays\n\n\nSee also\n\n Array\n Associative array: Creation, Iteration\n Collections\n Compound data type\n Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n Linked list\n Queue: Definition, Usage\n Set\n Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n Stack\n\n", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nBEGIN\n DECLARE TYPE ASSOC_ARRAY AS VARCHAR(20) ARRAY [VARCHAR(20)];\n DECLARE HASH ASSOC_ARRAY;\n SET HASH['key1'] = 'val1';\n SET HASH['key-2'] = 2;\n SET HASH['three'] = -238.83;\n SET HASH[4] = 'val3';\n\u00a0\n CALL DBMS_OUTPUT.PUT_LINE(HASH['key1']);\n CALL DBMS_OUTPUT.PUT_LINE(HASH['key-2']);\n CALL DBMS_OUTPUT.PUT_LINE(HASH['three']);\n CALL DBMS_OUTPUT.PUT_LINE(HASH[4]);\n CALL DBMS_OUTPUT.PUT_LINE(HASH['5']);\nEND@\n\u00a0", "input": ""}, {"instruction": "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\u00a0\n\nm\n=\n0\n\n\n\n\nA\n(\nm\n\u2212\n1\n,\n1\n)\n\n\n\nif\u00a0\n\nm\n>\n0\n\n\u00a0and\u00a0\n\nn\n=\n0\n\n\n\n\nA\n(\nm\n\u2212\n1\n,\nA\n(\nm\n,\nn\n\u2212\n1\n)\n)\n\n\n\nif\u00a0\n\nm\n>\n0\n\n\u00a0and\u00a0\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", "output": "DECLARE\n\u00a0\n FUNCTION ackermann(pi_m IN NUMBER,\n pi_n IN NUMBER) RETURN NUMBER IS\n BEGIN\n IF pi_m = 0 THEN\n RETURN pi_n + 1;\n ELSIF pi_n = 0 THEN\n RETURN ackermann(pi_m - 1, 1);\n ELSE\n RETURN ackermann(pi_m - 1, ackermann(pi_m, pi_n - 1));\n END IF;\n END ackermann;\n\u00a0\nBEGIN\n FOR n IN 0 .. 6 LOOP\n FOR m IN 0 .. 3 LOOP\n DBMS_OUTPUT.put_line('A(' || m || ',' || n || ') = ' || ackermann(m, n));\n END LOOP;\n END LOOP;\nEND;\n\u00a0", "input": ""}, {"instruction": "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\u00a0\n\nm\n=\n0\n\n\n\n\nA\n(\nm\n\u2212\n1\n,\n1\n)\n\n\n\nif\u00a0\n\nm\n>\n0\n\n\u00a0and\u00a0\n\nn\n=\n0\n\n\n\n\nA\n(\nm\n\u2212\n1\n,\nA\n(\nm\n,\nn\n\u2212\n1\n)\n)\n\n\n\nif\u00a0\n\nm\n>\n0\n\n\u00a0and\u00a0\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", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON@\n\u00a0\nCREATE OR REPLACE FUNCTION ACKERMANN(\n IN M SMALLINT,\n IN N BIGINT\n ) RETURNS BIGINT\n BEGIN\n DECLARE RET BIGINT;\n DECLARE STMT STATEMENT;\n\u00a0\n IF (M = 0) THEN\n SET RET = N + 1;\n ELSEIF (N = 0) THEN\n PREPARE STMT FROM 'SET\u00a0? = ACKERMANN(? - 1, 1)';\n EXECUTE STMT INTO RET USING M;\n ELSE\n PREPARE STMT FROM 'SET\u00a0? = ACKERMANN(? - 1, ACKERMANN(?,\u00a0? - 1))';\n EXECUTE STMT INTO RET USING M, M, N;\n END IF;\n RETURN RET;\n END @\n\u00a0\nBEGIN\n DECLARE M SMALLINT DEFAULT 0;\n DECLARE N SMALLINT DEFAULT 0;\n DECLARE MAX_LEVELS CONDITION FOR SQLSTATE '54038';\n DECLARE CONTINUE HANDLER FOR MAX_LEVELS BEGIN END;\n\u00a0\n WHILE (N <= 6) DO\n WHILE (M <= 3) DO\n CALL DBMS_OUTPUT.PUT_LINE('ACKERMANN(' || M || ', ' || N || ') = ' || ACKERMANN(M, N));\n SET M = M + 1;\n END WHILE;\n SET M = 0;\n SET N = N + 1;\n END WHILE;\nEND @\n\u00a0", "input": ""}, {"instruction": "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 \u00a0 \u00a0 \u00a0 a, b, c, d, e, f, \u00a0 and\n\u00a0 g \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\nShow all output here.\n\n\n\n \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n \u00a0 Show only the \u00a0 number \u00a0 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", "output": "\u00a0\nCREATE TABLE allints (v NUMBER);\nCREATE TABLE results \n(\na NUMBER,\nb NUMBER,\nc NUMBER,\nd NUMBER,\ne NUMBER,\nf NUMBER,\ng NUMBER\n);\n\u00a0\nCREATE OR REPLACE PROCEDURE foursquares(lo NUMBER,hi NUMBER,uniq BOOLEAN,show BOOLEAN)\nAS\n a NUMBER;\n b NUMBER;\n c NUMBER;\n d NUMBER;\n e NUMBER;\n f NUMBER;\n g NUMBER;\n out_line VARCHAR2(2000);\n\u00a0\n CURSOR results_cur IS \n SELECT\n a,\n b,\n c,\n d,\n e,\n f,\n g\n FROM\n results\n ORDER BY \n a,b,c,d,e,f,g;\n\u00a0\n results_rec results_cur%ROWTYPE;\n\u00a0\n solutions NUMBER;\n uorn VARCHAR2(2000);\nBEGIN\n solutions := 0;\n DELETE FROM allints;\n DELETE FROM results;\n FOR i IN lo..hi LOOP\n INSERT INTO allints VALUES (i);\n END LOOP;\n COMMIT;\n\u00a0\n IF uniq = TRUE THEN\n INSERT INTO results\n SELECT\n a.v a,\n b.v b,\n c.v c,\n d.v d,\n e.v e,\n f.v f,\n g.v g\n FROM\n allints a, allints b, allints c,allints d,\n allints e, allints f, allints g\n WHERE\n a.v NOT IN (b.v,c.v,d.v,e.v,f.v,g.v) AND\n b.v NOT IN (c.v,d.v,e.v,f.v,g.v) AND\n c.v NOT IN (d.v,e.v,f.v,g.v) AND\n d.v NOT IN (e.v,f.v,g.v) AND\n e.v NOT IN (f.v,g.v) AND\n f.v NOT IN (g.v) AND\n a.v = c.v + d.v AND\n g.v = d.v + e.v AND\n b.v = e.v + f.v - c.v\n ORDER BY \n a,b,c,d,e,f,g;\n uorn := ' unique solutions in ';\n ELSE\n INSERT INTO results\n SELECT\n a.v a,\n b.v b,\n c.v c,\n d.v d,\n e.v e,\n f.v f,\n g.v g\n FROM\n allints a, allints b, allints c,allints d,\n allints e, allints f, allints g\n WHERE\n a.v = c.v + d.v AND\n g.v = d.v + e.v AND\n b.v = e.v + f.v - c.v\n ORDER BY \n a,b,c,d,e,f,g; \n uorn := ' non-unique solutions in ';\n END IF;\n COMMIT;\n\u00a0\n OPEN results_cur;\n LOOP\n FETCH results_cur INTO results_rec;\n EXIT WHEN results_cur%notfound;\n a := results_rec.a;\n b := results_rec.b;\n c := results_rec.c;\n d := results_rec.d;\n e := results_rec.e;\n f := results_rec.f;\n g := results_rec.g;\n\u00a0\n solutions := solutions + 1;\n IF show = TRUE THEN\n out_line := TO_CHAR(a) || ' ';\n out_line := out_line || ' ' || TO_CHAR(b) || ' ';\n out_line := out_line || ' ' || TO_CHAR(c) || ' ';\n out_line := out_line || ' ' || TO_CHAR(d) || ' ';\n out_line := out_line || ' ' || TO_CHAR(e) || ' ';\n out_line := out_line || ' ' || TO_CHAR(f) ||' ';\n out_line := out_line || ' ' || TO_CHAR(g);\n END IF;\n\u00a0\n DBMS_OUTPUT.put_line(out_line);\n END LOOP;\n CLOSE results_cur;\n out_line := TO_CHAR(solutions) || uorn;\n out_line := out_line || TO_CHAR(lo) || ' to ' || TO_CHAR(hi);\n DBMS_OUTPUT.put_line(out_line);\n\u00a0\nEND;\n/\n\u00a0", "input": ""}, {"instruction": "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 \u00a0 \u00a0 \u00a0 a, b, c, d, e, f, \u00a0 and\n\u00a0 g \u00a0 \u00a0 \u00a0 with the decimal\ndigits \u00a0 LOW \u00a0 \u2500\u2500\u2500\u25ba \u00a0 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 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557 \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n \u2551 \u2551 \u2551 \u2551\n \u2551 a \u2551 \u2551 e \u2551\n \u2551 \u2551 \u2551 \u2551\n \u2551 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 b \u2551 \u2551 d \u2502 \u2502 f \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u2551 \u2502 \u2551 \u2551 \u2502 \u2502 \u2551 \u2502\n \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u255a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u255d \u2502\n \u2502 c \u2502 \u2502 g \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\nShow all output here.\n\n\n\n \u00a0 Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n\n \u00a0 Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n\n \u00a0 Show only the \u00a0 number \u00a0 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", "output": "\u00a0\n--#SET TERMINATOR @\n\u00a0\nSET SERVEROUTPUT ON @\n\u00a0\nCREATE TABLE ALL_INTS (\n V INTEGER\n)@\n\u00a0\nCREATE TABLE RESULTS (\n A INTEGER,\n B INTEGER,\n C INTEGER,\n D INTEGER,\n E INTEGER,\n F INTEGER,\n G INTEGER\n)@\n\u00a0\nCREATE OR REPLACE PROCEDURE FOUR_SQUARES(\n IN LO INTEGER,\n IN HI INTEGER,\n IN UNIQ SMALLINT,\n --IN UNIQ BOOLEAN,\n IN SHOW SMALLINT)\n --IN SHOW BOOLEAN)\n BEGIN\n DECLARE A INTEGER;\n DECLARE B INTEGER;\n DECLARE C INTEGER;\n DECLARE D INTEGER;\n DECLARE E INTEGER;\n DECLARE F INTEGER;\n DECLARE G INTEGER;\n DECLARE OUT_LINE VARCHAR(2000);\n DECLARE I SMALLINT;\n\u00a0\n DECLARE SOLUTIONS INTEGER;\n DECLARE UORN VARCHAR(2000);\n\u00a0\n SET SOLUTIONS = 0;\n DELETE FROM ALL_INTS;\n DELETE FROM RESULTS;\n SET I = LO;\n WHILE (I <= HI) DO\n INSERT INTO ALL_INTS VALUES (I);\n SET I = I + 1;\n END WHILE;\n COMMIT;\n\u00a0\n -- Computes unique solutions.\n IF (UNIQ = 0) THEN\n --IF (UNIQ = TRUE) THEN\n INSERT INTO RESULTS\n SELECT\n A.V A, B.V B, C.V C, D.V D, E.V E, F.V F, G.V G\n FROM\n ALL_INTS A, ALL_INTS B, ALL_INTS C, ALL_INTS D, ALL_INTS E, ALL_INTS F,\n ALL_INTS G\n WHERE\n A.V NOT IN (B.V, C.V, D.V, E.V, F.V, G.V)\n AND B.V NOT IN (C.V, D.V, E.V, F.V, G.V)\n AND C.V NOT IN (D.V, E.V, F.V, G.V)\n AND D.V NOT IN (E.V, F.V, G.V)\n AND E.V NOT IN (F.V, G.V)\n AND F.V NOT IN (G.V)\n AND A.V = C.V + D.V\n AND G.V = D.V + E.V\n AND B.V = E.V + F.V - C.V\n ORDER BY \n A, B, C, D, E, F, G;\n SET UORN = ' unique solutions in ';\n ELSE\n -- Compute non-unique solutions.\n INSERT INTO RESULTS\n SELECT\n A.V A, B.V B, C.V C, D.V D, E.V E, F.V F, G.V G\n FROM\n ALL_INTS A, ALL_INTS B, ALL_INTS C, ALL_INTS D, ALL_INTS E, ALL_INTS F,\n ALL_INTS G\n WHERE\n A.V = C.V + D.V\n AND G.V = D.V + E.V\n AND B.V = E.V + F.V - C.V\n ORDER BY \n A, B, C, D, E, F, G;\n SET UORN = ' non-unique solutions in ';\n END IF;\n COMMIT;\n\u00a0\n -- Counts the possible solutions.\n FOR v AS c CURSOR FOR\n SELECT\n A, B, C, D, E, F, G\n FROM RESULTS\n ORDER BY \n A, B, C, D, E, F, G\n DO\n SET SOLUTIONS = SOLUTIONS + 1;\n -- Shows the results.\n IF (SHOW = 0) THEN\n --IF (SHOW = TRUE) THEN\n SET OUT_LINE = A || ' ' || B || ' ' || C || ' ' || D || ' ' || E || ' '\n || F ||' ' || G;\n CALL DBMS_OUTPUT.PUT_LINE(OUT_LINE);\n END IF;\n END FOR;\n\u00a0\n SET OUT_LINE = SOLUTIONS || UORN || LO || ' to ' || HI;\n CALL DBMS_OUTPUT.PUT_LINE(OUT_LINE);\n END\n@\n\u00a0\nCALL FOUR_SQUARES(1, 7, 0, 0)@\nCALL FOUR_SQUARES(3, 9, 0, 0)@\nCALL FOUR_SQUARES(0, 9, 1, 1)@\n\u00a0", "input": ""}, {"instruction": "\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", "output": "USE rosettacode;\nGO\n\u00a0\nSET NOCOUNT ON;\nGO\n\u00a0\nCREATE TABLE dbo.numbers (n INT PRIMARY KEY);\nGO\n\u00a0\n-- NOTE If you want to play more than 10000 games, you need to extend the query generating the numbers table by adding\n-- next cross joins. Now the table contains enough values to solve the task and it takes less processing time.\n\u00a0\nWITH sample100 AS (\n SELECT TOP(100) object_id\n FROM master.sys.objects\n)\nINSERT numbers\n SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS n\n FROM sample100 AS A\n CROSS JOIN sample100 AS B;\nGO\n\u00a0\nCREATE TABLE dbo.drawers (drawer INT PRIMARY KEY, card INT);\nGO\n\u00a0\nCREATE TABLE dbo.results (strategy VARCHAR(10), game INT, result BIT, PRIMARY KEY (game, strategy));\nGO\n\u00a0\nCREATE PROCEDURE dbo.shuffleDrawers @prisonersCount INT\nAS BEGIN\n SET NOCOUNT ON;\n\u00a0\n IF NOT EXISTS (SELECT * FROM drawers)\n INSERT drawers (drawer, card)\n SELECT n AS drawer, n AS card\n FROM numbers\n WHERE n <= @prisonersCount;\n\u00a0\n DECLARE @randoms TABLE (n INT, random INT);\n DECLARE @n INT = 1;\n WHILE @n <= @prisonersCount BEGIN\n INSERT @randoms VALUES (@n, ROUND(RAND() * (@prisonersCount - 1), 0) + 1);\n\u00a0\n SET @n = @n + 1;\n END;\n\u00a0\n WITH ordered AS (\n SELECT ROW_NUMBER() OVER (ORDER BY random ASC) AS drawer,\n n AS card\n FROM @randoms\n )\n UPDATE drawers\n SET card = o.card\n FROM drawers AS s\n INNER JOIN ordered AS o\n ON o.drawer = s.drawer;\nEND\nGO\n\u00a0\nCREATE PROCEDURE dbo.find @prisoner INT, @strategy VARCHAR(10)\nAS BEGIN\n -- A prisoner can open no more than 50 drawers.\n DECLARE @drawersCount INT = (SELECT COUNT(*) FROM drawers);\n DECLARE @openMax INT = @drawersCount / 2;\n\u00a0\n -- Prisoners start outside the room.\n DECLARE @card INT = NULL;\n DECLARE @open INT = 1;\n WHILE @open <= @openMax BEGIN\n -- A prisoner tries to find his own number.\n IF @strategy = 'random' BEGIN\n DECLARE @random INT = ROUND(RAND() * (@drawersCount - 1), 0) + 1;\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @random);\n END\n IF @strategy = 'optimal' BEGIN\n IF @card IS NULL BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @prisoner);\n END ELSE BEGIN\n SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @card);\n END\n END\n\u00a0\n -- A prisoner finding his own number is then held apart from the others.\n IF @card = @prisoner\n RETURN 1;\n\u00a0\n SET @open = @open + 1;\n END\n\u00a0\n RETURN 0;\nEND\nGO\n\u00a0\nCREATE PROCEDURE dbo.playGame @gamesCount INT, @strategy VARCHAR(10), @prisonersCount INT = 100\nAS BEGIN\n SET NOCOUNT ON;\n\u00a0\n IF @gamesCount <> (SELECT COUNT(*) FROM results WHERE strategy = @strategy) BEGIN\n DELETE results\n WHERE strategy = @strategy;\n\u00a0\n INSERT results (strategy, game, result)\n SELECT @strategy AS strategy, n AS game, 0 AS result\n FROM numbers\n WHERE n <= @gamesCount;\n END\n\u00a0\n UPDATE results\n SET result = 0\n WHERE strategy = @strategy;\n\u00a0\n DECLARE @game INT = 1;\n WHILE @game <= @gamesCount BEGIN\n -- A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n -- Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n EXECUTE shuffleDrawers @prisonersCount;\n\u00a0\n -- A prisoner tries to find his own number.\n -- Prisoners start outside the room.\n -- They can decide some strategy before any enter the room.\n DECLARE @prisoner INT = 1;\n DECLARE @found INT = 0;\n WHILE @prisoner <= @prisonersCount BEGIN\n EXECUTE @found = find @prisoner, @strategy;\n IF @found = 1\n SET @prisoner = @prisoner + 1;\n ELSE\n BREAK;\n END;\n\u00a0\n -- If all 100 findings find their own numbers then they will all be pardoned. If any don't then all sentences stand.\n IF @found = 1\n UPDATE results SET result = 1 WHERE strategy = @strategy AND game = @game;\n\u00a0\n SET @game = @game + 1;\n END\nEND\nGO\n\u00a0\nCREATE FUNCTION dbo.computeProbability(@strategy VARCHAR(10))\nRETURNS decimal (18, 2)\nAS BEGIN\n RETURN (\n SELECT (SUM(CAST(result AS INT)) * 10000 / COUNT(*)) / 100\n FROM results\n WHERE strategy = @strategy\n );\nEND\nGO\n\u00a0\n-- Simulate several thousand instances of the game:\nDECLARE @gamesCount INT = 2000;\n\u00a0\n-- ...where the prisoners randomly open drawers.\nEXECUTE playGame @gamesCount, 'random';\n\u00a0\n-- ...where the prisoners use the optimal strategy mentioned in the Wikipedia article.\nEXECUTE playGame @gamesCount, 'optimal';\n\u00a0\n-- Show and compare the computed probabilities of success for the two strategies.\nDECLARE @log VARCHAR(max);\nSET @log = CONCAT('Games count: ', @gamesCount);\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"random\" strategy: ', dbo.computeProbability('random'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nSET @log = CONCAT('Probability of success with \"optimal\" strategy: ', dbo.computeProbability('optimal'));\nRAISERROR (@log, 0, 1) WITH NOWAIT;\nGO\n\u00a0\nDROP FUNCTION dbo.computeProbability;\nDROP PROCEDURE dbo.playGame;\nDROP PROCEDURE dbo.find;\nDROP PROCEDURE dbo.shuffleDrawers;\nDROP TABLE dbo.results;\nDROP TABLE dbo.drawers;\nDROP TABLE dbo.numbers;\nGO", "input": ""}, {"instruction": "A+B \u00a0 \u2500\u2500\u2500 a classic problem in programming contests, \u00a0 it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, \u00a0 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\u2212\n1000\n\u2264\nA\n,\nB\n\u2264\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: \u00a0 the sum of A and B.\n\n\n\nExample\n\n\n\n input \u00a0\n\n output \u00a0\n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n", "output": "SELECT A+B", "input": ""}, {"instruction": "A+B \u00a0 \u2500\u2500\u2500 a classic problem in programming contests, \u00a0 it's given so contestants can gain familiarity with the online judging system being used.\n\n\n\nTask\n\nGiven two integers, \u00a0 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\u2212\n1000\n\u2264\nA\n,\nB\n\u2264\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: \u00a0 the sum of A and B.\n\n\n\nExample\n\n\n\n input \u00a0\n\n output \u00a0\n\n\n 2 2 \n\n 4 \n\n\n 3 2 \n\n 5 \n\n\n", "output": "\u00a0\n\u00a0\nCREATE OR REPLACE FUNCTION splitadd (instring VARCHAR(255))\n\tRETURNS INTEGER\n\tNO EXTERNAL ACTION\nF1: BEGIN ATOMIC\n\u00a0\n\tDECLARE FIRST INTEGER;\n\tDECLARE SECOND INTEGER;\n\u00a0\n\tSET FIRST = REGEXP_SUBSTR(instring, '[0-9]+',1,1);\n\tSET SECOND = REGEXP_SUBSTR(instring, '[0-9]+',1,2);\n\u00a0\n\tRETURN FIRST + SECOND;\nEND\n\u00a0", "input": ""}]