task_id
int64
prompt
string
canonical_solution
string
test
string
0
# Instructions Implement the `accumulate` operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection. Given the collection of numbers: - 1, 2, 3, 4, 5 And the operation: - square a number (`x => x * x`) Your code should be able to produce the collection of squares: - 1, 4, 9, 16, 25 Check out the test suite to see the expected function signature. ## Restrictions Keep your hands off that collect/map/fmap/whatchamacallit functionality provided by your standard library! Solve this one yourself using other basic tools instead.
Accumulate : procedure parse arg input, function output = '' ; do while input \= '' parse var input token input cmd = 'retval =' function || '(' || ''''token'''' || ')' ; interpret cmd output ||= retval '' end return STRIP(output, 'T')
/* Unit Test Runner: t-rexx */ context('Checking the Accumulate function') /* Unit tests */ check('accumulate empty test' 'Accumulate("", "Dummy")',, 'Accumulate("", "Dummy")',, '=', '') check('accumulate squares test' 'Accumulate("1 2 3", "Square")',, 'Accumulate("1 2 3", "Square")',, '=', '1 4 9') check('accumulate upcases test' 'Accumulate("hello world", "ToUpperCase")',, 'Accumulate("hello world", "ToUpperCase")',, '=', 'HELLO WORLD') check('accumulate reversed strings test' 'Accumulate("the quick brown fox etc", "ReverseToken")',, 'Accumulate("the quick brown fox etc", "ReverseToken")',, '=', 'eht kciuq nworb xof cte') check('accumulate recursively test' 'Accumulate("1 2 3 4 5", "GenSeq")',, 'Accumulate("1 2 3 4 5", "GenSeq")',, '=', '1 1 2 1 2 3 1 2 3 4 1 2 3 4 5')
1
# Instructions Convert a phrase to its acronym. Techies love their TLA (Three Letter Acronyms)! Help generate some jargon by writing a program that converts a long name like Portable Network Graphics to its acronym (PNG). Punctuation is handled as follows: hyphens are word separators (like whitespace); all other punctuation can be removed from the input. For example: |Input|Output| |-|-| |As Soon As Possible|ASAP| |Liquid-crystal display|LCD| |Thank George It's Friday!|TGIF|
Abbreviate: procedure if ARG() \= 1 | ARG(1) == '' then ; return '' /* Convert hyphen to space, so as to act as word separator */ phrase = CHANGESTR('-', ARG(1), ' ') /* Remove punctuation, but retain (and normalize) spaces */ phrase = SPACE(CHANGESTR(';',, TRANSLATE(phrase,, '~`!@#$%^&*()_+=<,>.?/:;"''',, ';'),, '')) abbreviation = '' ; do while phrase \= '' parse upper var phrase word phrase ; abbreviation ||= LEFT(word, 1) end return abbreviation
/* Unit Test Runner: t-rexx */ context('Checking the Abbreviate function') /* Unit tests */ check('basic' 'Abbreviate("Portable Network Graphics")',, 'Abbreviate("Portable Network Graphics")',, '=', 'PNG') check('lowercase words' 'Abbreviate("Ruby on Rails")',, 'Abbreviate("Ruby on Rails")',, '=', 'ROR') check('punctuation' 'Abbreviate("First In, First Out")',, 'Abbreviate("First In, First Out")',, '=', 'FIFO') check('all caps word' 'Abbreviate("GNU Image Manipulation Program")',, 'Abbreviate("GNU Image Manipulation Program")',, '=', 'GIMP') check('punctuation without whitespace' 'Abbreviate("Complementary metal-oxide semiconductor")',, 'Abbreviate("Complementary metal-oxide semiconductor")',, '=', 'CMOS') check('very long abbreviation' 'Abbreviate("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me")',, 'Abbreviate("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me")',, '=', 'ROTFLSHTMDCOALM') check('consecutive delimiters' 'Abbreviate("Something - I made up from thin air")',, 'Abbreviate("Something - I made up from thin air")',, '=', 'SIMUFTA') check('apostrophes' 'Abbreviate("Halley''s Comet")',, 'Abbreviate("Halley''s Comet")',, '=', 'HC') check('underscore emphasis' 'Abbreviate("The Road __Not__ Taken")',, 'Abbreviate("The Road __Not__ Taken")',, '=', 'TRNT')
2
# Instructions Convert a sequence of digits in one base, representing a number, into a sequence of digits in another base, representing the same number. ~~~~exercism/note Try to implement the conversion yourself. Do not use something else to perform the conversion for you. ~~~~ ## About [Positional Notation][positional-notation] In positional notation, a number in base **b** can be understood as a linear combination of powers of **b**. The number 42, _in base 10_, means: `(4 × 10¹) + (2 × 10⁰)` The number 101010, _in base 2_, means: `(1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (0 × 2²) + (1 × 2¹) + (0 × 2⁰)` The number 1120, _in base 3_, means: `(1 × 3³) + (1 × 3²) + (2 × 3¹) + (0 × 3⁰)` _Yes. Those three numbers above are exactly the same. Congratulations!_ [positional-notation]: https://en.wikipedia.org/wiki/Positional_notation
Rebase : procedure parse value ARG(1) || ';' || ARG(2) || ';' || ARG(3) , with inBase ';' digits ';' outBase if inBase < 2 | outBase < 2 | LENGTH(digits) < 1 then ; return '' if Sum(digits) < 1 then ; return '' if \HasValidBaseDigits(digits, inBase) then ; return '' return Base10ToDigits(DigitsToBase10(digits, inbase), outBase) HasValidBaseDigits : procedure parse value SPACE(ARG(1)) || ';' || ARG(2) , with digits ';' base do while digits \= '' parse var digits digit digits if digit < 0 | digit >= base then ; return 0 end return 1 Base10ToDigits : procedure parse arg base10Value, base digits = '' ; do while base10Value > 0 parse value (base10Value % base) (base10Value // base) , with base10Value digit digits = digit digits end return STRIP(digits) DigitsToBase10 : procedure parse value SPACE(ReverseWords(ARG(1))) || ';' || ARG(2) 0, with digits ';' base asBase10 ndigits = WORDS(digits) do i = 1 to ndigits asBase10 += Power(base, (i-1)) * WORD(digits, i) end return asBase10 ReverseWords : procedure words = ARG(1) ; n = WORDS(words) ; revwords = '' do i = n to 1 by -1 revwords = revwords WORD(words, i) end return STRIP(revwords) Sum : procedure parse value SPACE(ARG(1)) || ';' || 0 with input ';' sum do while input \= '' ; parse var input elem input ; sum += elem ; end return sum Power : procedure parse arg x, y if y == 0 then ; return 1 t = Power(x, y % 2) if y // 2 == 0 then ; return t * t return x * t * t
/* Unit Test Runner: t-rexx */ context('Checking the Rebase function') /* Unit tests */ check('single bit to one decimal' 'Rebase(2, "1", 10)',, 'Rebase(2, "1", 10)',, '=', '1') check('binary to single decimal' 'Rebase(2, "1 0 1", 10)',, 'Rebase(2, "1 0 1", 10)',, '=', '5') check('single decimal to binary' 'Rebase(10, "5", 2)',, 'Rebase(10, "5", 2)',, '=', '1 0 1') check('binary to multiple decimal' 'Rebase(2, "1 0 1 0 1 0", 10)',, 'Rebase(2, "1 0 1 0 1 0", 10)',, '=', '4 2') check('decimal to binary' 'Rebase(10, "4 2", 2)',, 'Rebase(10, "4 2", 2)',, '=', '1 0 1 0 1 0') check('trinary to hexadecimal' 'Rebase(3, "1 1 2 0", 16)',, 'Rebase(3, "1 1 2 0", 16)',, '=', '2 10') check('hexadecimal to trinary' 'Rebase(16, "2 10", 3)',, 'Rebase(16, "2 10", 3)',, '=', '1 1 2 0') check('15 bit integer' 'Rebase(97, "3 46 60", 73)',, 'Rebase(97, "3 46 60", 73)',, '=', '6 10 45') check('empty list' 'Rebase(2, "", 10)',, 'Rebase(2, "", 10)',, '=', '') check('single zero' 'Rebase(10, "0", 2)',, 'Rebase(10, "0", 2)',, '=', '') check('multiple zeroes' 'Rebase(10, "0 0 0", 2)',, 'Rebase(10, "0 0 0", 2)',, '=', '') check('leading zeros' 'Rebase(7, "0 6 0", 10)',, 'Rebase(7, "0 6 0", 10)',, '=', '4 2') check('input base is one' 'Rebase(1, "0", 10)',, 'Rebase(1, "0", 10)',, '=', '') check('input base is zero' 'Rebase(0, "", 10)',, 'Rebase(0, "", 10)',, '=', '') check('input base is negative' 'Rebase(-2, "1", 10)',, 'Rebase(-2, "1", 10)',, '=', '') check('negative digit' 'Rebase(2, "1 -1 1 0 1 0", 10)',, 'Rebase(2, "1 -1 1 0 1 0", 10)',, '=', '') check('invalid positive digit' 'Rebase(2, "1 2 1 0 1 0", 10)',, 'Rebase(2, "1 2 1 0 1 0", 10)',, '=', '') check('output base is one' 'Rebase(2, "1 0 1 0 1 0", 1)',, 'Rebase(2, "1 0 1 0 1 0", 1)',, '=', '') check('output base is zero' 'Rebase(10, "7", 0)',, 'Rebase(10, "7", 0)',, '=', '') check('output base is negative' 'Rebase(2, "1", -7)',, 'Rebase(2, "1", -7)',, '=', '') check('both bases are negative' 'Rebase(-2, "1", -7)',, 'Rebase(-2, "1", -7)',, '=', '')
3
# Instructions An anagram is a rearrangement of letters to form a new word: for example `"owns"` is an anagram of `"snow"`. A word is not its own anagram: for example, `"stop"` is not an anagram of `"stop"`. Given a target word and a set of candidate words, this exercise requests the anagram set: the subset of the candidates that are anagrams of the target. The target and candidates are words of one or more ASCII alphabetic characters (`A`-`Z` and `a`-`z`). Lowercase and uppercase characters are equivalent: for example, `"PoTS"` is an anagram of `"sTOp"`, but `StoP` is not an anagram of `sTOp`. The anagram set is the subset of the candidate set that are anagrams of the target (in any order). Words in the anagram set should have the same letter case as in the candidate set. Given the target `"stone"` and candidates `"stone"`, `"tones"`, `"banana"`, `"tons"`, `"notes"`, `"Seton"`, the anagram set is `"tones"`, `"notes"`, `"Seton"`.
FindAnagrams : procedure parse arg target, candidates if target == '' | candidates == '' then ; return '' if WORDS(target) > WORDS(candidates) then ; return '' parse upper arg upperTarget, upperCandidates parse value SortString(upperTarget) ';' SortWordsInList(upperCandidates) ';' , DedupWord(upperCandidates) ';' , WORDS(candidates) 1 '' , with anagramTarget ';' anagramCandidates ';' dedupCandidates ';' , candidateWords startPos anagrams if WORDS(dedupCandidates) == 1 & , WORD(dedupCandidates, 1) == upperTarget then ; return '' do while startPos <= candidateWords anagramPos = WORDPOS(anagramTarget, anagramCandidates, startPos) if anagramPos > 0 then do candidate = WORD(candidates, anagramPos) if candidate \= target then ; anagrams ||= candidate '' startPos = anagramPos + 1 end ; else ; leave end return STRIP(anagrams) SortWordsInList : procedure parse arg words output = '' ; do while words \= '' parse var words word words output ||= SortString(word) '' end return STRIP(output) SortString : procedure letters = ARG(1) ; parse value LENGTH(letters) SUBSTR(letters, 1, 1) with n sorted if n < 2 then ; return sorted do i = 2 to n next = SUBSTR(letters, i, 1) do j = 1 to i-1 if next < SUBSTR(sorted, j, 1) then do if j > 1 then ; lm = SUBSTR(sorted, 1, j-1) ; else lm = '' sorted = lm || next || SUBSTR(sorted, j) leave j end if j == i-1 then ; sorted = sorted || next end end return STRIP(sorted) DedupWord : procedure parse arg input output = '' ; do while input \= '' parse var input token input if WORDPOS(token, output) < 1 then ; output ||= token '' end return STRIP(output, 'T')
/* Unit Test Runner: t-rexx */ context('Checking the FindAnagrams function') /* Unit tests */ check('no matches' 'FindAnagrams("diaper", "hello world zombies pants")',, 'FindAnagrams("diaper", "hello world zombies pants")',, '=', '') check('detects two anagrams' 'FindAnagrams("solemn", "lemons cherry melons")',, 'FindAnagrams("solemn", "lemons cherry melons")',, '=', 'lemons melons') check('does not detect anagram subsets' 'FindAnagrams("good", "dog goody")',, 'FindAnagrams("good", "dog goody")',, '=', '') check('detects anagram' 'FindAnagrams("listen", "enlists google inlets banana")',, 'FindAnagrams("listen", "enlists google inlets banana")',, '=', 'inlets') check('detects three anagrams' 'FindAnagrams("allergy", "gallery ballerina regally clergy largely leading")',, 'FindAnagrams("allergy", "gallery ballerina regally clergy largely leading")',, '=', 'gallery regally largely') check('detects multiple anagrams with different case' 'FindAnagrams("nose", "Eons ONES")',, 'FindAnagrams("nose", "Eons ONES")',, '=', 'Eons ONES') check('does not detect non-anagrams with identical checksum' 'FindAnagrams("mass", "last")',, 'FindAnagrams("mass", "last")',, '=', '') check('detects anagrams case-insensitively' 'FindAnagrams("Orchestra", "cashregister Carthorse radishes")',, 'FindAnagrams("Orchestra", "cashregister Carthorse radishes")',, '=', 'Carthorse') check('detects anagrams using case-insensitive subject' 'FindAnagrams("Orchestra", "cashregister carthorse radishes")',, 'FindAnagrams("Orchestra", "cashregister carthorse radishes")',, '=', 'carthorse') check('detects anagrams using case-insensitive possible matches' 'FindAnagrams("orchestra", "cashregister Carthorse radishes")',, 'FindAnagrams("orchestra", "cashregister Carthorse radishes")',, '=', 'Carthorse') check('does not detect a anagram if the original word is repeated' 'FindAnagrams("go", "go Go GO")',, 'FindAnagrams("go", "go Go GO")',, '=', '') check('anagrams must use all letters exactly once' 'FindAnagrams("tapper", "patter")',, 'FindAnagrams("tapper", "patter")',, '=', '') check('words are not anagrams of themselves' 'FindAnagrams("BANANA", "BANANA")',, 'FindAnagrams("BANANA", "BANANA")',, '=', '') check('words are not anagrams of themselves even if letter case is partially different' 'FindAnagrams("BANANA", "Banana")',, 'FindAnagrams("BANANA", "Banana")',, '=', '') check('words are not anagrams of themselves even if letter case is completely different' 'FindAnagrams("BANANA", "banana")',, 'FindAnagrams("BANANA", "banana")',, '=', '') check('words other than themselves can be anagrams' 'FindAnagrams("LISTEN", "LISTEN Silent")',, 'FindAnagrams("LISTEN", "LISTEN Silent")',, '=', 'Silent')
4
# Instructions An [Armstrong number][armstrong-number] is a number that is the sum of its own digits each raised to the power of the number of digits. For example: - 9 is an Armstrong number, because `9 = 9^1 = 9` - 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 1` - 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153` - 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190` Write some code to determine whether a number is an Armstrong number. [armstrong-number]: https://en.wikipedia.org/wiki/Narcissistic_number
IsArmstrongNumber : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) < 0 then ; return -1 parse value ARG(1) LENGTH(ARG(1)) 0 0 0 , with candidate length sum divisor digit if candidate == 0 then ; return 1 divisor = Power(10, length) ; do while divisor > 1 digit = candidate // divisor % (divisor % 10) sum = sum + Power(digit, length) divisor = divisor % 10 end return sum == candidate Power : procedure parse arg x, y if y == 0 then ; return 1 t = Power(x, y % 2) if y // 2 == 0 then ; return t * t return x * t * t
/* Unit Test Runner: t-rexx */ context('Checking the IsArmstrongNumber function') /* Unit tests */ check('Zero is an Armstrong number' 'IsArmstrongNumber(0)',, 'IsArmstrongNumber(0)',, '=', 1) check('Single-digit numbers are Armstrong numbers' 'IsArmstrongNumber(5)',, 'IsArmstrongNumber(5)',, '=', 1) check('There are no two-digit Armstrong numbers' 'IsArmstrongNumber(10)',, 'IsArmstrongNumber(10)',, '=', 0) check('Three-digit number that is an Armstrong number' 'IsArmstrongNumber(153)',, 'IsArmstrongNumber(153)',, '=', 1) check('Three-digit number that is not an Armstrong number' 'IsArmstrongNumber(100)',, 'IsArmstrongNumber(100)',, '=', 0) check('Four-digit number that is an Armstrong number' 'IsArmstrongNumber(9474)',, 'IsArmstrongNumber(9474)',, '=', 1) check('Four-digit number that is not an Armstrong number' 'IsArmstrongNumber(9475)',, 'IsArmstrongNumber(9475)',, '=', 0) check('Seven-digit number that is an Armstrong number' 'IsArmstrongNumber(9926315)',, 'IsArmstrongNumber(9926315)',, '=', 1) check('Seven-digit number that is not an Armstrong number' 'IsArmstrongNumber(9926314)',, 'IsArmstrongNumber(9926314)',, '=', 0)
5
# Instructions Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East. The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards. The first letter is replaced with the last letter, the second with the second-last, and so on. An Atbash cipher for the Latin alphabet would be as follows: ```text Plain: abcdefghijklmnopqrstuvwxyz Cipher: zyxwvutsrqponmlkjihgfedcba ``` It is a very weak cipher because it only has one possible key, and it is a simple mono-alphabetic substitution cipher. However, this may not have been an issue in the cipher's time. Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, leaving numbers unchanged, and punctuation is excluded. This is to make it harder to guess things based on word boundaries. All text will be encoded as lowercase letters. ## Examples - Encoding `test` gives `gvhg` - Encoding `x123 yes` gives `c123b vh` - Decoding `gvhg` gives `test` - Decoding `gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt` gives `thequickbrownfoxjumpsoverthelazydog`
Encode : procedure if ARG() < 1 | ARG(1) == '' then ; return '' parse value Convert(ARG(1)) with input output do while input \= '' parse var input chunk +5 input output ||= chunk '' end return STRIP(output, 'T') Decode : procedure if ARG() < 1 | ARG(1) == '' then ; return '' return Convert(ARG(1)) Convert : procedure sanitized = LOWER(CHANGESTR(';',, TRANSLATE(ARG(1),, ' ~`!@#$%^&*()_-+=<,>.?/:;"',, ';'),, '')) converted = TRANSLATE(sanitized, 'zyxwvutsrqponmlkjihgfedcba',, 'abcdefghijklmnopqrstuvwxyz') return converted
/* Unit Test Runner: t-rexx */ context('Checking the Encode and Decode functions') /* Unit tests */ check('encode -> encode yes' 'Encode("yes")',, 'Encode("yes")',, '=', 'bvh') check('encode -> encode no' 'Encode("no")',, 'Encode("no")',, '=', 'ml') check('encode -> encode OMG' 'Encode("OMG")',, 'Encode("OMG")',, '=', 'lnt') check('encode -> encode spaces' 'Encode("O M G")',, 'Encode("O M G")',, '=', 'lnt') check('encode -> encode mindblowingly' 'Encode("mindblowingly")',, 'Encode("mindblowingly")',, '=', 'nrmwy oldrm tob') check('encode -> encode numbers' 'Encode("Testing,1 2 3, testing.")',, 'Encode("Testing,1 2 3, testing.")',, '=', 'gvhgr mt123 gvhgr mt') check('encode -> encode deep thought' 'Encode("Truth is fiction.")',, 'Encode("Truth is fiction.")',, '=', 'gifgs rhurx grlm') check('encode -> encode all the letters' 'Encode("The quick brown fox jumps over the lazy dog.")',, 'Encode("The quick brown fox jumps over the lazy dog.")',, '=', 'gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt') check('decode -> decode exercism' 'Decode("vcvix rhn")',, 'Decode("vcvix rhn")',, '=', 'exercism') check('decode -> decode a sentence' 'Decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")',, 'Decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")',, '=', 'anobstacleisoftenasteppingstone') check('decode -> decode numbers' 'Decode("gvhgr mt123 gvhgr mt")',, 'Decode("gvhgr mt123 gvhgr mt")',, '=', 'testing123testing') check('decode -> decode all the letters' 'Decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")',, 'Decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")',, '=', 'thequickbrownfoxjumpsoverthelazydog') check('decode -> decode with too many spaces' 'Decode("vc vix r hn")',, 'Decode("vc vix r hn")',, '=', 'exercism') check('decode -> decode with no spaces' 'Decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv")',, 'Decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv")',, '=', 'anobstacleisoftenasteppingstone')
6
# Instructions Your task is to implement bank accounts supporting opening/closing, withdrawals, and deposits of money. As bank accounts can be accessed in many different ways (internet, mobile phones, automatic charges), your bank software must allow accounts to be safely accessed from multiple threads/processes (terminology depends on your programming language) in parallel. For example, there may be many deposits and withdrawals occurring in parallel; you need to ensure there is no [race conditions][wikipedia] between when you read the account balance and set the new balance. It should be possible to close an account; operations against a closed account must fail. [wikipedia]: https://en.wikipedia.org/wiki/Race_condition#In_software
Create : procedure return -1 Open : procedure parse arg balance if balance > -1 then ; return balance return 0 Close : procedure parse arg balance if balance < 0 then ; return balance return -1 Deposit : procedure parse arg amount, balance if balance < 0 | amount < 0 then ; return balance return balance + amount Withdraw : procedure parse arg amount, balance if balance < 0 | amount < 0 | (balance - amount < 0) ; then return balance return balance - amount Balance : procedure parse arg balance return balance
/* Unit Test Runner: t-rexx */ context('Checking the Create, Open, Close, Deposit, Withdraw, and Balance functions') /* Test Variables */ account_0 = Create() account_1 = Close(account_0) account_2 = Open(account_1) account_3 = Open(account_2) account_4 = Close(account_3) account_5 = Deposit(100, account_4) account_6 = Withdraw(50, account_5) account_7 = Withdraw(350, account_6) account_8 = Withdraw(-50, account_7) account_9 = Deposit(-50, account_8) account_10 = Open(account_9) account_11 = Deposit(100, account_10) account_12 = Deposit(150, account_11) account_13 = Withdraw(50, account_12) account_14 = Withdraw(350, account_13) account_15 = Withdraw(-50, account_14) account_16 = Deposit(-50, account_15) /* Unit tests */ check('Create a (dormant) new bank account' 'Balance(account_0)',, 'Balance(account_0)',, '=', -1) check('Close a dormant bank account - no account status change' 'Balance(account_1)',, 'Balance(account_1)',, '=', -1) check('Open a dormant bank account - dormant account now open' 'Balance(account_2)',, 'Balance(account_2)',, '=', 0) check('Open an already open bank account - no account status change' 'Balance(account_3)',, 'Balance(account_3)',, '=', 0) check('Close an already open bank account - account becomes dormant' 'Balance(account_4)',, 'Balance(account_4)',, '=', -1) check('Deposit money into a dormant bank account - deposit not accepted' 'Balance(account_5)',, 'Balance(account_5)',, '=', -1) check('Withdraw money from a dormant bank account - withdrawal unsuccessful' 'Balance(account_6)',, 'Balance(account_6)',, '=', -1) check('Attempt overdraw from a dormant bank account - withdrawal unsuccessful' 'Balance(account_7)',, 'Balance(account_7)',, '=', -1) check('Withdraw negative amount from a dormant bank account - withdrawal unsuccessful' 'Balance(account_8)',, 'Balance(account_8)',, '=', -1) check('Deposit negative amount into a dormant bank account - deposit unsuccessful' 'Balance(account_9)',, 'Balance(account_9)',, '=', -1) check('Open a dormant bank account - dormant account now open' 'Balance(account_10)',, 'Balance(account_10)',, '=', 0) check('Deposit money into an open bank account - deposit accepted' 'Balance(account_11)',, 'Balance(account_11)',, '=', 100) check('Deposit more money into an open bank account - deposit accepted' 'Balance(account_12)',, 'Balance(account_12)',, '=', 250) check('Withdraw money from an open bank account - withdrawal successful' 'Balance(account_13)',, 'Balance(account_13)',, '=', 200) check('Attempt overdraw from an open bank account - withdrawal unsuccessful, no account status change' 'Balance(account_14)',, 'Balance(account_14)',, '=', 200) check('Withdraw negative amount from an open bank account - withdrawal unsuccessful, no account status change' 'Balance(account_15)',, 'Balance(account_15)',, '=', 200) check('Deposit negative amount into an open bank account - deposit unsuccessful, no account status change' 'Balance(account_16)',, 'Balance(account_16)',, '=', 200)
7
# Instructions Recite the lyrics to that beloved classic, that field-trip favorite: 99 Bottles of Beer on the Wall. Note that not all verses are identical. ```text 99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down and pass it around, 96 bottles of beer on the wall. 96 bottles of beer on the wall, 96 bottles of beer. Take one down and pass it around, 95 bottles of beer on the wall. 95 bottles of beer on the wall, 95 bottles of beer. Take one down and pass it around, 94 bottles of beer on the wall. 94 bottles of beer on the wall, 94 bottles of beer. Take one down and pass it around, 93 bottles of beer on the wall. 93 bottles of beer on the wall, 93 bottles of beer. Take one down and pass it around, 92 bottles of beer on the wall. 92 bottles of beer on the wall, 92 bottles of beer. Take one down and pass it around, 91 bottles of beer on the wall. 91 bottles of beer on the wall, 91 bottles of beer. Take one down and pass it around, 90 bottles of beer on the wall. 90 bottles of beer on the wall, 90 bottles of beer. Take one down and pass it around, 89 bottles of beer on the wall. 89 bottles of beer on the wall, 89 bottles of beer. Take one down and pass it around, 88 bottles of beer on the wall. 88 bottles of beer on the wall, 88 bottles of beer. Take one down and pass it around, 87 bottles of beer on the wall. 87 bottles of beer on the wall, 87 bottles of beer. Take one down and pass it around, 86 bottles of beer on the wall. 86 bottles of beer on the wall, 86 bottles of beer. Take one down and pass it around, 85 bottles of beer on the wall. 85 bottles of beer on the wall, 85 bottles of beer. Take one down and pass it around, 84 bottles of beer on the wall. 84 bottles of beer on the wall, 84 bottles of beer. Take one down and pass it around, 83 bottles of beer on the wall. 83 bottles of beer on the wall, 83 bottles of beer. Take one down and pass it around, 82 bottles of beer on the wall. 82 bottles of beer on the wall, 82 bottles of beer. Take one down and pass it around, 81 bottles of beer on the wall. 81 bottles of beer on the wall, 81 bottles of beer. Take one down and pass it around, 80 bottles of beer on the wall. 80 bottles of beer on the wall, 80 bottles of beer. Take one down and pass it around, 79 bottles of beer on the wall. 79 bottles of beer on the wall, 79 bottles of beer. Take one down and pass it around, 78 bottles of beer on the wall. 78 bottles of beer on the wall, 78 bottles of beer. Take one down and pass it around, 77 bottles of beer on the wall. 77 bottles of beer on the wall, 77 bottles of beer. Take one down and pass it around, 76 bottles of beer on the wall. 76 bottles of beer on the wall, 76 bottles of beer. Take one down and pass it around, 75 bottles of beer on the wall. 75 bottles of beer on the wall, 75 bottles of beer. Take one down and pass it around, 74 bottles of beer on the wall. 74 bottles of beer on the wall, 74 bottles of beer. Take one down and pass it around, 73 bottles of beer on the wall. 73 bottles of beer on the wall, 73 bottles of beer. Take one down and pass it around, 72 bottles of beer on the wall. 72 bottles of beer on the wall, 72 bottles of beer. Take one down and pass it around, 71 bottles of beer on the wall. 71 bottles of beer on the wall, 71 bottles of beer. Take one down and pass it around, 70 bottles of beer on the wall. 70 bottles of beer on the wall, 70 bottles of beer. Take one down and pass it around, 69 bottles of beer on the wall. 69 bottles of beer on the wall, 69 bottles of beer. Take one down and pass it around, 68 bottles of beer on the wall. 68 bottles of beer on the wall, 68 bottles of beer. Take one down and pass it around, 67 bottles of beer on the wall. 67 bottles of beer on the wall, 67 bottles of beer. Take one down and pass it around, 66 bottles of beer on the wall. 66 bottles of beer on the wall, 66 bottles of beer. Take one down and pass it around, 65 bottles of beer on the wall. 65 bottles of beer on the wall, 65 bottles of beer. Take one down and pass it around, 64 bottles of beer on the wall. 64 bottles of beer on the wall, 64 bottles of beer. Take one down and pass it around, 63 bottles of beer on the wall. 63 bottles of beer on the wall, 63 bottles of beer. Take one down and pass it around, 62 bottles of beer on the wall. 62 bottles of beer on the wall, 62 bottles of beer. Take one down and pass it around, 61 bottles of beer on the wall. 61 bottles of beer on the wall, 61 bottles of beer. Take one down and pass it around, 60 bottles of beer on the wall. 60 bottles of beer on the wall, 60 bottles of beer. Take one down and pass it around, 59 bottles of beer on the wall. 59 bottles of beer on the wall, 59 bottles of beer. Take one down and pass it around, 58 bottles of beer on the wall. 58 bottles of beer on the wall, 58 bottles of beer. Take one down and pass it around, 57 bottles of beer on the wall. 57 bottles of beer on the wall, 57 bottles of beer. Take one down and pass it around, 56 bottles of beer on the wall. 56 bottles of beer on the wall, 56 bottles of beer. Take one down and pass it around, 55 bottles of beer on the wall. 55 bottles of beer on the wall, 55 bottles of beer. Take one down and pass it around, 54 bottles of beer on the wall. 54 bottles of beer on the wall, 54 bottles of beer. Take one down and pass it around, 53 bottles of beer on the wall. 53 bottles of beer on the wall, 53 bottles of beer. Take one down and pass it around, 52 bottles of beer on the wall. 52 bottles of beer on the wall, 52 bottles of beer. Take one down and pass it around, 51 bottles of beer on the wall. 51 bottles of beer on the wall, 51 bottles of beer. Take one down and pass it around, 50 bottles of beer on the wall. 50 bottles of beer on the wall, 50 bottles of beer. Take one down and pass it around, 49 bottles of beer on the wall. 49 bottles of beer on the wall, 49 bottles of beer. Take one down and pass it around, 48 bottles of beer on the wall. 48 bottles of beer on the wall, 48 bottles of beer. Take one down and pass it around, 47 bottles of beer on the wall. 47 bottles of beer on the wall, 47 bottles of beer. Take one down and pass it around, 46 bottles of beer on the wall. 46 bottles of beer on the wall, 46 bottles of beer. Take one down and pass it around, 45 bottles of beer on the wall. 45 bottles of beer on the wall, 45 bottles of beer. Take one down and pass it around, 44 bottles of beer on the wall. 44 bottles of beer on the wall, 44 bottles of beer. Take one down and pass it around, 43 bottles of beer on the wall. 43 bottles of beer on the wall, 43 bottles of beer. Take one down and pass it around, 42 bottles of beer on the wall. 42 bottles of beer on the wall, 42 bottles of beer. Take one down and pass it around, 41 bottles of beer on the wall. 41 bottles of beer on the wall, 41 bottles of beer. Take one down and pass it around, 40 bottles of beer on the wall. 40 bottles of beer on the wall, 40 bottles of beer. Take one down and pass it around, 39 bottles of beer on the wall. 39 bottles of beer on the wall, 39 bottles of beer. Take one down and pass it around, 38 bottles of beer on the wall. 38 bottles of beer on the wall, 38 bottles of beer. Take one down and pass it around, 37 bottles of beer on the wall. 37 bottles of beer on the wall, 37 bottles of beer. Take one down and pass it around, 36 bottles of beer on the wall. 36 bottles of beer on the wall, 36 bottles of beer. Take one down and pass it around, 35 bottles of beer on the wall. 35 bottles of beer on the wall, 35 bottles of beer. Take one down and pass it around, 34 bottles of beer on the wall. 34 bottles of beer on the wall, 34 bottles of beer. Take one down and pass it around, 33 bottles of beer on the wall. 33 bottles of beer on the wall, 33 bottles of beer. Take one down and pass it around, 32 bottles of beer on the wall. 32 bottles of beer on the wall, 32 bottles of beer. Take one down and pass it around, 31 bottles of beer on the wall. 31 bottles of beer on the wall, 31 bottles of beer. Take one down and pass it around, 30 bottles of beer on the wall. 30 bottles of beer on the wall, 30 bottles of beer. Take one down and pass it around, 29 bottles of beer on the wall. 29 bottles of beer on the wall, 29 bottles of beer. Take one down and pass it around, 28 bottles of beer on the wall. 28 bottles of beer on the wall, 28 bottles of beer. Take one down and pass it around, 27 bottles of beer on the wall. 27 bottles of beer on the wall, 27 bottles of beer. Take one down and pass it around, 26 bottles of beer on the wall. 26 bottles of beer on the wall, 26 bottles of beer. Take one down and pass it around, 25 bottles of beer on the wall. 25 bottles of beer on the wall, 25 bottles of beer. Take one down and pass it around, 24 bottles of beer on the wall. 24 bottles of beer on the wall, 24 bottles of beer. Take one down and pass it around, 23 bottles of beer on the wall. 23 bottles of beer on the wall, 23 bottles of beer. Take one down and pass it around, 22 bottles of beer on the wall. 22 bottles of beer on the wall, 22 bottles of beer. Take one down and pass it around, 21 bottles of beer on the wall. 21 bottles of beer on the wall, 21 bottles of beer. Take one down and pass it around, 20 bottles of beer on the wall. 20 bottles of beer on the wall, 20 bottles of beer. Take one down and pass it around, 19 bottles of beer on the wall. 19 bottles of beer on the wall, 19 bottles of beer. Take one down and pass it around, 18 bottles of beer on the wall. 18 bottles of beer on the wall, 18 bottles of beer. Take one down and pass it around, 17 bottles of beer on the wall. 17 bottles of beer on the wall, 17 bottles of beer. Take one down and pass it around, 16 bottles of beer on the wall. 16 bottles of beer on the wall, 16 bottles of beer. Take one down and pass it around, 15 bottles of beer on the wall. 15 bottles of beer on the wall, 15 bottles of beer. Take one down and pass it around, 14 bottles of beer on the wall. 14 bottles of beer on the wall, 14 bottles of beer. Take one down and pass it around, 13 bottles of beer on the wall. 13 bottles of beer on the wall, 13 bottles of beer. Take one down and pass it around, 12 bottles of beer on the wall. 12 bottles of beer on the wall, 12 bottles of beer. Take one down and pass it around, 11 bottles of beer on the wall. 11 bottles of beer on the wall, 11 bottles of beer. Take one down and pass it around, 10 bottles of beer on the wall. 10 bottles of beer on the wall, 10 bottles of beer. Take one down and pass it around, 9 bottles of beer on the wall. 9 bottles of beer on the wall, 9 bottles of beer. Take one down and pass it around, 8 bottles of beer on the wall. 8 bottles of beer on the wall, 8 bottles of beer. Take one down and pass it around, 7 bottles of beer on the wall. 7 bottles of beer on the wall, 7 bottles of beer. Take one down and pass it around, 6 bottles of beer on the wall. 6 bottles of beer on the wall, 6 bottles of beer. Take one down and pass it around, 5 bottles of beer on the wall. 5 bottles of beer on the wall, 5 bottles of beer. Take one down and pass it around, 4 bottles of beer on the wall. 4 bottles of beer on the wall, 4 bottles of beer. Take one down and pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall, 3 bottles of beer. Take one down and pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. ```
Sing : procedure if ARG() \= 2 | \DATATYPE(ARG(1), 'N') , | \DATATYPE(ARG(2), 'N') then ; return '' parse arg from, to if from < to then ; return '' return SingFromTo(from, to) SingFromTo : procedure parse arg from, to if from < to then ; return '' if from == to then ; return Verse(from) || SingFromTo(from - 1, to) return Verse(from) || "0A"X || SingFromTo(from - 1, to) Verse : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') then ; return '' parse arg N ; select when N < 0 | N > 99 then ; verse = '' when N == 0 then ; verse = ZeroBottles() when N == 1 then ; verse = OneBottles() when N == 2 then ; verse = TwoBottles() otherwise verse = N_Bottles(N) end return verse ZeroBottles : return , 'No more bottles of beer on the wall, no more bottles of beer.' || "0A"X || , 'Go to the store and buy some more, 99 bottles of beer on the wall.' || "0A"X OneBottles : return , '1 bottle of beer on the wall, 1 bottle of beer.' || "0A"X || , 'Take it down and pass it around, no more bottles of beer on the wall.' || "0A"X TwoBottles : return , '2 bottles of beer on the wall, 2 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 1 bottle of beer on the wall.' || "0A"X N_Bottles : parse arg N ; return , N 'bottles of beer on the wall,' N 'bottles of beer.' || "0A"X || , 'Take one down and pass it around,' N 'bottles of beer on the wall.' || "0A"X
/* Unit Test Runner: t-rexx */ context('Checking the Verse and Sing functions') /* Test Variables */ verse_0 = , 'No more bottles of beer on the wall, no more bottles of beer.' || "0A"X || , 'Go to the store and buy some more, 99 bottles of beer on the wall.' || "0A"X verse_1 = , '1 bottle of beer on the wall, 1 bottle of beer.' || "0A"X || , 'Take it down and pass it around, no more bottles of beer on the wall.' || "0A"X verse_2 = , '2 bottles of beer on the wall, 2 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 1 bottle of beer on the wall.' || "0A"X verse_3 = , '3 bottles of beer on the wall, 3 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 3 bottles of beer on the wall.' || "0A"X verse_99 = , '99 bottles of beer on the wall, 99 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 99 bottles of beer on the wall.' || "0A"X verse_1_to_0 = , '1 bottle of beer on the wall, 1 bottle of beer.' || "0A"X || , 'Take it down and pass it around, no more bottles of beer on the wall.' || "0A"X , || "0A"X || , 'No more bottles of beer on the wall, no more bottles of beer.' || "0A"X || , 'Go to the store and buy some more, 99 bottles of beer on the wall.' || "0A"X verse_99_to_97 = , '99 bottles of beer on the wall, 99 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 99 bottles of beer on the wall.' || "0A"X , || "0A"X || , '98 bottles of beer on the wall, 98 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 98 bottles of beer on the wall.' || "0A"X , || "0A"X || , '97 bottles of beer on the wall, 97 bottles of beer.' || "0A"X || , 'Take one down and pass it around, 97 bottles of beer on the wall.' || "0A"X verse_99_to_0_length = 11885 /* Unit tests */ check('verse -> single verse -> first generic verse' 'Verse(3)',, 'Verse(3)',, '=', verse_3) check('verse -> single verse -> last generic verse' 'Verse(99)',, 'Verse(99)',, '=', verse_99) check('verse -> single verse -> verse with 2 bottles' 'Verse(2)',, 'Verse(2)',, '=', verse_2) check('verse -> single verse -> verse with 1 bottle' 'Verse(1)',, 'Verse(1)',, '=', verse_1) check('verse -> single verse -> verse with 0 bottles' 'Verse(0)',, 'Verse(0)',, '=', verse_0) check('lyrics -> multiple verses -> first two verses' 'Sing(1, 0)',, 'Sing(1, 0)',, '=', verse_1_to_0) check('lyrics -> multiple verses -> last three verses' 'Sing(99, 97)',, 'Sing(99, 97)',, '=', verse_99_to_97) cmd = 'actual = Sing(99, 0)' ; interpret cmd check('lyrics -> multiple verses -> all verses' 'Sing(99, 0)',, 'Sing(99, 0)', LENGTH(actual), '=', verse_99_to_0_length)
8
# Instructions Your task is to implement a binary search algorithm. A binary search algorithm finds an item in a list by repeatedly splitting it in half, only keeping the half which contains the item we're looking for. It allows us to quickly narrow down the possible locations of our item until we find it, or until we've eliminated all possible locations. ~~~~exercism/caution Binary search only works when a list has been sorted. ~~~~ The algorithm looks like this: - Find the middle element of a sorted list and compare it with the item we're looking for. - If the middle element is our item, then we're done! - If the middle element is greater than our item, we can eliminate that element and all the elements **after** it. - If the middle element is less than our item, we can eliminate that element and all the elements **before** it. - If every element of the list has been eliminated then the item is not in the list. - Otherwise, repeat the process on the part of the list that has not been eliminated. Here's an example: Let's say we're looking for the number 23 in the following sorted list: `[4, 8, 12, 16, 23, 28, 32]`. - We start by comparing 23 with the middle element, 16. - Since 23 is greater than 16, we can eliminate the left half of the list, leaving us with `[23, 28, 32]`. - We then compare 23 with the new middle element, 28. - Since 23 is less than 28, we can eliminate the right half of the list: `[23]`. - We've found our item.
BinarySearch : procedure if ARG() \= 2 | ARG(1) == '' then ; return 0 parse arg needle, haystack parse value 1 WORDS(haystack) , with L R do while L <= R M = (L + R) % 2 if needle == WORD(haystack, M) then if L < M & WORD(haystack, L) == needle then ; return L ; else return M if needle < WORD(haystack, M) then ; R = M - 1 ; else L = M + 1 end return 0
/* Unit Test Runner: t-rexx */ context('Checking the BinarySearch function') /* Unit tests */ check('finds a value in an array with one element' 'BinarySearch("10", "10")',, 'BinarySearch("10", "10")',, '=', 1) check('finds a value in the middle of an array' 'BinarySearch("6", "1 2 3 4 5 6 7 8 9 10 11")',, 'BinarySearch("6", "1 2 3 4 5 6 7 8 9 10 11")',, '=', 6) check('finds a value at the beginning of an array' 'BinarySearch("1", "1 2 3 4 5 6 7 8 9 10 11")',, 'BinarySearch("1", "1 2 3 4 5 6 7 8 9 10 11")',, '=', 1) check('finds a value in an array of odd length' 'BinarySearch("3", "1 2 3 4 5 6 7 8 9 10 11")',, 'BinarySearch("3", "1 2 3 4 5 6 7 8 9 10 11")',, '=', 3) check('finds a value in an array of even length' 'BinarySearch("3", "1 2 3 4 5 6 7 8 9 10")',, 'BinarySearch("3", "1 2 3 4 5 6 7 8 9 10")',, '=', 3) check('identifies that a value is not included in the array' 'BinarySearch("4", "1 2 3 5 6 7 8 9 10 11")',, 'BinarySearch("4", "1 2 3 5 6 7 8 9 10 11")',, '=', 0) check('a value smaller than the array''s smallest value is not found' 'BinarySearch("0", "1 2 3 4 5 6 7 8 9 10 11")',, 'BinarySearch("0", "1 2 3 4 5 6 7 8 9 10 11")',, '=', 0) check('a value larger than the array''s largest value is not found' 'BinarySearch("13", "1 2 3 4 5 6 7 8 9 10 11")',, 'BinarySearch("13", "1 2 3 4 5 6 7 8 9 10 11")',, '=', 0) check('nothing is found in an empty array' 'BinarySearch("10", "")',, 'BinarySearch("10", "")',, '=', 0)
9
# Instructions Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question, such as "How are you?". He answers 'Whoa, chill out!' if you YELL AT HIM (in all capitals). He answers 'Calm down, I know what I'm doing!' if you yell a question at him. He says 'Fine. Be that way!' if you address him without actually saying anything. He answers 'Whatever.' to anything else. Bob's conversational partner is a purist when it comes to written communication and always follows normal rules regarding sentence punctuation in English.
Hey : procedure /* Convert \n, \r, \t to spaces, then strip and normalize spaces */ message = SPACE(TRANSLATE(ARG(1), ' ', "09"X||"0A"X||"0D"X)) if message == '' then ; return 'Fine. Be that way!' isQuestion = RIGHT(message, 1) == '?' /* Remove digits and punctuation, but retain spaces */ NON_LETTERS = '~`!@#$%^&*()_-+=<,>.?/:;"''0123456789' message = CHANGESTR(';',, TRANSLATE(message,, NON_LETTERS,, ';'),, '') isYelling = message \= '' & message == UPPER(message) if isYelling & isQuestion then ; return 'Calm down, I know what I''m doing!' if isYelling & \isQuestion then ; return 'Whoa, chill out!' if isQuestion then ; return 'Sure.' return 'Whatever.'
/* Unit Test Runner: t-rexx */ context('Checking the Hey function') /* Unit tests */ check('stating something' 'Hey("Tom-ay-to, tom-aaaah-to.")',, 'Hey("Tom-ay-to, tom-aaaah-to.")',, '=', 'Whatever.') check('shouting' 'Hey("WATCH OUT!")',, 'Hey("WATCH OUT!")',, '=', 'Whoa, chill out!') check('shouting gibberish' 'Hey("FCECDFCAAB")',, 'Hey("FCECDFCAAB")',, '=', 'Whoa, chill out!') check('asking a question' 'Hey("Does this cryogenic chamber make me look fat?")',, 'Hey("Does this cryogenic chamber make me look fat?")',, '=', 'Sure.') check('asking a numeric question' 'Hey("You are, what, like 15?")',, 'Hey("You are, what, like 15?")',, '=', 'Sure.') check('asking gibberish' 'Hey("fffbbcbeab?")',, 'Hey("fffbbcbeab?")',, '=', 'Sure.') check('talking forcefully' 'Hey("Hi there!")',, 'Hey("Hi there!")',, '=', 'Whatever.') check('using acronyms in regular speech' 'Hey("It's OK if you don't want to go work for NASA.")',, 'Hey("It's OK if you don't want to go work for NASA.")',, '=', 'Whatever.') check('forceful question' 'Hey("WHAT''S GOING ON?")',, 'Hey("WHAT''S GOING ON?")',, '=', 'Calm down, I know what I''m doing!') check('shouting numbers' 'Hey("1, 2, 3 GO!")',, 'Hey("1, 2, 3 GO!")',, '=', 'Whoa, chill out!') check('no letters' 'Hey("1, 2, 3")',, 'Hey("1, 2, 3")',, '=', 'Whatever.') check('question with no letters' 'Hey("4?")',, 'Hey("4?")',, '=', 'Sure.') check('shouting with special characters' 'Hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")',, 'Hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")',, '=', 'Whoa, chill out!') check('shouting with no exclamation mark' 'Hey("I HATE THE DENTIST")',, 'Hey("I HATE THE DENTIST")',, '=', 'Whoa, chill out!') check('statement containing question mark' 'Hey("Ending with ? means a question.")',, 'Hey("Ending with ? means a question.")',, '=', 'Whatever.') check('non-letters with question' 'Hey(":) ?")',, 'Hey(":) ?")',, '=', 'Sure.') check('prattling on' 'Hey("Wait! Hang on. Are you going to be OK?")',, 'Hey("Wait! Hang on. Are you going to be OK?")',, '=', 'Sure.') check('silence' 'Hey("")',, 'Hey("")',, '=', 'Fine. Be that way!') check('prolonged silence' 'Hey(" ")',, 'Hey(" ")',, '=', 'Fine. Be that way!') check('alternate silence' 'Hey(COPIES("09"X, 10))',, 'Hey(COPIES("09"X, 10))',, '=', 'Fine. Be that way!') check('multiple line question' 'Hey("0A"X||"Does this cryogenic chamber make me look fat?"||"0A"X||"No")',, 'Hey("0A"X||"Does this cryogenic chamber make me look fat?"||"0A"X||"No")',, '=', 'Whatever.') check('starting with whitespace' 'Hey(" hmmmmmmm...")',, 'Hey(" hmmmmmmm...")',, '=', 'Whatever.') check('ending with whitespace' 'Hey("Okay if like my spacebar quite a bit? ")',, 'Hey("Okay if like my spacebar quite a bit? ")',, '=', 'Sure.') check('other whitespace' 'Hey("0A"X||"0D"X||" "||"09"X)',, 'Hey("0A"X||"0D"X||" "||"09"X)',, '=', 'Fine. Be that way!') check('non-question ending with whitespace' 'Hey("This is a statement ending with whitespace ")',, 'Hey("This is a statement ending with whitespace ")',, '=', 'Whatever.') check('no input is silence' 'Hey()',, 'Hey()',, '=', 'Fine. Be that way!')
10
# Instructions Implement a clock that handles times without dates. You should be able to add and subtract minutes to it. Two clocks that represent the same time should be equal to each other.
Create : procedure parse arg hours, minutes return Add(minutes, (hours * 60)) GetTime : procedure parse arg clock return RIGHT(clock % 60, 2, '0') || ':' || RIGHT(clock // 60, 2, '0') Add : procedure parse arg minutes, clock return ((((clock + minutes) // 1440) + 1440) // 1440) Subtract : procedure parse arg minutes, clock return Add(-minutes, clock)
/* Unit Test Runner: t-rexx */ context('Checking the Create, Add, Subtract, and GetTime functions') /* Unit tests */ check('on the hour' 'GetTime(Create(8, 0))',, 'GetTime(Create(8, 0))',, '=', '08:00') check('past the hour' 'GetTime(Create(11, 9))',, 'GetTime(Create(11, 9))',, '=', '11:09') check('midnight is zero hours' 'GetTime(Create(24, 0))',, 'GetTime(Create(24, 0))',, '=', '00:00') check('hour rolls over' 'GetTime(Create(25, 0))',, 'GetTime(Create(25, 0))',, '=', '01:00') check('hour rolls over continuously' 'GetTime(Create(100, 0))',, 'GetTime(Create(100, 0))',, '=', '04:00') check('sixty minutes is next hour' 'GetTime(Create(1, 60))',, 'GetTime(Create(1, 60))',, '=', '02:00') check('minutes roll over' 'GetTime(Create(0, 160))',, 'GetTime(Create(0, 160))',, '=', '02:40') check('minutes roll over continuously' 'GetTime(Create(0, 1723))',, 'GetTime(Create(0, 1723))',, '=', '04:43') check('hour and minutes roll over' 'GetTime(Create(25, 160))',, 'GetTime(Create(25, 160))',, '=', '03:40') check('hour and minutes roll over continuously' 'GetTime(Create(201, 3001))',, 'GetTime(Create(201, 3001))',, '=', '11:01') check('hour and minutes roll over to exactly midnight' 'GetTime(Create(72, 8640))',, 'GetTime(Create(72, 8640))',, '=', '00:00') check('negative hour' 'GetTime(Create(-1, 15))',, 'GetTime(Create(-1, 15))',, '=', '23:15') check('negative hour rolls over' 'GetTime(Create(-25, 0))',, 'GetTime(Create(-25, 0))',, '=', '23:00') check('negative hour rolls over continuously' 'GetTime(Create(-91, 0))',, 'GetTime(Create(-91, 0))',, '=', '05:00') check('negative minutes' 'GetTime(Create(1, -40))',, 'GetTime(Create(1, -40))',, '=', '00:20') check('negative minutes roll over' 'GetTime(Create(1, -160))',, 'GetTime(Create(1, -160))',, '=', '22:20') check('negative minutes roll over continuously' 'GetTime(Create(1, -4820))',, 'GetTime(Create(1, -4820))',, '=', '16:40') check('negative sixty minutes is previous hour' 'GetTime(Create(2, -60))',, 'GetTime(Create(2, -60))',, '=', '01:00') check('negative hour and minutes both roll over' 'GetTime(Create(-25, -160))',, 'GetTime(Create(-25, -160))',, '=', '20:20') check('negative hour and minutes both roll over continuously' 'GetTime(Create(-121, -5810))',, 'GetTime(Create(-121, -5810))',, '=', '22:10') check('Add minutes' 'GetTime(Add(3, Create(10, 0)))',, 'GetTime(Add(3, Create(10, 0)))',, '=', '10:03') check('Add no minutes' 'GetTime(Add(0, Create(6, 41)))',, 'GetTime(Add(0, Create(6, 41)))',, '=', '06:41') check('Add to next hour' 'GetTime(Add(40, Create(0, 45)))',, 'GetTime(Add(40, Create(0, 45)))',, '=', '01:25') check('Add more than one hour' 'GetTime(Add(61, Create(10, 0)))',, 'GetTime(Add(61, Create(10, 0)))',, '=', '11:01') check('Add more than two hours with carry' 'GetTime(Add(160, Create(0, 45)))',, 'GetTime(Add(160, Create(0, 45)))',, '=', '03:25') check('Add across midnight' 'GetTime(Add(2, Create(23, 59)))',, 'GetTime(Add(2, Create(23, 59)))',, '=', '00:01') check('Add more than one day 1500 min 25 hrs' 'GetTime(Add(1500, Create(5, 32)))',, 'GetTime(Add(1500, Create(5, 32)))',, '=', '06:32') check('Add more than two days' 'GetTime(Add(3500, Create(1, 1)))',, 'GetTime(Add(3500, Create(1, 1)))',, '=', '11:21') check('Subtract minutes' 'GetTime(Subtract(3, Create(10, 3)))',, 'GetTime(Subtract(3, Create(10, 3)))',, '=', '10:00') check('Subtract to previous hour' 'GetTime(Subtract(30, Create(10, 3)))',, 'GetTime(Subtract(30, Create(10, 3)))',, '=', '09:33') check('Subtract more than an hour' 'GetTime(Subtract(70, Create(10, 3)))',, 'GetTime(Subtract(70, Create(10, 3)))',, '=', '08:53') check('Subtract across midnight' 'GetTime(Subtract(4, Create(0, 3)))',, 'GetTime(Subtract(4, Create(0, 3)))',, '=', '23:59') check('Subtract more than two hours' 'GetTime(Subtract(160, Create(0, 0)))',, 'GetTime(Subtract(160, Create(0, 0)))',, '=', '21:20') check('Subtract more than two hours with borrow' 'GetTime(Subtract(160, Create(6, 15)))',, 'GetTime(Subtract(160, Create(6, 15)))',, '=', '03:35') check('Subtract more than one day 1500 min 25 hrs' 'GetTime(Subtract(1500, Create(5, 32)))',, 'GetTime(Subtract(1500, Create(5, 32)))',, '=', '04:32') check('Subtract more than two days' 'GetTime(Subtract(3000, Create(2, 20)))',, 'GetTime(Subtract(3000, Create(2, 20)))',, '=', '00:20') check('clocks with same time' 'Create(15, 37)',, 'Create(15, 37)',, '=', Create(15, 37)) check('clocks a minute apart' 'Create(15, 36)',, 'Create(15, 36)',, '\=', Create(15, 37)) check('clocks an hour apart' 'Create(14, 37)',, 'Create(14, 37)',, '\=', Create(15, 37)) check('clocks with hour overflow' 'Create(10, 37)',, 'Create(10, 37)',, '=', Create(34, 37)) check('clocks with hour overflow by several days' 'Create(3, 11)',, 'Create(3, 11)',, '=', Create(99, 11)) check('clocks with negative hour' 'Create(22, 40)',, 'Create(22, 40)',, '=', Create(-2, 40)) check('clocks with negative hour that wraps' 'Create(17, 3)',, 'Create(17, 3)',, '=', Create(-31, 3)) check('clocks with negative hour that wraps multiple times' 'Create(13, 49)',, 'Create(13, 49)',, '=', Create(-83, 49)) check('clocks with minute overflow' 'Create(0, 1)',, 'Create(0, 1)',, '=', Create(0, 1441)) check('clocks with minute overflow by several days' 'Create(2, 2)',, 'Create(2, 2)',, '=', Create(2, 4322)) check('clocks with negative minute' 'Create(2, 40)',, 'Create(2, 40)',, '=', Create(3, -20)) check('clocks with negative minute that wraps' 'Create(4, 10)',, 'Create(4, 10)',, '=', Create(5, -1490)) check('clocks with negative minute that wraps multiple times' 'Create(6, 15)',, 'Create(6, 15)',, '=', Create(6, -4305)) check('clocks with negative hours and minutes' 'Create(7, 32)',, 'Create(7, 32)',, '=', Create(-12, -268)) check('clocks with negative hours and minutes that wrap' 'Create(18, 7)',, 'Create(18, 7)',, '=', Create(-54, -11513)) check('full clock and zeroed clock' 'Create(24, 0)',, 'Create(24, 0)',, '=', Create(0, 0))
11
# Instructions The Collatz Conjecture or 3x+1 problem can be summarized as follows: Take any positive integer n. If n is even, divide n by 2 to get n / 2. If n is odd, multiply n by 3 and add 1 to get 3n + 1. Repeat the process indefinitely. The conjecture states that no matter which number you start with, you will always reach 1 eventually. Given a number n, return the number of steps required to reach 1. ## Examples Starting with n = 12, the steps would be as follows: 0. 12 1. 6 2. 3 3. 10 4. 5 5. 16 6. 8 7. 4 8. 2 9. 1 Resulting in 9 steps. So for input n = 12, the return value would be 9.
ComputeSteps : procedure parse arg number if number == 1 then ; return 0 if number // 2 == 0 then ; return 1 + ComputeSteps(number % 2) return 1 + ComputeSteps(number * 3 + 1) Steps : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') then ; return -1 parse arg number if number < 1 then ; return -1 return ComputeSteps(number)
/* Unit Test Runner: t-rexx */ context('Checking the Steps function') /* Test Options */ numeric digits 20 /* Unit tests */ check('zero steps for one' 'Steps(1)',, 'Steps(1)',, '=', 0) check('divide if even' 'Steps(16)',, 'Steps(16)',, '=', 4) check('even and odd steps' 'Steps(12)',, 'Steps(12)',, '=', 9) check('large number of even and odd steps' 'Steps(1000000)',, 'Steps(1000000)',, '=', 152) check('zero is an error' 'Steps(0)',, 'Steps(0)',, '=', -1) check('negative value is an error' 'Steps(-1)',, 'Steps(-1)',, '=', -1)
12
# Instructions Create a custom set type. Sometimes it is necessary to define a custom data structure of some type, like a set. In this exercise you will define your own set. How it works internally doesn't matter, as long as it behaves like a set of unique elements.
SetCreate : procedure if ARG(1) == '' then ; return 'SET;0;' elements = SortWords(DedupWord(ARG(1))) return 'SET;' || WORDS(elements) || ';' || elements SetAdd : procedure parse arg set, newelem parse var set 'SET;' size ';' elements if WORDPOS(newelem, elements) > 0 then ; return set return 'SET;' || (size + 1) || ';' || SortWords(newelem elements) SetDifference : procedure parse arg set1, set2 parse var set1 'SET;' . ';' elements1 parse var set2 'SET;' . ';' elements2 elemsCpy = elements2 ; elemsDiff = elements1 do while elemsCpy \= '' parse var elemsCpy elem elemsCpy parse value WORDPOS(elem, elemsDiff) with elemPos if elemPos > 0 then ; elemsDiff = DELWORD(elemsDiff, elemPos, 1) end return SetCreate(elemsDiff) SetIntersection : procedure parse arg set1, set2 parse var set1 'SET;' . ';' elements1 parse var set2 'SET;' . ';' elements2 elemsCpy = elements2 ; elemsCommon = '' do while elemsCpy \= '' parse var elemsCpy elem elemsCpy if WORDPOS(elem, elements1) > 0 then ; elemsCommon ||= elem '' end elemsCpy = elements1 do while elemsCpy \= '' parse var elemsCpy elem elemsCpy if WORDPOS(elem, elements2) > 0 then ; elemsCommon ||= elem '' end return SetCreate(elemsCommon) SetUnion : procedure parse arg set1, set2 parse var set1 'SET;' . ';' elements1 parse var set2 'SET;' . ';' elements2 return SetCreate(elements1 elements2) SetIsSet : procedure if ARG(1) == '' then ; return 0 if SUBSTR(ARG(1), 1, 4) \= 'SET;' then ; return 0 return 1 SetContains : procedure parse arg set, elem parse var set 'SET;' size ';' elements if size < 1 then ; return 0 return WORDPOS(elem, elements) > 0 SetIsDisjoint : ; return SetIsEmpty(SetIntersection(ARG(1), ARG(2))) SetIsEmpty : procedure parse arg set parse var set 'SET;' size ';' . return size < 1 SetIsEqual : procedure parse arg set1, set2 parse var set1 'SET;' size1 ';' elements1 parse var set2 'SET;' size2 ';' elements2 if size1 \= size2 then ; return 0 return elements1 == elements2 SetIsSubset : procedure parse arg set1, set2 parse var set1 'SET;' size1 ';' elements1 parse var set2 'SET;' size2 ';' elements2 if size2 < 1 then ; return 1 if size2 > size1 then ; return 0 if size2 == size1 then ; return elements2 == elements1 elemsCpy = elements2 do while elemsCpy \= '' parse var elemsCpy elem elemsCpy if WORDPOS(elem, elements1) < 1 then ; return 0 end return 1 DedupWord : procedure parse arg input output = '' ; do while input \= '' parse var input token input if WORDPOS(token, output) < 1 then ; output ||= token '' end return STRIP(output, 'T') SortWords: procedure words = ARG(1) ; parse value WORDS(words) WORD(words, 1) with n sorted if n < 2 then ; return sorted do i = 2 to n next = WORD(words, i) do j = 1 to i-1 if next < WORD(sorted, j) then do if j > 1 then ; lm = SUBWORD(sorted, 1, j-1) ; else lm = '' sorted = lm next SUBWORD(sorted, j) leave j end if j == i-1 then ; sorted = sorted next end end return STRIP(sorted)
/* Unit Test Runner: t-rexx */ context('Checking the Custom Set exercise functions') /* Test Variables */ emptySet = SetCreate("") fullSet1 = SetCreate("AX TR WS TRYT ZXU AX TDY WS FGH") fullSet2 = SetCreate("JK YS WS QAFS FGH MNB") fullSet3 = SetCreate("QAFS BDF X77") subSet1 = SetCreate("AX WS TR") subSet2 = SetCreate("QAFS") intersectFullSet1And2 = SetCreate("FGH WS") unionFullSet1And2 = SetCreate("AX FGH JK MNB QAFS TDY TR TRYT WS YS ZXU") diffFullSet1And2 = SetCreate("AX TDY TR TRYT ZXU") diffFullSet2And1 = SetCreate("JK MNB QAFS YS") /* Unit tests */ check('sets with no elements are empty' 'SetIsEmpty(emptySet)',, 'SetIsEmpty(emptySet)',, '=', 1) check('sets with elements are not empty' 'SetIsEmpty(fullSet1)',, 'SetIsEmpty(fullSet1)',, '=', 0) check('nothing is contained in an empty set' 'SetContains(emptySet, "AX")',, 'SetContains(emptySet, "AX")',, '=', 0) check('when the element is in the set' 'SetContains(fullSet1, "AX")',, 'SetContains(fullSet1, "AX")',, '=', 1) check('when the element is not in the set' 'SetContains(fullSet1, "IJ")',, 'SetContains(fullSet1, "IJ")',, '=', 0) check('empty set is a subset of another empty set' 'SetIsSubset(emptySet, emptySet)',, 'SetIsSubset(emptySet, emptySet)',, '=', 1) check('empty set is a subset of non-empty set' 'SetIsSubset(fullSet1, emptySet)',, 'SetIsSubset(fullSet1, emptySet)',, '=', 1) check('non-empty set is not a subset of empty set' 'SetIsSubset(emptySet, fullSet1)',, 'SetIsSubset(emptySet, fullSet1)',, '=', 0) check('set is a subset of set with exact same elements' 'SetIsSubset(fullSet1, fullSet1)',, 'SetIsSubset(fullSet1, fullSet1)',, '=', 1) check('set is a subset of larger set with same elements' 'SetIsSubset(fullSet1, subSet1)',, 'SetIsSubset(fullSet1, subSet1)',, '=', 1) check('set is not a subset of set that does not contain its elements' 'SetIsSubset(subSet2, subSet1)',, 'SetIsSubset(subSet2, subSet1)',, '=', 0) check('the empty set is disjoint with itself' 'SetIsDisjoint(emptySet, emptySet)',, 'SetIsDisjoint(emptySet, emptySet)',, '=', 1) check('empty set is disjoint with non-empty set' 'SetIsDisjoint(fullSet1, emptySet)',, 'SetIsDisjoint(fullSet1, emptySet)',, '=', 1) check('non-empty set is disjoint with empty set' 'SetIsDisjoint(emptySet, fullSet1)',, 'SetIsDisjoint(emptySet, fullSet1)',, '=', 1) check('sets are not disjoint if they share an element' 'SetIsDisjoint(fullSet1, fullSet2)',, 'SetIsDisjoint(fullSet1, fullSet2)',, '=', 0) check('sets are disjoint if they share no elements' 'SetIsDisjoint(subSet1, subSet2)',, 'SetIsDisjoint(subSet1, subSet2)',, '=', 1) check('empty sets are equal' 'SetIsEqual(emptySet, emptySet)',, 'SetIsEqual(emptySet, emptySet)',, '=', 1) check('empty set is not equal to non-empty set' 'SetIsEqual(emptySet, fullSet1)',, 'SetIsEqual(emptySet, fullSet1)',, '=', 0) check('non-empty set is not equal to empty set' 'SetIsEqual(fullSet1, emptySet)',, 'SetIsEqual(fullSet1, emptySet)',, '=', 0) check('sets with the same elements are equal' 'SetIsEqual(fullSet1, fullSet1)',, 'SetIsEqual(fullSet1, fullSet1)',, '=', 1) check('sets with different elements are not equal' 'SetIsEqual(fullSet1, fullSet2)',, 'SetIsEqual(fullSet1, fullSet2)',, '=', 0) check('set is not equal to larger set with same elements' 'SetIsEqual(fullSet1, subSet1)',, 'SetIsEqual(fullSet1, subSet1)',, '=', 0) check('add to empty set' 'SetAdd(emptySet, "AX")',, 'SetAdd(emptySet, "AX")',, '=', SetCreate("AX")) check('add to non-empty set' 'SetAdd(subSet2, "AX")',, 'SetAdd(subSet2, "AX")',, '=', SetCreate("QAFS AX")) check('adding an existing element does not change the set' 'SetAdd(subSet1, "AX")',, 'SetAdd(subSet1, "AX")',, '=', subSet1) check('intersection of two empty sets is an empty set' 'SetIntersection(emptySet, emptySet)',, 'SetIntersection(emptySet, emptySet)',, '=', emptySet) check('intersection of an empty set and non-empty set is an empty set' 'SetIntersection(emptySet, fullSet1)',, 'SetIntersection(emptySet, fullSet1)',, '=', emptySet) check('intersection of a non-empty set and an empty set is an empty set' 'SetIntersection(fullSet1, emptySet)',, 'SetIntersection(fullSet1, emptySet)',, '=', emptySet) check('intersection of two sets with no shared elements is an empty set' 'SetIntersection(fullSet1, fullSet3)',, 'SetIntersection(fullSet1, fullSet3)',, '=', emptySet) check('intersection of two sets with shared elements is a set of the shared elements' 'SetIntersection(fullSet1, fullSet2)',, 'SetIntersection(fullSet1, fullSet2)',, '=', intersectFullSet1And2) check('difference of two empty sets is an empty set' 'SetDifference(emptySet, emptySet)',, 'SetDifference(emptySet, emptySet)',, '=', emptySet) check('difference of empty set and non-empty set is an empty set' 'SetDifference(emptySet, fullSet1)',, 'SetDifference(emptySet, fullSet1)',, '=', emptySet) check('difference of a non-empty set and an empty set is the non-empty set' 'SetDifference(fullSet1, emptySet)',, 'SetDifference(fullSet1, emptySet)',, '=', fullSet1) check('difference of two non-empty sets is a set of elements that are only in the first set' 'SetDifference(fullSet1, fullSet2)',, 'SetDifference(fullSet1, fullSet2)',, '=', diffFullSet1And2) check('difference of two non-empty sets is a set of elements that are only in the first set' 'SetDifference(fullSet2, fullSet1)',, 'SetDifference(fullSet2, fullSet1)',, '=', diffFullSet2And1) check('union of empty sets is an empty set' 'SetUnion(emptySet, emptySet)',, 'SetUnion(emptySet, emptySet)',, '=', emptySet) check('union of an empty set and non-empty set is the non-empty set' 'SetUnion(emptySet, fullSet1)',, 'SetUnion(emptySet, fullSet1)',, '=', fullSet1) check('union of a non-empty set and empty set is the non-empty set' 'SetUnion(fullSet1, emptySet)',, 'SetUnion(fullSet1, emptySet)',, '=', fullSet1) check('union of non-empty sets contains all unique elements' 'SetUnion(fullSet1, fullSet2)',, 'SetUnion(fullSet1, fullSet2)',, '=', unionFullSet1And2) check('union of non-empty sets contains all unique elements' 'SetUnion(fullSet2, fullSet1)',, 'SetUnion(fullSet2, fullSet1)',, '=', unionFullSet1And2)
13
# Instructions Write a function that returns the earned points in a single toss of a Darts game. [Darts][darts] is a game where players throw darts at a [target][darts-target]. In our particular instance of the game, the target rewards 4 different amounts of points, depending on where the dart lands: - If the dart lands outside the target, player earns no points (0 points). - If the dart lands in the outer circle of the target, player earns 1 point. - If the dart lands in the middle circle of the target, player earns 5 points. - If the dart lands in the inner circle of the target, player earns 10 points. The outer circle has a radius of 10 units (this is equivalent to the total radius for the entire target), the middle circle a radius of 5 units, and the inner circle a radius of 1. Of course, they are all centered at the same point (that is, the circles are [concentric][] defined by the coordinates (0, 0). Write a function that given a point in the target (defined by its [Cartesian coordinates][cartesian-coordinates] `x` and `y`, where `x` and `y` are [real][real-numbers]), returns the correct amount earned by a dart landing at that point. [darts]: https://en.wikipedia.org/wiki/Darts [darts-target]: https://en.wikipedia.org/wiki/Darts#/media/File:Darts_in_a_dartboard.jpg [concentric]: https://mathworld.wolfram.com/ConcentricCircles.html [cartesian-coordinates]: https://www.mathsisfun.com/data/cartesian-coordinates.html [real-numbers]: https://www.mathsisfun.com/numbers/real-numbers.html
SQRT : procedure parse value ABS(ARG(1)) 1 0 with x r r1 if x == 0 then ; return 0 do while r \= r1 ; parse value r (x / r + r) / 2 with r1 r ; end return r Score : procedure if ARG() \= 2 | \DATATYPE(ARG(1), 'N') | \DATATYPE(ARG(2), 'N') then ; return -1 parse arg x, y ; radius = SQRT(x * x + y * y) if radius <= 1 then ; return 10 if radius <= 5 then ; return 5 if radius <= 10 then ; return 1 return 0
/* Unit Test Runner: t-rexx */ context('Checking the Score function') /* Unit tests */ check('Missed target' 'Score(-9, 9)',, 'Score(-9, 9)',, '=', 0) check('On the outer circle' 'Score(0, 10)',, 'Score(0, 10)',, '=', 1) check('On the middle circle' 'Score(-5, 0)',, 'Score(-5, 0)',, '=', 5) check('On the inner circle' 'Score(0, -1)',, 'Score(0, -1)',, '=', 10) check('Exactly on centre' 'Score(0, 0)',, 'Score(0, 0)',, '=', 10) check('Near the centre' 'Score(-0.1, -0.1)',, 'Score(-0.1, -0.1)',, '=', 10) check('Just within the inner circle' 'Score(0.7, 0.7)',, 'Score(0.7, 0.7)',, '=', 10) check('Just outside the inner circle' 'Score(0.8, -0.8)',, 'Score(0.8, -0.8)',, '=', 5) check('Just within the middle circle' 'Score(-3.5, 3.5)',, 'Score(-3.5, 3.5)',, '=', 5) check('Just outside the middle circle' 'Score(-3.6, 3.6)',, 'Score(-3.6, 3.6)',, '=', 1) check('Just within the outer circle' 'Score(-7.0, 7.0)',, 'Score(-7.0, 7.0)',, '=', 1) check('Just outside the outer circle' 'Score(7.1, -7.1)',, 'Score(7.1, -7.1)',, '=', 0) check('Asymmetric position between the inner and middle circles' 'Score(0.5, -4)',, 'Score(0.5, -4)',, '=', 5)
14
# Instructions Find the difference between the square of the sum and the sum of the squares of the first N natural numbers. The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025. The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385. Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640. You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.
SumOfSquares : procedure parse arg n return n * (n + 1) * (2 * n + 1) / 6 SquareOfSum : procedure parse arg n return (n * (n + 1) / 2) ** 2 Difference : procedure parse arg n return SquareOfSum(n) - SumOfSquares(n)
/* Unit Test Runner: t-rexx */ context('Checking the SquareOfSum, SumOfSquares, and Difference functions') /* Unit tests */ check('Square the sum of the numbers up to the given number' 'SquareOfSum(1)',, 'SquareOfSum(1)',, '=', 1) check('Square the sum of the numbers up to the given number' 'SquareOfSum(5)',, 'SquareOfSum(5)',, '=', 225) check('Square the sum of the numbers up to the given number' 'SquareOfSum(100)',, 'SquareOfSum(100)',, '=', 25502500) check('Sum the squares of the numbers up to the given number' 'SumOfSquares(1)',, 'SumOfSquares(1)',, '=', 1) check('Sum the squares of the numbers up to the given number' 'SumOfSquares(5)',, 'SumOfSquares(5)',, '=', 55) check('Sum the squares of the numbers up to the given number' 'SumOfSquares(100)',, 'SumOfSquares(100)',, '=', 338350) check('Subtract sum of squares from square of sums' 'Difference(1)',, 'Difference(1)',, '=', 0) check('Subtract sum of squares from square of sums' 'Difference(5)',, 'Difference(5)',, '=', 170) check('Subtract sum of squares from square of sums' 'Difference(100)',, 'Difference(100)',, '=', 25164150)
15
# Instructions Implement various kinds of error handling and resource management. An important point of programming is how to handle errors and close resources even if errors occur. This exercise requires you to handle various errors. Because error handling is rather programming language specific you'll have to refer to the tests for your track to see what's exactly required.
HandleErrorUsingReturnCode : procedure if ARG() \= 1 | ARG(1) == '' then ; return -1 return ARG(1)
/* Unit Test Runner: t-rexx */ context('Checking the HandleErrorUsingReturnCode function') /* Unit tests */ check('HandleErrorUsingReturnCode with valid argument' 'HandleErrorUsingReturnCode("value_to_return")',, 'HandleErrorUsingReturnCode("value_to_return")',, '=', 'value_to_return') check('HandleErrorUsingReturnCode with no argument' 'HandleErrorUsingReturnCode()',, 'HandleErrorUsingReturnCode()',, '=', -1) check('HandleErrorUsingReturnCode with empty string argument' 'HandleErrorUsingReturnCode("")',, 'HandleErrorUsingReturnCode("")',, '=', -1) check('HandleErrorUsingReturnCode with extra arguments' 'HandleErrorUsingReturnCode("a", 4, 5.3)',, 'HandleErrorUsingReturnCode("a", 4, 5.3)',, '=', -1)
16
# Instructions Your task is to change the data format of letters and their point values in the game. Currently, letters are stored in groups based on their score, in a one-to-many mapping. - 1 point: "A", "E", "I", "O", "U", "L", "N", "R", "S", "T", - 2 points: "D", "G", - 3 points: "B", "C", "M", "P", - 4 points: "F", "H", "V", "W", "Y", - 5 points: "K", - 8 points: "J", "X", - 10 points: "Q", "Z", This needs to be changed to store each individual letter with its score in a one-to-one mapping. - "a" is worth 1 point. - "b" is worth 3 points. - "c" is worth 3 points. - "d" is worth 2 points. - etc. As part of this change, the team has also decided to change the letters to be lower-case rather than upper-case. ~~~~exercism/note If you want to look at how the data was previously structured and how it needs to change, take a look at the examples in the test suite. ~~~~
OrderSequence : procedure if ARG() \= 2 | ARG(1) == '' | ARG(2) == '' then ; return '' order = ARG(1) ; data = ARG(2) ; output = '' do while order \= '' parse var order letter +1 order pos = POS(letter, data) if pos > 0 then do parse value SUBSTR(data, pos) with datum . output ||= STRIP(datum) '' end end return output Transform : procedure if ARG() < 1 | ARG() > 2 | ARG(1) == '' then ; return '' RECSEP = ';' ; KEYSEP = ':' ; output = '' input = ARG(1) ; do while input \= '' parse lower var input record (RECSEP) input parse var record key (KEYSEP) data do while data \= '' parse var data value data output ||= value || KEYSEP || key '' end end if ARG(2) \= '' then ; output = OrderSequence(ARG(2), output) return STRIP(output)
/* Unit Test Runner: t-rexx */ context('Checking the Transform function') /* Test Variables */ inputA = '1:A E I O U L N R S T;' ||, '2:D G;' ||, '3:B C M P;' ||, '4:F H V W Y;' ||, '5:K;' ||, '8:J X;' ||, '10:Q Z;' outputA = 'a:1 e:1 i:1 o:1 u:1 l:1 n:1 r:1 s:1 t:1 d:2 g:2 b:3' , 'c:3 m:3 p:3 f:4 h:4 v:4 w:4 y:4 k:5 j:8 x:8 q:10 z:10' inputB = '1:A E I O U L N R S T;' ||, '2:D G;' ||, '3:B C M P;' ||, '4:F H V W Y;' ||, '5:K;' ||, '8:J X;' ||, '10:Q Z;' outputB = 'a:1 b:3 c:3 d:2 e:1 f:4 g:2 h:4 i:1 j:8 k:5 l:1 m:3' , 'n:1 o:1 p:3 q:10 r:1 s:1 t:1 u:1 v:4 w:4 x:8 y:4 z:10' orderB = XRANGE('a', 'z') /* Unit tests */ check('single letter' 'Transform("1:A")',, 'Transform("1:A")',, '=', "a:1") check('single score with multiple letters' 'Transform("1:A E I O U;")',, 'Transform("1:A E I O U;")',, '=', "a:1 e:1 i:1 o:1 u:1") check('multiple scores with multiple letters' 'Transform("1:A E;2:D G;")',, 'Transform("1:A E;2:D G;")',, '=', "a:1 e:1 d:2 g:2") check('multiple scores with differing numbers of letters' 'Transform(inputA)',, 'Transform(inputA)',, '=', outputA) check('multiple scores with differing numbers of letters (output ordered)' 'Transform(inputB, orderB)',, 'Transform(inputB, orderB)',, '=', outputB)
17
# Instructions Given a moment, determine the moment that would be after a gigasecond has passed. A gigasecond is 10^9 (1,000,000,000) seconds.
From : procedure if ARG() < 1 | ARG() > 2 | ARG(1) == '' then ; return '' timeval = ARG(2) ; if ARG(2) == '' then ; timeval = '00:00:00' parse value ARG(1) 1000000000 (TIME('O') / 1000000) 0 , with dateval GIGASECOND TZOFF DAYLIGHT_SAVING_SECONDS /* Adjust for Daylight Saving Time: 3600 if DST is active else 0 */ if IsDSTActive() then ; DAYLIGHT_SAVING_SECONDS = 3600 base = DATE('T', dateval, 'I') newtime = base + TIME('S', timeval, 'N') + GIGASECOND timeoff = newtime - base - TZOFF + DAYLIGHT_SAVING_SECONDS /* YYYY-MM-DD HH:MM:SS */ return DATE('I', newtime, 'T') TIME('N', timeoff, 'T') IsDSTActive : procedure /* WARNING: UNIX / Linux specific system command */ cmd = "date -d '1 Jan' +%z ; date -d '1 Jul' +%z ; date +%z" address SYSTEM cmd with OUTPUT FIFO '' /* Assume no DST if command invocation error occurs */ if RC \= 0 then ; return 0 tzgroup = '' ; do while QUEUED() > 0 parse pull data with '+' tzoffset tzgroup ||= tzoffset || ';' end parse var tzgroup tz1 ';' tz7 ';' tznow ';' if tznow > tz1 | tznow > tz7 then ; return 1 return 0
/* Unit Test Runner: t-rexx */ context('Checking the From function') /* Test Options */ numeric digits 20 /* Unit tests */ check('date only specification of time' 'From("2011-04-25")',, 'From("2011-04-25")',, '=', '2043-01-01 01:46:40') check('second test for date only specification of time' 'From("1977-06-13")',, 'From("1977-06-13")',, '=', '2009-02-19 01:46:40') check('third test for date only specification of time' 'From("1959-07-19")',, 'From("1959-07-19")',, '=', '1991-03-27 01:46:40') check('full time specified' 'From("2015-01-24", "22:00:00")',, 'From("2015-01-24", "22:00:00")',, '=', '2046-10-02 23:46:40') check('full time with day roll-over' 'From("2015-01-24", "23:59:59")',, 'From("2015-01-24", "23:59:59")',, '=', '2046-10-03 01:46:39')
18
# Instructions Given students' names along with the grade that they are in, create a roster for the school. In the end, you should be able to: - Add a student's name to the roster for a grade - "Add Jim to grade 2." - "OK." - Get a list of all students enrolled in a grade - "Which students are in grade 2?" - "We've only got Jim just now." - Get a sorted list of all students in all grades. Grades should sort as 1, 2, 3, etc., and students within a grade should be sorted alphabetically by name. - "Who all is enrolled in school right now?" - "Let me think. We have Anna, Barb, and Charlie in grade 1, Alex, Peter, and Zoe in grade 2 and Jim in grade 5. So the answer is: Anna, Barb, Charlie, Alex, Peter, Zoe and Jim" Note that all our students only have one name (It's a small town, what do you want?) and each student cannot be added more than once to a grade or the roster. In fact, when a test attempts to add the same student more than once, your implementation should indicate that this is incorrect.
GradeSchoolCreate : procedure if ARG() < 1 then ; return 'GRADESCHOOL;0;' parse value SPACE(ARG(1)) with entries if STRIP(entries) == '' | , \GradeSchoolValidEntries(entries) then ; return 'GRADESCHOOL;0;' return 'GRADESCHOOL;' || WORDS(entries) || ';' || entries GradeSchoolValidEntries : procedure parse arg entries do while entries \= '' parse var entries student ':' grade entries if student == '' | grade == '' then ; return 0 end return 1 GradeSchoolIsEmpty : procedure if ARG() == 1 then ; return ARG(1) == 'GRADESCHOOL;0;' if ARG() == 2 then do parse arg gradeschool, target parse var gradeschool 'GRADESCHOOL;' size ';' entries do while entries \= '' parse var entries student ':' grade entries if grade == target then ; return 0 end end return 1 GradeSchoolAdd : procedure parse arg gradeschool, student, grade parse var gradeschool 'GRADESCHOOL;' size ';' entries if student == '' | grade == '' then ; return gradeschool if POS(student, entries) > 0 then ; return gradeschool newentry = STRIP(student) || ':' || STRIP(grade) return 'GRADESCHOOL;' || (size + 1) || ';' || SPACE(newentry entries) GradeSchoolList : procedure parse arg gradeschool, sortCmd, target parse var gradeschool 'GRADESCHOOL;' size ';' entries students = entries ; grades = '' do while entries \= '' parse var entries student ':' grade entries grades ||= grade || ':' || student '' end students = sortWords(students) ; grades = sortWords(grades) select when sortCmd == 'N' then entries = students when sortCmd == 'G' then entries = grades otherwise nop end output = '' ; do while entries \= '' parse var entries leftval ':' rightval entries if target \= '' & target == rightval | , target == '' then ; output ||= leftval rightval || "0A"X end return output SortWords: procedure words = ARG(1) ; parse value WORDS(words) WORD(words, 1) with n sorted if n < 2 then ; return sorted do i = 2 to n next = WORD(words, i) do j = 1 to i-1 if next < WORD(sorted, j) then do if j > 1 then ; lm = SUBWORD(sorted, 1, j-1) ; else lm = '' sorted = lm next SUBWORD(sorted, j) leave j end if j == i-1 then ; sorted = sorted next end end return STRIP(sorted) ReverseWords: procedure words = ARG(1) ; n = WORDS(words) ; revwords = '' do i = n to 1 by -1 revwords = revwords WORD(words, i) end return STRIP(revwords)
/* Unit Test Runner: t-rexx */ context('Checking the Grade School functions') /* Test Variables */ roster_empty = GradeSchoolCreate() roster_aimee_only = GradeSchoolCreate("Aimee:2") roster_harry_only = GradeSchoolCreate("Harry:2") roster_multiple_students_same_grade = GradeSchoolCreate("Harry:2 Mark:2 John:2 Bill:2") roster_multiple_students_different_grades = GradeSchoolCreate("Harry:3 Mark:5 John:9 Bill:7") roster_multiple_grades = GradeSchoolCreate("Harry:3 Mark:5 John:9 Bill:7 Sam:5 Anne:5 Jill:3") output_sorted_grades = '3 Harry' || "0A"X || '3 Jill' || "0A"X || '5 Anne' || "0A"X || '5 Mark' || "0A"X || '5 Sam' || "0A"X || '7 Bill' || "0A"X || '9 John' || "0A"X output_sorted_names = 'Anne 5' || "0A"X || 'Bill 7' || "0A"X || 'Harry 3' || "0A"X || 'Jill 3' || "0A"X || 'John 9' || "0A"X || 'Mark 5' || "0A"X || 'Sam 5' || "0A"X output_selected_grade = 'Harry 3' || "0A"X || 'Jill 3' || "0A"X roster_2 = GradeSchoolCreate() roster_3 = GradeSchoolCreate() roster_3 = GradeSchoolAdd(roster_3, "Bill", 2) roster_3 = GradeSchoolAdd(roster_3, "John", 2) roster_3 = GradeSchoolAdd(roster_3, "Mark", 2) roster_3 = GradeSchoolAdd(roster_3, "Harry", 2) roster_4 = GradeSchoolCreate() roster_4 = GradeSchoolAdd(roster_4, "Bill", 7) roster_4 = GradeSchoolAdd(roster_4, "John", 9) roster_4 = GradeSchoolAdd(roster_4, "Mark", 5) roster_4 = GradeSchoolAdd(roster_4, "Harry", 3) roster_5 = GradeSchoolCreate() roster_5 = GradeSchoolAdd(roster_5, "Harry", 2) roster_6 = GradeSchoolCreate() roster_6 = GradeSchoolAdd(roster_6, "Harry", 2) roster_6 = GradeSchoolAdd(roster_6, "Harry", 3) roster_7 = GradeSchoolCreate() roster_8 = GradeSchoolCreate() roster_8 = GradeSchoolAdd(roster_8, "Harry", 2) roster_8 = GradeSchoolAdd(roster_8, "Bob", 3) roster_9 = roster_multiple_grades /* Unit tests */ check('Roster is empty when no student is added' 'GradeSchoolCreate()',, 'GradeSchoolCreate()',, '=', roster_empty) check('Student is added to the roster' 'GradeSchoolAdd(roster_2, "Aimee", 2)',, 'GradeSchoolAdd(roster_2, "Aimee", 2)',, '=', roster_aimee_only) check('Multiple students in the same grade are added to the roster' 'GradeSchoolAdd(roster_3)',, 'GradeSchoolAdd(roster_3)',, '=', roster_multiple_students_same_grade) check('Students in multiple grades are added to the roster' 'GradeSchoolAdd(roster_4)',, 'GradeSchoolAdd(roster_4)',, '=', roster_multiple_students_different_grades) check('Cannot add student to same grade in the roster more than once' 'GradeSchoolAdd(roster_5, "Harry", 2)',, 'GradeSchoolAdd(roster_5, "Harry", 2)',, '=', roster_harry_only) check('A student cannot be in two different grades' 'GradeSchoolAdd(roster_6, "Harry", 3)',, 'GradeSchoolAdd(roster_6, "Harry", 3)',, '=', roster_harry_only) check('Grade is empty if no students in the roster' 'GradeSchoolIsEmpty(roster_7)',, 'GradeSchoolIsEmpty(roster_7)',, '=', 1) check('Grade is empty if no students in that grade' 'GradeSchoolIsEmpty(roster_8, 5)',, 'GradeSchoolIsEmpty(roster_8, 5)',, '=', 1) check('Grade is not empty if students in that grade' 'GradeSchoolIsEmpty(roster_8, 2)',, 'GradeSchoolIsEmpty(roster_8, 2)',, '=', 0) check('Students are sorted by grades in the roster' 'GradeSchoolList(roster_9, "G")',, 'GradeSchoolList(roster_9, "G")',, '=', output_sorted_grades) check('Students are sorted by name in the roster' 'GradeSchoolList(roster_9, "N")',, 'GradeSchoolList(roster_9, "N")',, '=', output_sorted_names) check('Students are sorted by name in a grade' 'GradeSchoolList(roster_9, "N", 3)',, 'GradeSchoolList(roster_9, "N", 3)',, '=', output_selected_grade)
19
# Instructions Calculate the number of grains of wheat on a chessboard given that the number on each square doubles. There once was a wise servant who saved the life of a prince. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board, with the number of grains doubling on each successive square. There are 64 squares on a chessboard (where square 1 has one grain, square 2 has two grains, and so on). Write code that shows: - how many grains were on a given square, and - the total number of grains on the chessboard
ComputeSquare : procedure parse arg n if n == 1 then ; return 1 else ; return ComputeSquare(n - 1) * 2 Square : procedure parse arg n if n < 1 | n > 64 then ; return -1 else ; return ComputeSquare(n) Total : procedure ; return Square(64) * 2 - 1
/* Unit Test Runner: t-rexx */ context('Checking the Square, and Total functions') /* Test Options */ numeric digits 20 /* Unit tests */ check('Returns the number of grains on the square' 'Square(1)',, 'Square(1)',, '=', 1) check('Returns the number of grains on the square' 'Square(2)',, 'Square(2)',, '=', 2) check('Returns the number of grains on the square' 'Square(3)',, 'Square(3)',, '=', 4) check('Returns the number of grains on the square' 'Square(4)',, 'Square(4)',, '=', 8) check('Returns the number of grains on the square' 'Square(16)',, 'Square(16)',, '=', 32768) check('Returns the number of grains on the square' 'Square(32)',, 'Square(32)',, '=', 2147483648) check('Returns the number of grains on the square' 'Square(64)',, 'Square(64)',, '=', 9223372036854775808) check('Square 0 raises an exception' 'Square(0)',, 'Square(0)',, '=', -1) check('Negative square raises an exception' 'Square(-1)',, 'Square(-1)',, '=', -1) check('Square greater than 64 raises an exception' 'Square(65)',, 'Square(65)',, '=', -1) check('Returns the total number of grains on the board' 'Total()',, 'Total()',, '=', 18446744073709551615)
20
# Instructions Calculate the Hamming Distance between two DNA strands. Your body is made up of cells that contain DNA. Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells. In fact, the average human body experiences about 10 quadrillion cell divisions in a lifetime! When cells divide, their DNA replicates too. Sometimes during this process mistakes happen and single pieces of DNA get encoded with the incorrect information. If we compare two strands of DNA and count the differences between them we can see how many mistakes occurred. This is known as the "Hamming Distance". We read DNA using the letters C,A,G and T. Two strands might look like this: GAGCCTACTAACGGGAT CATCGTAATGACGGCCT ^ ^ ^ ^ ^ ^^ They have 7 differences, and therefore the Hamming Distance is 7. The Hamming Distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :) ## Implementation notes The Hamming distance is only defined for sequences of equal length, so an attempt to calculate it between sequences of different lengths should not work.
Distance: procedure if ARG() \= 2 | LENGTH(ARG(1)) \= LENGTH(ARG(2)) then ; return -1 s1 = ARG(1) ; s2 = ARG(2) ; distance = 0 do while s1 \= '' parse var s1 nuc1 +1 s1 ; parse var s2 nuc2 +1 s2 distance += (nuc1 \= nuc2) end return distance
/* Unit Test Runner: t-rexx */ context('Checking the Distance function') /* Unit tests */ check('empty strands' 'Distance("", "")',, 'Distance("", "")',, '=', 0) check('single letter identical strands' 'Distance("A", "A")',, 'Distance("A", "A")',, '=', 0) check('single letter different strands' 'Distance("G", "T")',, 'Distance("G", "T")',, '=', 1) check('long identical strands' 'Distance("GGACTGAAATCTG", "GGACTGAAATCTG")',, 'Distance("GGACTGAAATCTG", "GGACTGAAATCTG")',, '=', 0) check('long different strands' 'Distance("GGACGGATTCTG", "AGGACGGATTCT")',, 'Distance("GGACGGATTCTG", "AGGACGGATTCT")',, '=', 9) check('disallow first strand longer' 'Distance("AATG", "AAA")',, 'Distance("AATG", "AAA")',, '=', -1) check('disallow second strand longer' 'Distance("ATA", "AGTG")',, 'Distance("ATA", "AGTG")',, '=', -1) check('disallow left empty strand' 'Distance("", "AGTG")',, 'Distance("", "AGTG")',, '=', -1) check('disallow right empty strand' 'Distance("AGTG", "")',, 'Distance("AGTG", "")',, '=', -1) check('disallow no input' 'Distance()',, 'Distance()',, '=', -1) check('expose subtle' 'Distance("A?A", "AAA")',, 'Distance("A?A", "AAA")',, '=', 1)
21
# Instructions The classical introductory exercise. Just say "Hello, World!". ["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment. The objectives are simple: - Modify the provided code so that it produces the string "Hello, World!". - Run the test suite and make sure that it succeeds. - Submit your solution and check it at the website. If everything goes well, you will be ready to fetch your first real exercise. [hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
HelloWorld : procedure return "Hello, World!"
/* Unit Test Runner: t-rexx */ context('Checking the HelloWorld function') /* Unit tests */ check('Say Hi!' 'HelloWorld()',, 'HelloWorld()',, '=', "Hello, World!")
22
# Instructions Manage a game player's High Score list. Your task is to build a high-score component of the classic Frogger game, one of the highest selling and most addictive games of all time, and a classic of the arcade era. Your task is to write methods that return the highest score from the list, the last added score and the three highest scores.
ScoresCreate : procedure parse value SPACE(ARG(1)) with scores if scores == '' | , VERIFY(CHANGESTR(' ', scores, ''), '0123456789', 'N') > 0 then return 'SCORES;' return 'SCORES;' || scores ScoresList : procedure parse value ARG(3) || ';' || ARG(2) || ';' || WORDS(ARG(1)) || ARG(1) , with sortOrder ';' required ';' words 'SCORES;' scores if words == 1 then ; return scores select when sortOrder == 'A' then scores = sortWords(scores) when sortOrder == 'D' then scores = reverseWords(sortWords(scores)) otherwise nop end if \DATATYPE(required, 'N') | required > words then ; return scores if required == 0 then ; return '' if required < 0 then ; return SUBWORD(scores, MAX(words + required + 1, 1)) return SUBWORD(scores, 1, required) ScoresGetLatest : procedure required = ARG(2) if ARG(3) \= '' then do scores = ScoresList(ARG(1)) wordpos = WORDPOS(ARG(3), scores) if required == 0 | required == '' then ; return SUBWORD(scores, wordpos + 1) return SUBWORD(scores, wordpos + 1, required) end ; else do if DATATYPE(required, 'N') & required > 0 then ; required = 0 - required if required == '' then ; required = -1 return ScoresList(ARG(1), required) end ScoresGetPersonalBest : procedure required = ARG(2) ; sortOrder = ARG(3) if required == '' then ; required = -1 if sortOrder == '' then do sortOrder = 'A' if required > 0 then ; required = 0 - required end return ScoresList(ARG(1), required, sortOrder) SortWords: procedure words = ARG(1) ; parse value WORDS(words) WORD(words, 1) with n sorted if n < 2 then ; return sorted do i = 2 to n next = WORD(words, i) do j = 1 to i-1 if next < WORD(sorted, j) then do if j > 1 then ; lm = SUBWORD(sorted, 1, j-1) ; else lm = '' sorted = lm next SUBWORD(sorted, j) leave j end if j == i-1 then ; sorted = sorted next end end return STRIP(sorted) ReverseWords: procedure words = ARG(1) ; n = WORDS(words) ; revwords = '' do i = n to 1 by -1 revwords = revwords WORD(words, i) end return STRIP(revwords)
/* Unit Test Runner: t-rexx */ context('Checking the High Scores functions') /* Test Variables */ scores = ScoresCreate("10 30 90 30 100 20 10 0 30 40 40 40 70 70") scores_list = "10 30 90 30 100 20 10 0 30 40 40 40 70 70" scores_less_than_three = ScoresCreate("40 60") scores_only_one = ScoresCreate("40") /* Unit tests */ check('List of scores' 'ScoresList(scores)',, 'ScoresList(scores)',, '=', scores_list) check('Latest score' 'ScoresGetLatest(scores)',, 'ScoresGetLatest(scores)',, '=', 70) check('Personal best' 'ScoresGetPersonalBest(scores)',, 'ScoresGetPersonalBest(scores)',, '=', 100) check('Top 3 scores -> Personal top three from a list of scores' 'ScoresGetPersonalBest(scores, 3)',, 'ScoresGetPersonalBest(scores, 3)',, '=', "70 90 100") check('Top 3 scores -> Personal top highest to lowest' 'ScoresGetPersonalBest(scores, 3, "D")',, 'ScoresGetPersonalBest(scores, 3, "D")',, '=', "100 90 70") check('Top 3 scores -> Personal top when there is a tie' 'ScoresGetPersonalBest(scores, 3)',, 'ScoresGetPersonalBest(scores, 3)',, '=', "70 90 100") check('Top 3 scores -> Personal top when there are less than 3' 'ScoresGetPersonalBest(scores_less_than_three, 3)',, 'ScoresGetPersonalBest(scores_less_than_three, 3)',, '=', "40 60") check('Top 3 scores -> Personal top when there is only one' 'ScoresGetPersonalBest(scores_only_one, 3)',, 'ScoresGetPersonalBest(scores_only_one, 3)',, '=', "40") check('Top 3 scores -> Latest score after personal best' 'ScoresGetLatest(scores, 1, 100)',, 'ScoresGetLatest(scores, 1, 100)',, '=', "20") check('Top 3 scores -> Scores after personal best' 'ScoresGetLatest(scores, 0, 100)',, 'ScoresGetLatest(scores, 0, 100)',, '=', "20 10 0 30 40 40 40 70 70")
23
# Instructions Recite the nursery rhyme 'This is the House that Jack Built'. > [The] process of placing a phrase of clause within another phrase of clause is called embedding. > It is through the processes of recursion and embedding that we are able to take a finite number of forms (words and phrases) and construct an infinite number of expressions. > Furthermore, embedding also allows us to construct an infinitely long structure, in theory anyway. - [papyr.com][papyr] The nursery rhyme reads as follows: ```text This is the house that Jack built. This is the malt that lay in the house that Jack built. This is the rat that ate the malt that lay in the house that Jack built. This is the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the farmer sowing his corn that kept the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. This is the horse and the hound and the horn that belonged to the farmer sowing his corn that kept the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built. ``` [papyr]: https://papyr.com/hypertextbooks/grammar/ph_noun.htm
Recite : procedure parse arg from, to if to == '' then ; to = from parse value DATATYPE(from, 'N') DATATYPE(to, 'N') , with isFromNumeric isToNumeric if \isFromNumeric | from < 1 | from > 12 then ; return '' if \isFromNumeric | to < 1 | to > 12 then ; return '' if from > to then ; return '' if from == to then ; return VersesFrom(from) versesRecited = '' ; stop = to do n = from to stop ; versesRecited ||= VersesFrom(n) || "0A"X ; end return versesRecited VersesFrom : procedure parse value GetNouns() with records nounLength ';' nouns parse value GetVerbs() with . verbLength ';' verbs parse value (records - (ARG(1) - 2)) '' with nth embedded if nth > 1 then do nouns = SUBSTR(nouns, nounLength * nth - (nounLength - 1)) verbs = SUBSTR(verbs, verbLength * nth - (verbLength - 1)) do while nouns \= '' parse var nouns noun +(nounLength) nouns parse var verbs verb +(verbLength) verbs embedded ||= STRIP(noun) STRIP(verb) '' end end return SPACE('This is' embedded 'the house that Jack built.') || "0A"X GetNouns : return , '12 36;' || , '------------------------------------' || , 'the horse and the hound and the horn' || , 'the farmer sowing his corn ' || , 'the rooster that crowed in the morn ' || , 'the priest all shaven and shorn ' || , 'the man all tattered and torn ' || , 'the maiden all forlorn ' || , 'the cow with the crumpled horn ' || , 'the dog ' || , 'the cat ' || , 'the rat ' || , 'the malt ' GetVerbs : return , '12 16;' || , '----------------' || , 'that belonged to' || , 'that kept ' || , 'that woke ' || , 'that married ' || , 'that kissed ' || , 'that milked ' || , 'that tossed ' || , 'that worried ' || , 'that killed ' || , 'that ate ' || , 'that lay in '
/* Unit Test Runner: t-rexx */ context('Checking the Recite function') /* Test Variables */ verse_1 = , 'This is the house that Jack built.' || "0A"X verse_2 = , 'This is the malt that lay in the house that Jack built.' || "0A"X verse_3 = , 'This is the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_4 = , 'This is the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_5 = , 'This is the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_6 = , 'This is the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_7 = , 'This is the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_8 = , 'This is the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_9 = , 'This is the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_10 = , 'This is the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_11 = , 'This is the farmer sowing his corn that kept the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verse_12 = , 'This is the horse and the hound and the horn that belonged to the farmer sowing his corn that kept the rooster that crowed in the morn that woke the priest all shaven and shorn that married the man all tattered and torn that kissed the maiden all forlorn that milked the cow with the crumpled horn that tossed the dog that worried the cat that killed the rat that ate the malt that lay in the house that Jack built.' || "0A"X verses_4_to_8 = , verse_4 || "0A"X || verse_5 || "0A"X || verse_6 || "0A"X || verse_7 || "0A"X || verse_8 || "0A"X verses_1_to_12_length = 2348 /* Unit tests */ check('verse one - the house that jack built' 'Recite(1)',, 'Recite(1)',, '=', verse_1) check('verse two - the malt that lay' 'Recite(2)',, 'Recite(2)',, '=', verse_2) check('verse three - the rat that ate' 'Recite(3)',, 'Recite(3)',, '=', verse_3) check('verse four - the cat that killed' 'Recite(4)',, 'Recite(4)',, '=', verse_4) check('verse five - the dog that worried' 'Recite(5)',, 'Recite(5)',, '=', verse_5) check('verse six - the cow with the crumpled horn' 'Recite(6)',, 'Recite(6)',, '=', verse_6) check('verse seven - the maiden all forlorn' 'Recite(7)',, 'Recite(7)',, '=', verse_7) check('verse eight - the man all tattered and torn' 'Recite(8)',, 'Recite(8)',, '=', verse_8) check('verse nine - the priest all shaven and shorn' 'Recite(9)',, 'Recite(9)',, '=', verse_9) check('verse 10 - the rooster that crowed in the morn' 'Recite(10)',, 'Recite(10)',, '=', verse_10) check('verse 11 - the farmer sowing his corn' 'Recite(11)',, 'Recite(11)',, '=', verse_11) check('verse 12 - the horse and the hound and the horn' 'Recite(12)',, 'Recite(12)',, '=', verse_12) check('multiple verses' 'Recite(4, 8)',, 'Recite(4, 8)',, '=', verses_4_to_8) cmd = 'actual = Recite(1, 12)' ; interpret cmd check('full rhyme' 'Recite(1, 12)',, 'Recite(1, 12)', LENGTH(actual), '=', verses_1_to_12_length) check('invalid verse 1' 'Recite(0, 12)',, 'Recite(0, 12)',, '=', '') check('invalid verse 2' 'Recite(1, -1)',, 'Recite(1, -1)',, '=', '') check('invalid verse 3' 'Recite(14, 12)',, 'Recite(14, 12)',, '=', '') check('invalid verse 4' 'Recite(1, 13)',, 'Recite(1, 13)',, '=', '')
24
# Instructions The [ISBN-10 verification process][isbn-verification] is used to validate book identification numbers. These normally contain dashes and look like: `3-598-21508-8` ## ISBN The ISBN-10 format is 9 digits (0 to 9) plus one check character (either a digit or an X only). In the case the check character is an X, this represents the value '10'. These may be communicated with or without hyphens, and can be checked for their validity by the following formula: ```text (d₁ * 10 + d₂ * 9 + d₃ * 8 + d₄ * 7 + d₅ * 6 + d₆ * 5 + d₇ * 4 + d₈ * 3 + d₉ * 2 + d₁₀ * 1) mod 11 == 0 ``` If the result is 0, then it is a valid ISBN-10, otherwise it is invalid. ## Example Let's take the ISBN-10 `3-598-21508-8`. We plug it in to the formula, and get: ```text (3 * 10 + 5 * 9 + 9 * 8 + 8 * 7 + 2 * 6 + 1 * 5 + 5 * 4 + 0 * 3 + 8 * 2 + 8 * 1) mod 11 == 0 ``` Since the result is 0, this proves that our ISBN is valid. ## Task Given a string the program should check if the provided string is a valid ISBN-10. Putting this into place requires some thinking about preprocessing/parsing of the string prior to calculating the check digit for the ISBN. The program should be able to verify ISBN-10 both with and without separating dashes. ## Caveats Converting from strings to numbers can be tricky in certain languages. Now, it's even trickier since the check digit of an ISBN-10 may be 'X' (representing '10'). For instance `3-598-21507-X` is a valid ISBN-10. [isbn-verification]: https://en.wikipedia.org/wiki/International_Standard_Book_Number
IsValid : procedure parse value SPACE(ARG(1)) with input if LENGTH(input) < 10 then ; return 0 if VERIFY(input, 'X-0123456789', 'N') > 0 then ; return 0 isbn = CHANGESTR('-', input, '') ; isbnlen = LENGTH(isbn) if isbnlen \= 10 then ; return 0 hasXChar = COUNTSTR('X', isbn) > 0 if hasXChar & POS('X', isbn) < isbnlen ; then ; return 0 checksum = SUBSTR(isbn, isbnlen, 1) ; if hasXChar then ; checksum = 10 isbn = DELSTR(isbn, isbnlen, 1) do i = 1 to 9 ; checksum += SUBSTR(isbn, i, 1) * (11 - i) ; end return checksum // 11 == 0
/* Unit Test Runner: t-rexx */ context('Checking the IsValid function') /* Unit tests */ check('valid isbn number' 'IsValid("3-598-21508-8")',, 'IsValid("3-598-21508-8")',, '=', 1) check('invalid isbn check digit' 'IsValid("3-598-21508-9")',, 'IsValid("3-598-21508-9")',, '=', 0) check('valid isbn number with a check digit of 10' 'IsValid("3-598-21507-X")',, 'IsValid("3-598-21507-X")',, '=', 1) check('check digit is a character other than x' 'IsValid("3-598-21507-A")',, 'IsValid("3-598-21507-A")',, '=', 0) check('invalid character in isbn' 'IsValid("3-598-P1581-X")',, 'IsValid("3-598-P1581-X")',, '=', 0) check('x is only valid as a check digit' 'IsValid("3-598-2X507-9")',, 'IsValid("3-598-2X507-9")',, '=', 0) check('valid isbn without separating dashes' 'IsValid("3598215088")',, 'IsValid("3598215088")',, '=', 1) check('isbn without separating dashes and x as check digit' 'IsValid("359821507X")',, 'IsValid("359821507X")',, '=', 1) check('isbn without check digit and dashes' 'IsValid("359821507")',, 'IsValid("359821507")',, '=', 0) check('too long isbn and no dashes' 'IsValid("3598215078X")',, 'IsValid("3598215078X")',, '=', 0) check('too short isbn' 'IsValid("00")',, 'IsValid("00")',, '=', 0) check('isbn without check digit' 'IsValid("3-598-21507")',, 'IsValid("3-598-21507")',, '=', 0) check('check digit of x should not be used for 0' 'IsValid("3-598-21515-X")',, 'IsValid("3-598-21515-X")',, '=', 0) check('empty isbn' 'IsValid("")',, 'IsValid("")',, '=', 0) check('input is 9 characters' 'IsValid("134456729")',, 'IsValid("134456729")',, '=', 0) check('invalid characters are not ignored' 'IsValid("3132P34035")',, 'IsValid("3132P34035")',, '=', 0) check('input is too long but contains a valid isbn' 'IsValid("98245726788")',, 'IsValid("98245726788")',, '=', 0)
25
# Instructions Determine if a word or phrase is an isogram. An isogram (also known as a "non-pattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times. Examples of isograms: - lumberjacks - background - downstream - six-year-old The word *isograms*, however, is not an isogram, because the s repeats.
IsIsogram : procedure if ARG() \= 1 then ; return 0 if ARG(1) == '' then ; return 1 /* Remove all non-letters, even spaces */ NON_LETTERS = ' ~`!@#$%^&*()_-+=<,>.?/:;"''0123456789' candidate = CHANGESTR(';',, TRANSLATE(UPPER(ARG(1)),, NON_LETTERS, ';'),, '') /* Setup letter frequency table (integer indexes) */ isogram.0 = 26 ; do i = 1 to isogram.0 by 1 ; isogram.i = 0 ; end /* Parse input, count up letter occurrences */ do while candidate \= '' parse var candidate letter +1 candidate /* Compute table index mapping to letter. Note, 64 is C2D('A') - 1 */ i = C2D(letter) - 64 ; isogram.i += 1 /* Bail if any letter occurs more than once */ if isogram.i > 1 then ; return 0 end return 1
/* Unit Test Runner: t-rexx */ context('Checking the IsIsogram function') /* Unit tests */ check('empty string' 'IsIsogram("")',, 'IsIsogram("")',, '=', 1) check('isogram with only lower case characters' 'IsIsogram("isogram")',, 'IsIsogram("isogram")',, '=', 1) check('word with one duplicated character' 'IsIsogram("eleven")',, 'IsIsogram("eleven")',, '=', 0) check('word with one duplicated character from the end of the alphabet' 'IsIsogram("zzyzx")',, 'IsIsogram("zzyzx")',, '=', 0) check('longest reported english isogram' 'IsIsogram("subdermatoglyphic")',, 'IsIsogram("subdermatoglyphic")',, '=', 1) check('word with duplicated character in mixed case' 'IsIsogram("Alphabet")',, 'IsIsogram("Alphabet")',, '=', 0) check('word with duplicated character in mixed case, lowercase first' 'IsIsogram("alphAbet")',, 'IsIsogram("alphAbet")',, '=', 0) check('hypothetical isogrammic word with hyphen' 'IsIsogram("thumbscrew-japingly")',, 'IsIsogram("thumbscrew-japingly")',, '=', 1) check('hypothetical word with duplicated character following hyphen' 'IsIsogram("thumbscrew-jappingly")',, 'IsIsogram("thumbscrew-jappingly")',, '=', 0) check('isogram with duplicated hyphen' 'IsIsogram("six-year-old")',, 'IsIsogram("six-year-old")',, '=', 1) check('made-up name that is an isogram' 'IsIsogram("Emily Jung Schwartzkopf")',, 'IsIsogram("Emily Jung Schwartzkopf")',, '=', 1) check('duplicated character in the middle' 'IsIsogram("accentor")',, 'IsIsogram("accentor")',, '=', 0) check('same first and last characters' 'IsIsogram("angola")',, 'IsIsogram("angola")',, '=', 0) check('word with duplicated character and with two hyphens' 'IsIsogram("nine-nine-four")',, 'IsIsogram("nine-nine-four")',, '=', 0)
26
# Instructions Your task is to determine whether a given year is a leap year.
IsLeapYear : procedure parse arg year return year // 400 == 0 | year // 4 == 0 & year // 100 \== 0
/* Unit Test Runner: t-rexx */ context('Checking the IsLeapYear function') /* Unit tests */ check('year not divisible by 4 in common year' 'IsLeapYear(2015)',, 'IsLeapYear(2015)',, '=', 0) check('year divisible by 2, not divisible by 4 in common year' 'IsLeapYear(1970)',, 'IsLeapYear(1970)',, '=', 0) check('year divisible by 4, not divisible by 100 in leap year' 'IsLeapYear(1996)',, 'IsLeapYear(1996)',, '=', 1) check('year divisible by 4 and 5 is still a leap year' 'IsLeapYear(1960)',, 'IsLeapYear(1960)',, '=', 1) check('year divisible by 100, not divisible by 400 in common year' 'IsLeapYear(2100)',, 'IsLeapYear(2100)',, '=', 0) check('year divisible by 100 but not by 3 is still not a leap year' 'IsLeapYear(1900)',, 'IsLeapYear(1900)',, '=', 0) check('year divisible by 400 is leap year' 'IsLeapYear(2000)',, 'IsLeapYear(2000)',, '=', 1) check('year divisible by 400 but not by 125 is still a leap year' 'IsLeapYear(2400)',, 'IsLeapYear(2400)',, '=', 1) check('year divisible by 200, not divisible by 400 in common year' 'IsLeapYear(1800)',, 'IsLeapYear(1800)',, '=', 0)
27
# Instructions Implement basic list operations. In functional languages list operations like `length`, `map`, and `reduce` are very common. Implement a series of basic list operations, without using existing functions. The precise number and names of the operations to be implemented will be track dependent to avoid conflicts with existing names, but the general operations you will implement include: - `append` (*given two lists, add all items in the second list to the end of the first list*); - `concatenate` (*given a series of lists, combine all items in all lists into one flattened list*); - `filter` (*given a predicate and a list, return the list of all items for which `predicate(item)` is True*); - `length` (*given a list, return the total number of items within it*); - `map` (*given a function and a list, return the list of the results of applying `function(item)` on all items*); - `foldl` (*given a function, a list, and initial accumulator, fold (reduce) each item into the accumulator from the left using `function(accumulator, item)`*); - `foldr` (*given a function, a list, and an initial accumulator, fold (reduce) each item into the accumulator from the right using `function(item, accumulator)`*); - `reverse` (*given a list, return a list with all the original items, but in reversed order*);
Append : ; return SPACE(ARG(1) ARG(2)) ListLength : ; return WORDS(ARG(1)) Head : ; return WORD(ARG(1), 1) Tail : ; return DELWORD(ARG(1), 1, 1) Filter : procedure parse arg input, function output = '' ; do while input \= '' parse var input token input cmd = 'isTrue =' function || "(token)" ; interpret cmd if isTrue then ; output ||= token '' end return SPACE(output) Map : procedure parse arg input, function output = '' ; do while input \= '' parse var input token input cmd = 'retval =' function || "(token)" ; interpret cmd output ||= retval '' end return SPACE(output) FoldL : procedure parse arg input, function, redux if input == '' then ; return SPACE(redux) parse var input head tail cmd = 'redux =' function || "(head, redux)" ; interpret cmd return FoldL(tail, function, redux) FoldR : procedure parse arg input, function, redux return FoldL(ListReverse(input), function, redux) ListReverse : procedure parse arg input output = '' ; do while input \= '' parse var input elem input output = elem output end return SPACE(output)
/* Unit Test Runner: t-rexx */ context('Checking the List-Ops functions') /* Unit tests */ check('append entries to a list and return the new list -> empty lists' 'Append("", "")',, 'Append("", "")',, '=', '') check('append entries to a list and return the new list -> list to empty list' 'Append("", "1 2 3 4")',, 'Append("", "1 2 3 4")',, '=', '1 2 3 4') check('append entries to a list and return the new list -> empty list to list' 'Append("1 2 3 4", "")',, 'Append("1 2 3 4", "")',, '=', '1 2 3 4') check('append entries to a list and return the new list -> non-empty lists' 'Append("1 2 3 4", "5 6 7 8")',, 'Append("1 2 3 4", "5 6 7 8")',, '=', '1 2 3 4 5 6 7 8') check('filter list returning only values that satisfy the filter function -> empty list' 'Filter("", "IsEven")',, 'Filter("", "IsEven")',, '=', '') check('filter list returning only values that satisfy the filter function -> non-empty list' 'Filter("1 2 3 4", "IsEven")',, 'Filter("1 2 3 4", "IsEven")',, '=', '2 4') check('returns the length of a list -> empty list' 'ListLength("")',, 'ListLength("")',, '=', 0) check('returns the length of a list -> non-empty list' 'ListLength("1 2 3 4")',, 'ListLength("1 2 3 4")',, '=', 4) check('return a list of elements whose values equal the list value transformed by the mapping function -> empty list' 'Map("", "Add1")',, 'Map("", "Add1")',, '=', '') check('return a list of elements whose values equal the list value transformed by the mapping function -> non-empty list' 'Map("1 2 3 4", "Add1")',, 'Map("1 2 3 4", "Add1")',, '=', '2 3 4 5') check('folds (reduces) the given list from the left with a function -> empty list' 'FoldL("", "Multiply", 1)',, 'FoldL("", "Multiply", 1)',, '=', 1) check('folds (reduces) the given list from the left with a function -> direction independent function applied to non-empty list' 'FoldL("1 2 3 4", "Multiply", 1)',, 'FoldL("1 2 3 4", "Multiply", 1)',, '=', 24) check('folds (reduces) the given list from the left with a function -> direction dependent function applied to non-empty list' 'FoldL("1 2 3 4", "IntegerDivide", 1)',, 'FoldL("4 2 5 5", "IntegerDivide", 200)',, '=', 1) check('folds (reduces) the given list from the left with a function -> empty list' 'FoldL("", "Concatenate", "")',, 'FoldL("", "Concatenate", "")',, '=', '') check('folds (reduces) the given list from the left with a function -> direction dependent function applied to non-empty list' 'FoldL("A B C D", "Concatenate", "")',, 'FoldL("A B C D", "Concatenate", "")',, '=', 'A B C D') check('folds (reduces) the given list from the right with a function -> empty list' 'FoldR("", "Multiply", 1)',, 'FoldR("", "Multiply", 1)',, '=', 1) check('folds (reduces) the given list from the right with a function -> direction independent function applied to non-empty list' 'FoldR("1 2 3 4", "Multiply", 1)',, 'FoldR("1 2 3 4", "Multiply", 1)',, '=', 24) check('folds (reduces) the given list from the right with a function -> direction dependent function applied to non-empty list' 'FoldR("1 2 3 4", "IntegerDivide", 1)',, 'FoldR("5 5 2 4", "IntegerDivide", 200)',, '=', 1) check('folds (reduces) the given list from the right with a function -> empty list' 'FoldR("", "Concatenate", "")',, 'FoldR("", "Concatenate", "")',, '=', '') check('folds (reduces) the given list from the right with a function -> direction dependent function applied to non-empty list' 'FoldR("A B C D", "Concatenate", "")',, 'FoldR("A B C D", "Concatenate", "")',, '=', 'D C B A') check('reverse the elements of the list -> empty list' 'ListReverse("")',, 'ListReverse("")',, '=', '') check('reverse the elements of the list -> non-empty list' 'ListReverse("1 2 3 4 5")',, 'ListReverse("1 2 3 4 5")',, '=', '5 4 3 2 1')
28
# Instructions Given a number determine whether or not it is valid per the Luhn formula. The [Luhn algorithm][luhn] is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers. The task is to check if a given string is valid. ## Validating a Number Strings of length 1 or less are not valid. Spaces are allowed in the input, but they should be stripped before checking. All other non-digit characters are disallowed. ### Example 1: valid credit card number ```text 4539 3195 0343 6467 ``` The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling ```text 4_3_ 3_9_ 0_4_ 6_6_ ``` If doubling the number results in a number greater than 9 then subtract 9 from the product. The results of our doubling: ```text 8569 6195 0383 3437 ``` Then sum all of the digits: ```text 8+5+6+9+6+1+9+5+0+3+8+3+3+4+3+7 = 80 ``` If the sum is evenly divisible by 10, then the number is valid. This number is valid! ### Example 2: invalid credit card number ```text 8273 1232 7352 0569 ``` Double the second digits, starting from the right ```text 7253 2262 5312 0539 ``` Sum the digits ```text 7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57 ``` 57 is not evenly divisible by 10, so this number is not valid. [luhn]: https://en.wikipedia.org/wiki/Luhn_algorithm
IsValid : procedure parse value CHANGESTR(' ', ARG(1), '') with input if VERIFY(input, '0123456789', 'N') > 0 then ; return 0 if SUBSTR(input, 1, 1) == '0' then ; input = DELSTR(input, 1, 1) if input == '' then ; return 0 parse value LENGTH(input) (LENGTH(input) // 2 \= 0) 0 , with inputlen parity sum do i = 1 to inputlen digit = SUBSTR(input, i, 1) if (i-1) // 2 == parity then do digit *= 2 ; if digit > 9 then ; digit = digit - 9 end sum += digit end return sum // 10 == 0
/* Unit Test Runner: t-rexx */ context('Checking the IsValid function') /* Unit tests */ check('single digit strings can not be valid test' 'IsValid("1")',, 'IsValid("1")',, '=', 0) check('a single zero is invalid test' 'IsValid("0")',, 'IsValid("0")',, '=', 0) check('a simple valid sin that remains valid if reversed test' 'IsValid("059")',, 'IsValid("059")',, '=', 1) check('a simple valid sin that becomes invalid if reversed test' 'IsValid("59")',, 'IsValid("59")',, '=', 1) check('a valid canadian sin test' 'IsValid("055 444 285")',, 'IsValid("055 444 285")',, '=', 1) check('invalid canadian sin test' 'IsValid("055 444 286")',, 'IsValid("055 444 286")',, '=', 0) check('invalid credit card test' 'IsValid("8273 1232 7352 0569")',, 'IsValid("8273 1232 7352 0569")',, '=', 0) check('valid number with an even number of digits test' 'IsValid("095 245 88")',, 'IsValid("095 245 88")',, '=', 1) check('valid strings with a non digit included become invalid test' 'IsValid("055a 444 285")',, 'IsValid("055a 444 285")',, '=', 0) check('valid strings with punctuation included become invalid test' 'IsValid("055-444-285")',, 'IsValid("055-444-285")',, '=', 0) check('valid strings with symbols included become invalid test' 'IsValid("055 444$ 285")',, 'IsValid("055 444$ 285")',, '=', 0) check('single zero with space is invalid test' 'IsValid(" 0")',, 'IsValid(" 0")',, '=', 0) check('more than a single zero is valid test' 'IsValid("0000 0")',, 'IsValid("0000 0")',, '=', 1) check('input digit 9 is correctly converted to output digit 9 test' 'IsValid("091")',, 'IsValid("091")',, '=', 1) check('very long input is valid test' 'IsValid("9999999999 9999999999 9999999999 9999999999")',, 'IsValid("9999999999 9999999999 9999999999 9999999999")',, '=', 1) check('valid luhn with an odd number of digits and non zero first digit test' 'IsValid("109")',, 'IsValid("109")',, '=', 1) check('strings with non digits is invalid test' 'IsValid(":9")',, 'IsValid(":9")',, '=', 0)
29
# Instructions Given a string containing brackets `[]`, braces `{}`, parentheses `()`, or any combination thereof, verify that any and all pairs are matched and nested correctly. The string may also contain other characters, which for the purposes of this exercise should be ignored.
IsBalanced : procedure parse arg input stk = '' ; do while input \= '' parse var input c +1 input select when c == '[' then ; stk ||= ']' when c == '(' then ; stk ||= ')' when c == '{' then ; stk ||= '}' when VERIFY(c, '])}', 'M') > 0 then do if stk == '' then ; return 0 if c \= SUBSTR(stk, LENGTH(stk), 1) then ; return 0 stk = DELSTR(stk, LENGTH(stk), 1) end otherwise nop end end return stk == ''
/* Unit Test Runner: t-rexx */ context('Checking the IsBalanced function') /* Unit tests */ check("paired square brackets" 'IsBalanced("[]")',, 'IsBalanced("[]")',, '=', 1) check("empty string" 'IsBalanced("")',, 'IsBalanced("")',, '=', 1) check("unpaired brackets" 'IsBalanced("[[")',, 'IsBalanced("[[")',, '=', 0) check("wrong ordered brackets" 'IsBalanced("}{")',, 'IsBalanced("}{")',, '=', 0) check("wrong closing bracket" 'IsBalanced("{]")',, 'IsBalanced("{]")',, '=', 0) check("paired with whitespace" 'IsBalanced("{ }")',, 'IsBalanced("{ }")',, '=', 1) check("partially paired brackets" 'IsBalanced("{[])")',, 'IsBalanced("{[])")',, '=', 0) check("simple nested brackets" 'IsBalanced("{[]}")',, 'IsBalanced("{[]}")',, '=', 1) check("several paired brackets" 'IsBalanced("{}[]")',, 'IsBalanced("{}[]")',, '=', 1) check("paired and nested brackets" 'IsBalanced("([{}({}[])])")',, 'IsBalanced("([{}({}[])])")',, '=', 1) check("unopened closing brackets" 'IsBalanced("{[)][]}")',, 'IsBalanced("{[)][]}")',, '=', 0) check("unpaired and nested brackets" 'IsBalanced("([{])")',, 'IsBalanced("([{])")',, '=', 0) check("paired and wrong nested brackets" 'IsBalanced("[({]})")',, 'IsBalanced("[({]})")',, '=', 0) check("paired and incomplete brackets" 'IsBalanced("{}[")',, 'IsBalanced("{}[")',, '=', 0) check("math expression" 'IsBalanced("(((185 + 223.85) * 15) - 543)/2")',, 'IsBalanced("(((185 + 223.85) * 15) - 543)/2")',, '=', 1) check("complex latex expression" 'IsBalanced("\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)")',, 'IsBalanced("\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)")',, '=', 1)
30
# Instructions Given a string representing a matrix of numbers, return the rows and columns of that matrix. So given a string with embedded newlines like: ```text 9 8 7 5 3 2 6 6 7 ``` representing this matrix: ```text 1 2 3 |--------- 1 | 9 8 7 2 | 5 3 2 3 | 6 6 7 ``` your code should be able to spit out: - A list of the rows, reading each row left-to-right while moving top-to-bottom across the rows, - A list of the columns, reading each column top-to-bottom while moving from left-to-right. The rows for our example matrix: - 9, 8, 7 - 5, 3, 2 - 6, 6, 7 And its columns: - 9, 5, 6 - 8, 3, 6 - 7, 2, 7
MatrixCreate : procedure if ARG(1) == '' then ; return 'MATRIX;1;1;0' SEP = ',' ; parse arg matdata select when POS('\n', matdata) > 0 then datasep = '\n' when POS("0A"X, matdata) > 0 then datasep = "0A"X when POS(SEP, matdata) > 0 then datasep = SEP otherwise return 'MATRIX;1;1;' || STRIP(matdata) end rows = COUNTSTR(datasep, matdata) + 1 matdata = CHANGESTR(datasep, matdata, SEP) cols = WORDS(SUBSTR(matdata, 1, POS(SEP, matdata) - 1)) return 'MATRIX;' || rows || ';' || cols || ';' || SPACE(matdata) MatrixRow : procedure parse arg matrix, target parse var matrix 'MATRIX;' rows ';' cols ';' data if DATATYPE(target, 'N') then do if target < 1 then ; target = 1 if target > rows then ; target = rows do r = 1 to rows parse var data row ',' data if target == r then ; return SPACE(row) end end return '' MatrixCol : procedure parse arg matrix, target parse var matrix 'MATRIX;' rows ';' cols ';' data if DATATYPE(target, 'N') then do if target < 1 then ; target = 1 if target > cols then ; target = cols col = '' ; do r = 1 to rows parse var data row ',' data col ||= WORD(row, target) '' end return SPACE(col) end return ''
/* Unit Test Runner: t-rexx */ context('Checking the Matrix functions') /* Test Variables */ matrix_1x1 = MatrixCreate("7") matrix_3x3 = MatrixCreate("3 8 4\n11 7 18\n6 1 4") matrix_3x3_0AX_sep = MatrixCreate("3 8 4" || "0A"X || "11 7 18" || "0A"X || "6 1 4") matrix_3x3_comma_sep = MatrixCreate("3 8 4,11 7 18,6 1 4") matrix_4x3 = MatrixCreate("3 8 4\n11 7 18\n6 1 4\n5 1 4") matrix_3x4 = MatrixCreate("3 8 4 11\n7 18 6 1\n4 5 1 4") /* Unit tests */ check('create 3 x 3 matrix (\n separator)' 'MatrixCreate("3 8 4\n11 7 18\n6 1 4")',, 'MatrixCreate("3 8 4\n11 7 18\n6 1 4")',, '=', matrix_3x3) check('create 3 x 3 matrix (0AX separator)' 'MatrixCreate("3 8 4" || "0A"X || "11 7 18" || "0A"X || "6 1 4")',, 'MatrixCreate("3 8 4" || "0A"X || "11 7 18" || "0A"X || "6 1 4")',, '=', matrix_3x3_0AX_sep) check('create 3 x 3 matrix (, separator)' 'MatrixCreate("3 8 4,11 7 18,6 1 4")',, 'MatrixCreate("3 8 4,11 7 18,6 1 4")',, '=', matrix_3x3_comma_sep) check('extract row from one number matrix' 'MatrixRow(matrix_1x1, 1)',, 'MatrixRow(matrix_1x1, 1)',, '=', '7') check('can extract row' 'MatrixRow(matrix_3x3, 1)',, 'MatrixRow(matrix_3x3, 1)',, '=', '3 8 4') check('extract row where numbers have different widths' 'MatrixRow(matrix_3x3, 2)',, 'MatrixRow(matrix_3x3, 2)',, '=', '11 7 18') check('can extract row from non-square matrix with no corresponding column' 'MatrixRow(matrix_4x3, 4)',, 'MatrixRow(matrix_4x3, 4)',, '=', '5 1 4') check('extract column from one number matrix' 'MatrixCol(matrix_1x1, 1)',, 'MatrixCol(matrix_1x1, 1)',, '=', '7') check('can extract column' 'MatrixCol(matrix_3x3, 2)',, 'MatrixCol(matrix_3x3, 2)',, '=', '8 7 1') check('extract column where numbers have different widths' 'MatrixCol(matrix_3x3, 1)',, 'MatrixCol(matrix_3x3, 1)',, '=', '3 11 6') check('can extract column from non-square matrix with no corresponding column' 'MatrixCol(matrix_3x4, 4)',, 'MatrixCol(matrix_3x4, 4)',, '=', '11 1 4')
31
# Instructions Given a number n, determine what the nth prime is. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.
NthPrime : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) < 1 then ; return -1 parse value ARG(1) 0 2 with nthIdx currIdx candidate if nthIdx == 1 then ; return 2 do while currIdx < nthIdx prime = 1 ; j = 2 ; do while (j * j) <= candidate if candidate // j == 0 then do prime = 0 ; leave end j += 1 end if prime then ; currIdx += 1 candidate += 1 end return candidate - 1
/* Unit Test Runner: t-rexx */ context('Checking the NthPrime function') /* Test Options */ numeric digits 6 /* Unit tests */ check('first prime' 'NthPrime(1)',, 'NthPrime(1)',, '=', 2) check('second prime' 'NthPrime(2)',, 'NthPrime(2)',, '=', 3) check('sixth prime' 'NthPrime(6)',, 'NthPrime(6)',, '=', 13) check('big prime' 'NthPrime(10001)',, 'NthPrime(10001)',, '=', 104743) check('there is no zeroth prime' 'NthPrime(0)',, 'NthPrime(0)',, '=', -1)
32
# Instructions Each of us inherits from our biological parents a set of chemical instructions known as DNA that influence how our bodies are constructed. All known life depends on DNA! > Note: You do not need to understand anything about nucleotides or DNA to complete this exercise. DNA is a long chain of other chemicals and the most important are the four nucleotides, adenine, cytosine, guanine and thymine. A single DNA chain can contain billions of these four nucleotides and the order in which they occur is important! We call the order of these nucleotides in a bit of DNA a "DNA sequence". We represent a DNA sequence as an ordered collection of these four nucleotides and a common way to do that is with a string of characters such as "ATTACG" for a DNA sequence of 6 nucleotides. 'A' for adenine, 'C' for cytosine, 'G' for guanine, and 'T' for thymine. Given a string representing a DNA sequence, count how many of each nucleotide is present. If the string contains characters that aren't A, C, G, or T then it is invalid and you should signal an error. For example: ```text "GATTACA" -> 'A': 3, 'C': 1, 'G': 1, 'T': 2 "INVALID" -> error ```
Count : procedure if ARG() \= 1 | (VERIFY(ARG(1), 'ACGT') \= 0) then ; return '' counts.A = 0 ; counts.C = 0 ; counts.G = 0 ; counts.T = 0 parse arg sequence do while sequence \= '' parse var sequence nucleotide +1 sequence counts.nucleotide += 1 end return 'A:' || counts.A 'C:' || counts.C 'G:' || counts.G 'T:' || counts.T
/* Unit Test Runner: t-rexx */ context('Checking the Count function') /* Unit tests */ check('Empty strand' 'Count("")',, 'Count("")',, '=', 'A:0 C:0 G:0 T:0') check('Can count one nucleotide in single-character input' 'Count("G")',, 'Count("G")',, '=', 'A:0 C:0 G:1 T:0') check('Strand with repeated nucleotide' 'Count("GGGGGGG")',, 'Count("GGGGGGG")',, '=', 'A:0 C:0 G:7 T:0') check('Strand with repeated nucleotides' 'Count("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC")',, 'Count("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC")',, '=', 'A:20 C:12 G:17 T:21') check('Invalid nucleotides' 'Count("AGXXACT")',, 'Count("AGXXACT")',, '=', '')
33
# Instructions Given a 3 x 4 grid of pipes, underscores, and spaces, determine which number is represented, or whether it is garbled. ## Step One To begin with, convert a simple binary font to a string containing 0 or 1. The binary font uses pipes and underscores, four rows high and three columns wide. ```text _ # | | # zero. |_| # # the fourth row is always blank ``` Is converted to "0" ```text # | # one. | # # (blank fourth row) ``` Is converted to "1" If the input is the correct size, but not recognizable, your program should return '?' If the input is the incorrect size, your program should return an error. ## Step Two Update your program to recognize multi-character binary strings, replacing garbled numbers with ? ## Step Three Update your program to recognize all numbers 0 through 9, both individually and as part of a larger string. ```text _ _| |_ ``` Is converted to "2" ```text _ _ _ _ _ _ _ _ # | _| _||_||_ |_ ||_||_|| | # decimal numbers. ||_ _| | _||_| ||_| _||_| # # fourth line is always blank ``` Is converted to "1234567890" ## Step Four Update your program to handle multiple numbers, one per line. When converting several lines, join the lines with commas. ```text _ _ | _| _| ||_ _| _ _ |_||_ |_ | _||_| _ _ _ ||_||_| ||_| _| ``` Is converted to "123,456,789".
Convert : procedure parse arg input parse value (COUNTSTR("0A"X, input) > 0) '' with hasGroups output do while input \= '' parse var input group "0A"X input output ||= ConvertGroup(group) ; if hasGroups then ; output ||= ',' end return STRIP(output, 'T', ',') ConvertGroup : procedure parse value ARG(1) || ';' || LENGTH(ARG(1)) with input ';' inputlen parse value (inputlen // 12 == 0) (inputlen % 12) , with isValid ndigits if \isValid | ndigits < 1 then ; return '' parse value (inputlen % 4) '' with rowlen output do nth = 1 to ndigits digit = ExtractNthDigit(input, nth, inputlen, rowlen) output ||= GetNumberGivenDigit(digit) end return output ExtractNthDigit : procedure parse arg table, nth, tablelen, rowlen parse value (nth * 3 - 2) '' with offset output do i = 0 to 2 output ||= SUBSTR(table, offset + rowlen * i, 3) end output ||= COPIES(' ', 3) return output GetDigitTable : ; return , ' _ | ||_| :0; | | :1; _ _||_ :2; _ _| _| :3;' || , ' |_| | :4; _ |_ _| :5; _ |_ |_| :6; _ | | :7;' || , ' _ |_||_| :8; _ |_| _| :9' GetDigitGivenNumber : procedure parse arg number if number < 0 | number > 9 then ; return '' digits = GetDigitTable() ; pos = POS(number, digits) if pos < 1 then ; return '?' return SUBSTR(digits, pos - 13, 12) GetNumberGivenDigit : procedure parse arg digit digits = GetDigitTable() ; pos = POS(digit, digits) if pos < 1 then ; return '?' return SUBSTR(digits, pos + 13, 1)
/* Unit Test Runner: t-rexx */ context('Checking the Convert function') /* Test Variables */ input_0 = , ' _ ' || , '| |' || , '|_|' || , ' ' input_1 = , ' ' || , ' |' || , ' |' || , ' ' input_bad1 = , ' ' || , ' _ ' || , ' | ' || , ' ' input_bad2 = , ' _ ' || , '| |' || , ' ' input_bad3 = , ' ' || , ' |' || , ' |' || , ' ' input_binary = , ' _ _ _ _ ' || , ' | || | || | | || || |' || , ' | ||_| ||_| | ||_||_|' || , ' ' input_binary_garbled = , ' _ _ _ ' || , ' | || | || | || || |' || , ' | | _| ||_| | ||_||_|' || , ' ' input_2 = , ' _ ' || , ' _|' || , '|_ ' || , ' ' input_3 = , ' _ ' || , ' _|' || , ' _|' || , ' ' input_4 = , ' ' || , '|_|' || , ' |' || , ' ' input_5 = , ' _ ' || , '|_ ' || , ' _|' || , ' ' input_6 = , ' _ ' || , '|_ ' || , '|_|' || , ' ' input_7 = , ' _ ' || , ' |' || , ' |' || , ' ' input_8 = , ' _ ' || , '|_|' || , '|_|' || , ' ' input_9 = , ' _ ' || , '|_|' || , ' _|' || , ' ' input_series_decimal = , ' _ _ _ _ _ _ _ _ ' || , ' | _| _||_||_ |_ ||_||_|| |' || , ' ||_ _| | _||_| ||_| _||_|' || , ' ' input_series_fixed = , ' _ _ ' || , ' | _| _|' || , ' ||_ _|' || , ' ' || , "0A"X || , ' _ _ ' || , '|_||_ |_ ' || , ' | _||_|' || , ' ' || , "0A"X || , ' _ _ _ ' || , ' ||_||_|' || , ' ||_| _|' || , ' ' || , "0A"X input_series_varying = , ' _ _ ' || , ' | _| _||_|' || , ' ||_ _| |' || , ' ' || , "0A"X || , ' _ _ ' || , '|_ |_ ' || , ' _||_|' || , ' ' || , "0A"X || , ' _ ' || , ' |' || , ' |' || , ' ' || , "0A"X /* Unit tests */ check('No input' 'Convert("")',, 'Convert("")',, '=', '') check('Recognizes 0' 'Convert('input_0')',, 'Convert(input_0)',, '=', 0) check('Recognizes 1' 'Convert('input_1')',, 'Convert(input_1)',, '=', 1) check('Unreadable but correctly sized inputs return ?' 'Convert('input_bad1')',, 'Convert(input_bad1)',, '=', '?') check('Input with a number of lines that is not a multiple of four raises an error' 'Convert('input_bad2')',, 'Convert(input_bad2)',, '=', '') check('Input with a number of columns that is not a multiple of three raises an error' 'Convert('input_bad3')',, 'Convert(input_bad3)',, '=', '') check('Recognizes 110101100' 'Convert('input_binary')',, 'Convert(input_binary)',, '=', '110101100') check('Garbled numbers in a string are replaced with ?' 'Convert('input_binary_garbled')',, 'Convert(input_binary_garbled)',, '=', '11?10?1?0') check('Recognizes 2' 'Convert('input_2')',, 'Convert(input_2)',, '=', 2) check('Recognizes 3' 'Convert('input_3')',, 'Convert(input_3)',, '=', 3) check('Recognizes 4' 'Convert('input_4')',, 'Convert(input_4)',, '=', 4) check('Recognizes 5' 'Convert('input_5')',, 'Convert(input_5)',, '=', 5) check('Recognizes 6' 'Convert('input_6')',, 'Convert(input_6)',, '=', 6) check('Recognizes 7' 'Convert('input_7')',, 'Convert(input_7)',, '=', 7) check('Recognizes 8' 'Convert('input_8')',, 'Convert(input_8)',, '=', 8) check('Recognizes 9' 'Convert('input_9')',, 'Convert(input_9)',, '=', 9) check('Recognizes string of decimal numbers' 'Convert('input_series_decimal')',, 'Convert(input_series_decimal)',, '=', '1234567890') check('Numbers (fixed) separated by empty lines are recognized. Lines are joined by commas.' 'Convert('input_series_fixed')',, 'Convert(input_series_fixed)',, '=', '123,456,789') check('Numbers (varying) separated by empty lines are recognized. Lines are joined by commas.' 'Convert('input_series_varying')',, 'Convert(input_series_varying)',, '=', '1234,56,7')
34
# Instructions Your task is to figure out if a sentence is a pangram. A pangram is a sentence using every letter of the alphabet at least once. It is case insensitive, so it doesn't matter if a letter is lower-case (e.g. `k`) or upper-case (e.g. `K`). For this exercise we only use the basic letters used in the English alphabet: `a` to `z`.
IsPangram : procedure if ARG() \= 1 | ARG(1) == '' then ; return 0 /* Remove all non-letters, even spaces */ NON_LETTERS = ' ~`!@#$%^&*()_-+=<,>.?/:;"''0123456789' candidate = CHANGESTR(';',, TRANSLATE(UPPER(ARG(1)),, NON_LETTERS, ';'),, '') /* Initialize letter frequency table */ pangram.0 = 26 ; do i = 1 to pangram.0 by 1 letter = D2C(i + 64) ; pangram.letter = 0 end /* Parse input, count up letter occurrences */ do while candidate \= '' parse var candidate letter +1 candidate ; pangram.letter += 1 end /* Check letters counts, bail on first zero-valued count */ do i = 1 to pangram.0 by 1 letter = D2C(i + 64) ; if pangram.letter < 1 then ; return 0 end return 1
/* Unit Test Runner: t-rexx */ context('Checking the IsPangram function') /* Unit tests */ check('empty sentence' 'IsPangram("")',, 'IsPangram("")',, '=', 0) check('perfect lower case' 'IsPangram("abcdefghijklmnopqrstuvwxyz")',, 'IsPangram("abcdefghijklmnopqrstuvwxyz")',, '=', 1) check('only lower case' 'IsPangram("the quick brown fox jumps over the lazy dog")',, 'IsPangram("the quick brown fox jumps over the lazy dog")',, '=', 1) check('missing the letter "x"' 'IsPangram("a quick movement of the enemy will jeopardize five gunboats")',, 'IsPangram("a quick movement of the enemy will jeopardize five gunboats")',, '=', 0) check('missing the letter "h"' 'IsPangram("five boxing wizards jump quickly at it")',, 'IsPangram("five boxing wizards jump quickly at it")',, '=', 0) check('with underscores' 'IsPangram("the_quick_brown_fox_jumps_over_the_lazy_dog")',, 'IsPangram("the_quick_brown_fox_jumps_over_the_lazy_dog")',, '=', 1) check('with numbers' 'IsPangram("the 1 quick brown fox jumps over the 2 lazy dogs")',, 'IsPangram("the 1 quick brown fox jumps over the 2 lazy dogs")',, '=', 1) check('missing letters replaced by numbers' 'IsPangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog")',, 'IsPangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog")',, '=', 0) check('mixed case and punctuation' 'IsPangram(""Five quacking Zephyrs jolt my wax bed."")',, 'IsPangram(""Five quacking Zephyrs jolt my wax bed."")',, '=', 1) check('a-m and A-M are 26 different characters but not a pangram' 'IsPangram("the quick brown fox jumps over with lazy FX")',, 'IsPangram("the quick brown fox jumps over with lazy FX")',, '=', 0)
35
# Instructions Determine if a number is perfect, abundant, or deficient based on Nicomachus' (60 - 120 CE) classification scheme for positive integers. The Greek mathematician [Nicomachus][nicomachus] devised a classification scheme for positive integers, identifying each as belonging uniquely to the categories of **perfect**, **abundant**, or **deficient** based on their [aliquot sum][aliquot-sum]. The aliquot sum is defined as the sum of the factors of a number not including the number itself. For example, the aliquot sum of 15 is (1 + 3 + 5) = 9 - **Perfect**: aliquot sum = number - 6 is a perfect number because (1 + 2 + 3) = 6 - 28 is a perfect number because (1 + 2 + 4 + 7 + 14) = 28 - **Abundant**: aliquot sum > number - 12 is an abundant number because (1 + 2 + 3 + 4 + 6) = 16 - 24 is an abundant number because (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36 - **Deficient**: aliquot sum < number - 8 is a deficient number because (1 + 2 + 4) = 7 - Prime numbers are deficient Implement a way to determine whether a given number is **perfect**. Depending on your language track, you may also need to implement a way to determine whether a given number is **abundant** or **deficient**. [nicomachus]: https://en.wikipedia.org/wiki/Nicomachus [aliquot-sum]: https://en.wikipedia.org/wiki/Aliquot_sum
ClassifyNumber : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) < 1 then ; return '' parse value ARG(1) AliquotSum(ARG(1)) with number aliquotSum if aliquotSum < number then ; return 'DEFICIENT' if aliquotSum == number then ; return 'PERFECT' return 'ABUNDANT' AliquotSum : procedure parse value ARG(1) TRUNC(SquareRoot(ARG(1)) + 1) 2 0 , with number limit divisor sum if number == 1 then ; return 0 do while divisor < limit if number // divisor == 0 then do if divisor == number % divisor then ; sum += divisor else ; sum += (divisor + number % divisor) end divisor += 1 end return sum + 1 SquareRoot : procedure parse value ABS(ARG(1)) 1 0 with x r r1 if x == 0 then ; return 0 do while r \= r1 ; parse value r (x / r + r) / 2 with r1 r ; end return r
/* Unit Test Runner: t-rexx */ context('Checking the ClassifyNumber function') /* Test opttions */ numeric digits 20 /* Unit tests */ check('Perfect numbers -> Smallest perfect number is classified correctly' 'ClassifyNumber(6)',, 'ClassifyNumber(6)',, '=', 'PERFECT') check('Perfect numbers -> Medium perfect number is classified correctly' 'ClassifyNumber(28)',, 'ClassifyNumber(28)',, '=', 'PERFECT') check('Perfect numbers -> Large perfect number is classified correctly' 'ClassifyNumber(33550336)',, 'ClassifyNumber(33550336)',, '=', 'PERFECT') check('Abundant numbers -> Smallest abundant number is classified correctly' 'ClassifyNumber(12)',, 'ClassifyNumber(12)',, '=', 'ABUNDANT') check('Abundant numbers -> Medium abundant number is classified correctly' 'ClassifyNumber(30)',, 'ClassifyNumber(30)',, '=', 'ABUNDANT') check('Abundant numbers -> Large abundant number is classified correctly' 'ClassifyNumber(33550335)',, 'ClassifyNumber(33550335)',, '=', 'ABUNDANT') check('Deficient numbers -> Smallest prime deficient number is classified correctly' 'ClassifyNumber(2)',, 'ClassifyNumber(2)',, '=', 'DEFICIENT') check('Deficient numbers -> Smallest non-prime deficient number is classified correctly' 'ClassifyNumber(4)',, 'ClassifyNumber(4)',, '=', 'DEFICIENT') check('Deficient numbers -> Medium deficient number is classified correctly' 'ClassifyNumber(32)',, 'ClassifyNumber(32)',, '=', 'DEFICIENT') check('Deficient numbers -> Large deficient number is classified correctly' 'ClassifyNumber(33550337)',, 'ClassifyNumber(33550337)',, '=', 'DEFICIENT') check('Deficient numbers -> Edge case (no factors other than itself) is classified correctly' 'ClassifyNumber(1)',, 'ClassifyNumber(1)',, '=', 'DEFICIENT') check('Invalid inputs -> Zero is rejected (as it is not a positive integer)' 'ClassifyNumber(0)',, 'ClassifyNumber(0)',, '=', '') check('Invalid inputs -> Negative integer is rejected (as it is not a positive integer)' 'ClassifyNumber(-1)',, 'ClassifyNumber(-1)',, '=', '')
36
# Instructions Clean up user-entered phone numbers so that they can be sent SMS messages. The **North American Numbering Plan (NANP)** is a telephone numbering system used by many countries in North America like the United States, Canada or Bermuda. All NANP-countries share the same international country code: `1`. NANP numbers are ten-digit numbers consisting of a three-digit Numbering Plan Area code, commonly known as *area code*, followed by a seven-digit local number. The first three digits of the local number represent the *exchange code*, followed by the unique four-digit number which is the *subscriber number*. The format is usually represented as ```text (NXX)-NXX-XXXX ``` where `N` is any digit from 2 through 9 and `X` is any digit from 0 through 9. Your task is to clean up differently formatted telephone numbers by removing punctuation and the country code (1) if present. For example, the inputs - `+1 (613)-995-0253` - `613-995-0253` - `1 613 995 0253` - `613.995.0253` should all produce the output `6139950253` **Note:** As this exercise only deals with telephone numbers used in NANP-countries, only 1 is considered a valid country code.
Clean : procedure parse value SPACE(ARG(1)) with input if LENGTH(input) < 10 then ; return '' if VERIFY(input, ' .-+()0123456789', 'N') > 0 then ; return '' nanp = CHANGESTR(';', TRANSLATE(input,, ' .-+()', ';'), '') parse value LENGTH(nanp) SUBSTR(nanp, 1, 1) , with nanplen areacode if nanplen > 10 & areacode \= '1' then ; return '' if nanplen < 11 then ; nanp = '1' || nanp parse value LENGTH(nanp) SUBSTR(nanp, 2, 1) SUBSTR(nanp, 5, 1) , with nanplen areacode exchcode if nanplen \= 11 then ; return '' if VERIFY(areacode, '01', 'M') > 0 then ; return '' if VERIFY(exchcode, '01', 'M') > 0 then ; return '' return DELSTR(nanp, 1, 1)
/* Unit Test Runner: t-rexx */ context('Checking the Clean function') /* Unit tests */ check('cleans the number' 'Clean("(223) 456-7890")',, 'Clean("(223) 456-7890")',, '=', '2234567890') check('cleans numbers with dots' 'Clean("223.456.7890")',, 'Clean("223.456.7890")',, '=', '2234567890') check('cleans numbers with multiple spaces' 'Clean("223 456 7890 ")',, 'Clean("223 456 7890 ")',, '=', '2234567890') check('invalid when 9 digits' 'Clean("123456789")',, 'Clean("123456789")',, '=', '') check('invalid when 11 digits does not start with a 1' 'Clean("22234567890")',, 'Clean("22234567890")',, '=', '') check('valid when 11 digits and starting with 1' 'Clean("12234567890")',, 'Clean("12234567890")',, '=', '2234567890') check('valid when 11 digits and starting with 1 even with punctuation' 'Clean("+1 (223) 456-7890")',, 'Clean("+1 (223) 456-7890")',, '=', '2234567890') check('invalid when more than 11 digits' 'Clean("321234567890")',, 'Clean("321234567890")',, '=', '') check('invalid with letters' 'Clean("123-abc-7890")',, 'Clean("123-abc-7890")',, '=', '') check('invalid with punctuations' 'Clean("123-@:!-7890")',, 'Clean("123-@:!-7890")',, '=', '') check('invalid if area code does not start with 2-9' 'Clean("(123) 456-7890")',, 'Clean("(123) 456-7890")',, '=', '') check('invalid if exchange code does not start with 2-9' 'Clean("(223) 056-7890")',, 'Clean("(223) 056-7890")',, '=', '')
37
# Instructions Compute the prime factors of a given natural number. A prime number is only evenly divisible by itself and 1. Note that 1 is not a prime number. ## Example What are the prime factors of 60? - Our first divisor is 2. 2 goes into 60, leaving 30. - 2 goes into 30, leaving 15. - 2 doesn't go cleanly into 15. So let's move on to our next divisor, 3. - 3 goes cleanly into 15, leaving 5. - 3 does not go cleanly into 5. The next possible factor is 4. - 4 does not go cleanly into 5. The next possible factor is 5. - 5 does go cleanly into 5. - We're left only with 1, so now, we're done. Our successful divisors in that computation represent the list of prime factors of 60: 2, 2, 3, and 5. You can check this yourself: ```text 2 * 2 * 3 * 5 = 4 * 15 = 60 ``` Success!
Factors : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) < 2 then ; return '' return STRIP(ComputeFactors(ARG(1))) IsPrime : procedure n = ARG(1) if n == 1 then ; return 0 if n == 2 then ; return 1 limit = (SquareRoot(n) % 1) + 1 do i = 2 to limit if n // i == 0 then ; return 0 end return 1 ComputeFactors : procedure n = ARG(1) if n == 1 then ; return '' if IsPrime(n) then ; return '' || n limit = (SquareRoot(n) % 1) + 1 do i = 2 to limit if n // i == 0 then ; return i ComputeFactors(n / i) end return '' SquareRoot : procedure parse value ABS(ARG(1)) 1 0 with x r r1 if x == 0 then ; return 0 do while r \= r1 ; parse value r (x / r + r) / 2 with r1 r ; end return r
/* Unit Test Runner: t-rexx */ context('Checking the Factors function') /* Test Options */ numeric digits 20 /* Unit tests */ check('no factors' 'Factors(1)',, 'Factors(1)',, '=', '') check('prime number' 'Factors(2)',, 'Factors(2)',, '=', '2') check('another prime number' 'Factors(31)',, 'Factors(31)',, '=', '31') check('square of a prime' 'Factors(9)',, 'Factors(9)',, '=', '3 3') check('product of first prime' 'Factors(20)',, 'Factors(20)',, '=', '2 2 5') check('cube of a prime' 'Factors(8)',, 'Factors(8)',, '=', '2 2 2') check('product of second prime' 'Factors(33)',, 'Factors(33)',, '=', '3 11') check('product of third prime' 'Factors(75)',, 'Factors(75)',, '=', '3 5 5') check('product of first and second prime' 'Factors(6)',, 'Factors(6)',, '=', '2 3') check('product of primes and non-primes' 'Factors(18)',, 'Factors(18)',, '=', '2 3 3') check('product of primes' 'Factors(901255)',, 'Factors(901255)',, '=', '5 17 23 461') check('factors include a large prime' 'Factors(93819012551)',, 'Factors(93819012551)',, '=', '11 9539 894119')
38
# Instructions Translate RNA sequences into proteins. RNA can be broken into three nucleotide sequences called codons, and then translated to a polypeptide like so: RNA: `"AUGUUUUCU"` => translates to Codons: `"AUG", "UUU", "UCU"` => which become a polypeptide with the following sequence => Protein: `"Methionine", "Phenylalanine", "Serine"` There are 64 codons which in turn correspond to 20 amino acids; however, all of the codon sequences and resulting amino acids are not important in this exercise. If it works for one codon, the program should work for all of them. However, feel free to expand the list in the test suite to include them all. There are also three terminating codons (also known as 'STOP' codons); if any of these codons are encountered (by the ribosome), all translation ends and the protein is terminated. All subsequent codons after are ignored, like this: RNA: `"AUGUUUUCUUAAAUG"` => Codons: `"AUG", "UUU", "UCU", "UAA", "AUG"` => Protein: `"Methionine", "Phenylalanine", "Serine"` Note the stop codon `"UAA"` terminates the translation and the final methionine is not translated into the protein sequence. Below are the codons and resulting Amino Acids needed for the exercise. Codon | Protein :--- | :--- AUG | Methionine UUU, UUC | Phenylalanine UUA, UUG | Leucine UCU, UCC, UCA, UCG | Serine UAU, UAC | Tyrosine UGU, UGC | Cysteine UGG | Tryptophan UAA, UAG, UGA | STOP Learn more about [protein translation on Wikipedia][protein-translation]. [protein-translation]: https://en.wikipedia.org/wiki/Translation_(biology)
Translate : procedure CODON_PROTEIN_MAP = 'AUG:methionine UUU:phenylalanine' , 'UUC:phenylalanine UUA:leucine UUG:leucine' , 'UCU:serine UCC:serine UCA:serine UCG:serine' , 'UAU:tyrosine UAC:tyrosine UGU:cysteine UGC:cysteine' , 'UGG:tryptophan UAA:stop UAG:stop UGA:stop' if ARG() \= 1 | (LENGTH(ARG(1)) // 3 \= 0) then ; return '' parse arg sequence proteins do while sequence \= '' parse var sequence codon +3 sequence codpos = POS(codon, CODON_PROTEIN_MAP) if codpos < 1 then ; return '' parse value SUBSTR(CODON_PROTEIN_MAP, codpos) with . ':' protein . if protein == 'stop' then ; leave proteins = proteins protein end return STRIP(proteins, 'L')
/* Unit Test Runner: t-rexx */ context('Checking the Translate function') /* Unit tests */ check('Empty RNA sequence results in no proteins' 'Translate("")',, 'Translate("")',, '=', '') check('Methionine RNA sequence' 'Translate("AUG")',, 'Translate("AUG")',, '=', 'methionine') check('Phenylalanine RNA sequence 1' 'Translate("UUU")',, 'Translate("UUU")',, '=', 'phenylalanine') check('Phenylalanine RNA sequence 2' 'Translate("UUC")',, 'Translate("UUC")',, '=', 'phenylalanine') check('Leucine RNA sequence 1' 'Translate("UUA")',, 'Translate("UUA")',, '=', 'leucine') check('Leucine RNA sequence 2' 'Translate("UUG")',, 'Translate("UUG")',, '=', 'leucine') check('Serine RNA sequence 1' 'Translate("UCU")',, 'Translate("UCU")',, '=', 'serine') check('Serine RNA sequence 2' 'Translate("UCC")',, 'Translate("UCC")',, '=', 'serine') check('Serine RNA sequence 3' 'Translate("UCA")',, 'Translate("UCA")',, '=', 'serine') check('Serine RNA sequence 4' 'Translate("UCG")',, 'Translate("UCG")',, '=', 'serine') check('Tyrosine RNA sequence 1' 'Translate("UAU")',, 'Translate("UAU")',, '=', 'tyrosine') check('Tyrosine RNA sequence 2' 'Translate("UAC")',, 'Translate("UAC")',, '=', 'tyrosine') check('Cysteine RNA sequence 1' 'Translate("UGU")',, 'Translate("UGU")',, '=', 'cysteine') check('Cysteine RNA sequence 2' 'Translate("UGC")',, 'Translate("UGC")',, '=', 'cysteine') check('Tryptophan RNA sequence' 'Translate("UGG")',, 'Translate("UGG")',, '=', 'tryptophan') check('STOP codon RNA sequence 1' 'Translate("UAA")',, 'Translate("UAA")',, '=', '') check('STOP codon RNA sequence 2' 'Translate("UAG")',, 'Translate("UAG")',, '=', '') check('STOP codon RNA sequence 3' 'Translate("UGA")',, 'Translate("UGA")',, '=', '') check('Translate RNA strand into correct protein list' 'Translate("AUGUUUUGG")',, 'Translate("AUGUUUUGG")',, '=', 'methionine phenylalanine tryptophan') check('Translation stops if STOP codon at beginning of sequence' 'Translate("UAGUGG")',, 'Translate("UAGUGG")',, '=', '') check('Translation stops if STOP codon at end of two-codon sequence' 'Translate("UGGUAG")',, 'Translate("UGGUAG")',, '=', 'tryptophan') check('Translation stops if STOP codon at end of three-codon sequence' 'Translate("AUGUUUUAA")',, 'Translate("AUGUUUUAA")',, '=', 'methionine phenylalanine') check('Translation stops if STOP codon in middle of three-codon sequence' 'Translate("UGGUAGUGG")',, 'Translate("UGGUAGUGG")',, '=', 'tryptophan') check('Translation stops if STOP codon in middle of six-codon sequence' 'Translate("UGGUGUUAUUAAUGGUUU")',, 'Translate("UGGUGUUAUUAAUGGUUU")',, '=', 'tryptophan cysteine tyrosine')
39
# Instructions For want of a horseshoe nail, a kingdom was lost, or so the saying goes. Given a list of inputs, generate the relevant proverb. For example, given the list `["nail", "shoe", "horse", "rider", "message", "battle", "kingdom"]`, you will output the full text of this proverbial rhyme: ```text For want of a nail the shoe was lost. For want of a shoe the horse was lost. For want of a horse the rider was lost. For want of a rider the message was lost. For want of a message the battle was lost. For want of a battle the kingdom was lost. And all for the want of a nail. ``` Note that the list of inputs may vary; your solution should be able to handle lists of arbitrary length and content. No line of the output text should be a static, unchanging string; all should vary according to the input given.
Proverb : procedure if ARG() < 1 | ARG(1) == '' then ; return '' if ARG() == 1 then ; return 'And all for the want of a' ARG(1) || '.' || "0A"X proverb = '' ; lastn = ARG() do n = 1 to lastn if n + 1 > lastn then ; leave proverb ||= 'For want of a' ARG(n) 'the' ARG(n + 1) 'was lost.' || "0A"X end return proverb || 'And all for the want of a' ARG(1) || '.' || "0A"X
/* Unit Test Runner: t-rexx */ context('Checking the Proverb function') /* Test Variables */ proverb_1 = 'And all for the want of a nail.' || "0A"X proverb_2 = 'For want of a nail the shoe was lost.' || "0A"X || , 'And all for the want of a nail.' || "0A"X proverb_3 = 'For want of a nail the shoe was lost.' || "0A"X || , 'For want of a shoe the horse was lost.' || "0A"X || , 'And all for the want of a nail.' || "0A"X proverb_full = 'For want of a nail the shoe was lost.' || "0A"X || , 'For want of a shoe the horse was lost.' || "0A"X || , 'For want of a horse the rider was lost.' || "0A"X || , 'For want of a rider the message was lost.' || "0A"X || , 'For want of a message the battle was lost.' || "0A"X || , 'For want of a battle the kingdom was lost.' || "0A"X || , 'And all for the want of a nail.' || "0A"X proverb_modern = 'For want of a pin the gun was lost.' || "0A"X || , 'For want of a gun the soldier was lost.' || "0A"X || , 'For want of a soldier the battle was lost.' || "0A"X || , 'And all for the want of a pin.' || "0A"X /* Unit tests */ check('zero pieces' 'Proverb()',, 'Proverb()',, '=', '') check('one piece' 'Proverb("nail")',, 'Proverb("nail")',, '=', proverb_1) check('two pieces' 'Proverb("nail", "shoe")',, 'Proverb("nail", "shoe")',, '=', proverb_2) check('three pieces' 'Proverb("nail", "shoe", "horse")',, 'Proverb("nail", "shoe", "horse")',, '=', proverb_3) check('full proverb' 'Proverb("nail", "shoe", "horse", "rider", "message", "battle", "kingdom")',, 'Proverb("nail", "shoe", "horse", "rider", "message", "battle", "kingdom")',, '=', proverb_full) check('four pieces modernized' 'Proverb("pin", "gun", "soldier", "battle")',, 'Proverb("pin", "gun", "soldier", "battle")',, '=', proverb_modern)
40
# Instructions Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other. In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal. A chessboard can be represented by an 8 by 8 array. So if you are told the white queen is at `c5` (zero-indexed at column 2, row 3) and the black queen at `f2` (zero-indexed at column 5, row 6), then you know that the set-up is like so: ```text a b c d e f g h 8 _ _ _ _ _ _ _ _ 8 7 _ _ _ _ _ _ _ _ 7 6 _ _ _ _ _ _ _ _ 6 5 _ _ W _ _ _ _ _ 5 4 _ _ _ _ _ _ _ _ 4 3 _ _ _ _ _ _ _ _ 3 2 _ _ _ _ _ B _ _ 2 1 _ _ _ _ _ _ _ _ 1 a b c d e f g h ``` You are also be able to answer whether the queens can attack each other. In this case, that answer would be yes, they can, because both pieces share a diagonal.
CanAttack : procedure parse arg wq, bq if wq == '' | bq == '' then ; return '' if wq == bq then ; return '' if \IsValidBoardPosition(wq) | \IsValidBoardPosition(bq) then ; return '' parse value MakeXYPosition(wq) with wqx wqy parse value MakeXYPosition(bq) with bqx bqy if wqx == '' | bqx == '' then ; return '' return wqx == bqx | wqy == bqy | ABS(wqx - bqx) == ABS(wqy - bqy) IsValidXY : procedure parse arg x, y return x < 9 & x > 0 & y < 9 & y > 0 IsValidBoardPosition : procedure parse value STRIP(ARG(1)) with colsym +1 row validColumn = VERIFY(colsym, 'abcdefgh', 'M') > 0 return row > 0 & row < 9 & validColumn MakeXYPosition : procedure parse arg boardPosition parse value IsValidBoardPosition(ARG(1)) with isValidBoardPosition if \isValidBoardPosition then ; return '' y = C2D(SUBSTR(boardPosition, 1, 1)) - C2D('a') + 1 x = SUBSTR(boardPosition, 2, 1) if \IsValidXY(x, y) then ; return '' return x y
/* Unit Test Runner: t-rexx */ context('Checking the Queen Attack function') /* Unit tests */ function = 'CanAttack' check('Test attack ability -> cannot attack' 'CanAttack("b3", "d7")',, 'CanAttack("b3", "d7")',, '=', 0) check('Test attack ability -> cannot attack' 'CanAttack("b3", "d7")',, 'CanAttack("b3", "d7")',, '=', 0) check('Test attack ability -> can attack on same row' 'CanAttack("e4", "b4")',, 'CanAttack("e4", "b4")',, '=', 1) check('Test attack ability -> can attack on same column' 'CanAttack("b4", "b7")',, 'CanAttack("b4", "b7")',, '=', 1) check('Test attack ability -> can attack on first diagonal' 'CanAttack("a1", "f6")',, 'CanAttack("a1", "f6")',, '=', 1) check('Test attack ability -> can attack on second diagonal' 'CanAttack("a6", "b7")',, 'CanAttack("a6", "b7")',, '=', 1) check('Test attack ability -> can attack on third diagonal' 'CanAttack("d1", "f3")',, 'CanAttack("d1", "f3")',, '=', 1) check('Test attack ability -> can attack on fourth diagonal' 'CanAttack("f1", "a6")',, 'CanAttack("f1", "a6")',, '=', 1) check('Test attack ability -> queens must not share same square' 'CanAttack("e4", "e4")',, 'CanAttack("e4", "e4")',, '=', '') check('Test attack ability -> queens must not be blank' 'CanAttack("", "")',, 'CanAttack("", "")',, '=', '') check('Test attack ability -> invalid row 1' 'CanAttack("f1", "a9")',, 'CanAttack("f1", "a9")',, '=', '') check('Test attack ability -> invalid row 2' 'CanAttack("f1", "a0")',, 'CanAttack("f1", "a0")',, '=', '') check('Test attack ability -> invalid column' 'CanAttack("f1", "i8")',, 'CanAttack("f1", "i8")',, '=', '')
41
# Instructions Your task is to convert a number into a string that contains raindrop sounds corresponding to certain potential factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to test if one number is a factor of another is to use the [modulo operation][modulo]. The rules of `raindrops` are that if a given number: - has 3 as a factor, add 'Pling' to the result. - has 5 as a factor, add 'Plang' to the result. - has 7 as a factor, add 'Plong' to the result. - _does not_ have any of 3, 5, or 7 as a factor, the result should be the digits of the number. ## Examples - 28 has 7 as a factor, but not 3 or 5, so the result would be "Plong". - 30 has both 3 and 5 as factors, but not 7, so the result would be "PlingPlang". - 34 is not factored by 3, 5, or 7, so the result would be "34". [modulo]: https://en.wikipedia.org/wiki/Modulo_operation
Raindrops : procedure parse arg n raindrops if n < 1 | ARG() \= 1 then ; return -1 if n // 3 == 0 then ; raindrops = 'Pling' if n // 5 == 0 then ; raindrops = raindrops || 'Plang' if n // 7 == 0 then ; raindrops = raindrops || 'Plong' if raindrops == '' then ; return n return raindrops
/* Unit Test Runner: t-rexx */ context('Checking the Raindrops function') /* Unit tests */ check('there is no sound for' 'Raindrops(1)',, 'Raindrops(1)',, '=', 1) check('Pling is the sound for' 'Raindrops(3)',, 'Raindrops(3)',, '=', 'Pling') check('Plang is the sound for' 'Raindrops(5)',, 'Raindrops(5)',, '=', 'Plang') check('Plong is the sound for' 'Raindrops(7)',, 'Raindrops(7)',, '=', 'Plong') check('Pling is the sound for' 'Raindrops(6)',, 'Raindrops(6)',, '=', 'Pling') check('there is no sound for' 'Raindrops(8)',, 'Raindrops(8)',, '=', 8) check('Pling is the sound for' 'Raindrops(9)',, 'Raindrops(9)',, '=', 'Pling') check('Plang is the sound for' 'Raindrops(10)',, 'Raindrops(10)',, '=', 'Plang') check('Plong is the sound for' 'Raindrops(14)',, 'Raindrops(14)',, '=', 'Plong') check('PlingPlang is the sound for' 'Raindrops(15)',, 'Raindrops(15)',, '=', 'PlingPlang') check('PlingPlong is the sound for' 'Raindrops(21)',, 'Raindrops(21)',, '=', 'PlingPlong') check('Plang is the sound for' 'Raindrops(25)',, 'Raindrops(25)',, '=', 'Plang') check('Pling is the sound for' 'Raindrops(27)',, 'Raindrops(27)',, '=', 'Pling') check('PlangPlong is the sound for' 'Raindrops(35)',, 'Raindrops(35)',, '=', 'PlangPlong') check('Plong is the sound for' 'Raindrops(49)',, 'Raindrops(49)',, '=', 'Plong') check('there is no sound for' 'Raindrops(52)',, 'Raindrops(52)',, '=', 52) check('PlingPlangPlong is the sound for' 'Raindrops(105)',, 'Raindrops(105)',, '=', 'PlingPlangPlong') check('Plang is the sound for' 'Raindrops(3125)',, 'Raindrops(3125)',, '=', 'Plang')
42
# Instructions If you want to build something using a Raspberry Pi, you'll probably use _resistors_. For this exercise, you need to know two things about them: - Each resistor has a resistance value. - Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read. To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values. Each band has a position and a numeric value. The first 2 bands of a resistor have a simple encoding scheme: each color maps to a single number. In this exercise you are going to create a helpful program so that you don't have to remember the values of the bands. These colors are encoded as follows: - black: 0 - brown: 1 - red: 2 - orange: 3 - yellow: 4 - green: 5 - blue: 6 - violet: 7 - grey: 8 - white: 9 The goal of this exercise is to create a way: - to look up the numerical value associated with a particular color band - to list the different band colors Mnemonics map the colors to the numbers, that, when stored as an array, happen to map to their index in the array: Better Be Right Or Your Great Big Values Go Wrong. More information on the color encoding of resistors can be found in the [Electronic color code Wikipedia article][e-color-code]. [e-color-code]: https://en.wikipedia.org/wiki/Electronic_color_code
ColorCode : procedure return WORDPOS(UPPER(ARG(1)), Colors()) - 1 Colors : procedure return 'BLACK BROWN RED ORANGE YELLOW GREEN BLUE VIOLET GREY WHITE'
/* Unit Test Runner: t-rexx */ context('Checking the ColorCode and Colors functions') /* Unit tests */ check('Color codes -> Black' 'ColorCode("Black")',, 'ColorCode("Black")',, '=', 0) check('Color codes -> White' 'ColorCode("White")',, 'ColorCode("White")',, '=', 9) check('Color codes -> Orange' 'ColorCode("Orange")',, 'ColorCode("Orange")',, '=', 3) COLORS = 'BLACK BROWN RED ORANGE YELLOW GREEN BLUE VIOLET GREY WHITE' check('Colors' 'Colors()',, 'Colors()',, '=', COLORS)
43
# Instructions If you want to build something using a Raspberry Pi, you'll probably use _resistors_. For this exercise, you need to know two things about them: - Each resistor has a resistance value. - Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read. To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values. Each band has a position and a numeric value. The first 2 bands of a resistor have a simple encoding scheme: each color maps to a single number. For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15. In this exercise you are going to create a helpful program so that you don't have to remember the values of the bands. The program will take color names as input and output a two digit number, even if the input is more than two colors! The band colors are encoded as follows: - black: 0 - brown: 1 - red: 2 - orange: 3 - yellow: 4 - green: 5 - blue: 6 - violet: 7 - grey: 8 - white: 9 From the example above: brown-green should return 15, and brown-green-violet should return 15 too, ignoring the third color.
ColorCode : procedure COLORS = 'BLACK BROWN RED ORANGE YELLOW GREEN BLUE VIOLET GREY WHITE' parse upper value ARG(1) with tcolor ucolor . return 10 * (WORDPOS(tcolor, COLORS) - 1) + WORDPOS(ucolor, COLORS) - 1
/* Unit Test Runner: t-rexx */ context('Checking the ColorCode function') /* Unit tests */ check('Color codes -> Brown and black' 'ColorCode("Brown Black")',, 'ColorCode("Brown Black")',, '=', 10) check('Color codes -> Blue and grey' 'ColorCode("Blue Grey")',, 'ColorCode("Blue Grey")',, '=', 68) check('Color codes -> Yellow and violet' 'ColorCode("Yellow Violet")',, 'ColorCode("Yellow Violet")',, '=', 47) check('Color codes -> White and red' 'ColorCode("White Red")',, 'ColorCode("White Red")',, '=', 92) check('Color codes -> Orange and orange' 'ColorCode("Orange Orange")',, 'ColorCode("Orange Orange")',, '=', 33) check('Ignore additional colors' 'ColorCode("Green Brown Orange")',, 'ColorCode("Green Brown Orange")',, '=', 51) check('Color codes -> Black and brown, one digit' 'ColorCode("Black Brown")',, 'ColorCode("Black Brown")',, '=', 1)
44
# Instructions If you want to build something using a Raspberry Pi, you'll probably use _resistors_. For this exercise, you need to know only three things about them: - Each resistor has a resistance value. - Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read. To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values. - Each band acts as a digit of a number. For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15. In this exercise, you are going to create a helpful program so that you don't have to remember the values of the bands. The program will take 3 colors as input, and outputs the correct value, in ohms. The color bands are encoded as follows: - black: 0 - brown: 1 - red: 2 - orange: 3 - yellow: 4 - green: 5 - blue: 6 - violet: 7 - grey: 8 - white: 9 In Resistor Color Duo you decoded the first two colors. For instance: orange-orange got the main value `33`. The third color stands for how many zeros need to be added to the main value. The main value plus the zeros gives us a value in ohms. For the exercise it doesn't matter what ohms really are. For example: - orange-orange-black would be 33 and no zeros, which becomes 33 ohms. - orange-orange-red would be 33 and 2 zeros, which becomes 3300 ohms. - orange-orange-orange would be 33 and 3 zeros, which becomes 33000 ohms. (If Math is your thing, you may want to think of the zeros as exponents of 10. If Math is not your thing, go with the zeros. It really is the same thing, just in plain English instead of Math lingo.) This exercise is about translating the colors into a label: > "... ohms" So an input of `"orange", "orange", "black"` should return: > "33 ohms" When we get to larger resistors, a [metric prefix][metric-prefix] is used to indicate a larger magnitude of ohms, such as "kiloohms". That is similar to saying "2 kilometers" instead of "2000 meters", or "2 kilograms" for "2000 grams". For example, an input of `"orange", "orange", "orange"` should return: > "33 kiloohms" [metric-prefix]: https://en.wikipedia.org/wiki/Metric_prefix
Colors : procedure return 'BLACK BROWN RED ORANGE YELLOW GREEN BLUE VIOLET GREY WHITE' ValidColors : procedure parse upper arg colors, numcolors /* Extract `numcolors` colors only */ colors_ = SUBSTR(colors,, 1,, WORDINDEX(colors, numcolors) + , WORDLENGTH(colors, numcolors) - 1) /* Eliminate excess from input */ colors = colors_ /* Validate each color against reference */ do while colors_ \= '' parse var colors_ color colors_ if WORDPOS(color, Colors()) < 1 then ; return '' end return colors ColorCode : procedure /* Extract and validate colors, compute their numeric value */ if ARG() < 1 | ARG(1) == '' then ; return '' colors = ValidColors(ARG(1), 3) ; if colors == '' then ; return '' parse var colors tcolor ucolor zcolor . tval = (WORDPOS(tcolor, Colors()) - 1) uval = (WORDPOS(ucolor, Colors()) - 1) zval = (WORDPOS(zcolor, Colors()) - 1) /* Compute resistance value in ohms */ zeroes = '' ; if zval > 0 then ; zeroes = COPIES('0', zval) ohms = (10 * tval + uval) || zeroes /* Report resistance value in appropriate units */ if ohms / 1000000000 >= 1.0 then do if ohms // 1000000000 > 0 then return (ohms % 1000000000) || (ohms // 1000000000 % 1000000) 'megaohms' return (ohms % 1000000000) 'gigaohms' end if ohms / 1000000 >= 1.0 then do if ohms // 1000000 > 0 then return (ohms % 1000000) || (ohms // 1000000 % 1000) 'kiloohms' return (ohms % 1000000) 'megaohms' end if ohms / 1000 >= 1.0 then do if ohms // 1000 > 0 then return (ohms % 1000) || (ohms // 1000 % 1) 'ohms' return (ohms % 1000) 'kiloohms' end return ohms 'ohms'
/* Unit Test Runner: t-rexx */ function = 'ColorCode' context('Checking the ColorCode function') /* Test Options */ numeric digits 20 /* Unit tests */ check("Orange and orange and black" 'ColorCode("Orange Orange Black")',, 'ColorCode("Orange Orange Black")',, '=', '33 ohms') check("Blue and grey and brown" 'ColorCode("Blue Grey Brown")',, 'ColorCode("Blue Grey Brown")',, '=', '680 ohms') check("Brown and red and red" 'ColorCode("Brown Red Red")',, 'ColorCode("Brown Red Red")',, '=', '1200 ohms') check("Red and black and red" 'ColorCode("Red Black Red")',, 'ColorCode("Red Black Red")',, '=', '2 kiloohms') check("Green and brown and orange" 'ColorCode("Green Brown Orange")',, 'ColorCode("Green Brown Orange")',, '=', '51 kiloohms') check("Yellow and violet and yellow" 'ColorCode("Yellow Violet Yellow")',, 'ColorCode("Yellow Violet Yellow")',, '=', '470 kiloohms') check("Blue and violet and blue" 'ColorCode("Blue Violet Grey")',, 'ColorCode("Blue Violet Grey")',, '=', '6700 megaohms') check("Invalid first color" 'ColorCode("foo White White")',, 'ColorCode("foo White White")',, '=', '') check("Invalid second color" 'ColorCode("White bar White")',, 'ColorCode("White bar White")',, '=', '') check("Invalid third color" 'ColorCode("White White baz")',, 'ColorCode("White White baz")',, '=', '') check("Minimum possible value" 'ColorCode("Black Black Black")',, 'ColorCode("Black Black Black")',, '=', '0 ohms') check("Maximum possible value" 'ColorCode("White White White")',, 'ColorCode("White White White")',, '=', '99 gigaohms') check("First two colors make an invalid octal number" 'ColorCode("Black Grey Black")',, 'ColorCode("Black Grey Black")',, '=', '8 ohms') check("Ignore extra colors" 'ColorCode("Blue Green Yellow Orange")',, 'ColorCode("Blue Green Yellow Orange")',, '=', '650 kiloohms')
45
# Instructions Reverse a string For example: input: "cool" output: "looc"
ReverseString : procedure parse arg s if s == '' then ; return '' else ; return ReverseString(RIGHT(s, LENGTH(s) - 1)) || LEFT(s, 1)
/* Unit Test Runner: t-rexx */ context('Checking the ReverseString function') /* Unit tests */ check('an empty string' 'ReverseString("")',, 'ReverseString("")',, '=', "") check('an word' 'ReverseString("robot")',, 'ReverseString("robot")',, '=', "tobor") check('an capitalized word' 'ReverseString("Ramen")',, 'ReverseString("Ramen")',, '=', "nemaR") check('a sentence with punctuation' 'ReverseString("I''m Hungry")',, 'ReverseString("I''m Hungry!")',, '=', "!yrgnuH m'I") check('a palindrome' 'ReverseString("racecar")',, 'ReverseString("racecar")',, '=', "racecar") check('an even-sized word' 'ReverseString("drawer")',, 'ReverseString("drawer")',, '=', "reward")
46
# Instructions Your task is determine the RNA complement of a given DNA sequence. Both DNA and RNA strands are a sequence of nucleotides. The four nucleotides found in DNA are adenine (**A**), cytosine (**C**), guanine (**G**) and thymine (**T**). The four nucleotides found in RNA are adenine (**A**), cytosine (**C**), guanine (**G**) and uracil (**U**). Given a DNA strand, its transcribed RNA strand is formed by replacing each nucleotide with its complement: - `G` -> `C` - `C` -> `G` - `T` -> `A` - `A` -> `U` ~~~~exercism/note If you want to look at how the inputs and outputs are structured, take a look at the examples in the test suite. ~~~~
DNA2RNA : procedure if ARG() \= 1 | ARG(1) == '' then ; return '' return TRANSLATE(UPPER(ARG(1)), 'GCAU', 'CGTA')
/* Unit Test Runner: t-rexx */ context('Checking the DNA2RNA function') /* Unit tests */ check('Empty RNA sequence' 'DNA2RNA("")',, 'DNA2RNA("")',, '=', "") check('RNA complement of cytosine is guanine' 'DNA2RNA("C")',, 'DNA2RNA("C")',, '=', "G") check('RNA complement of guanine is cytosine' 'DNA2RNA("G")',, 'DNA2RNA("G")',, '=', "C") check('RNA complement of thymine is adenine' 'DNA2RNA("T")',, 'DNA2RNA("T")',, '=', "A") check('RNA complement of adenine is uracil' 'DNA2RNA("A")',, 'DNA2RNA("A")',, '=', "U") check('RNA complement' 'DNA2RNA("ACGTGGTCTTAA")',, 'DNA2RNA("ACGTGGTCTTAA")',, '=', "UGCACCAGAAUU")
47
# Instructions Write a function to convert from normal numbers to Roman Numerals. The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis. One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programs. The Romans wrote numbers using letters - I, V, X, L, C, D, M. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets). ```text 1 => I 10 => X 7 => VII ``` The maximum number supported by this notation is 3,999. (The Romans themselves didn't tend to go any higher) Wikipedia says: 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. To see this in practice, consider the example of 1990. In Roman numerals 1990 is MCMXC: 1000=M 900=CM 90=XC 2008 is written as MMVIII: 2000=MM 8=VIII Learn more about [Roman numberals on Wikipedia][roman-numerals]. [roman-numerals]: https://wiki.imperivm-romanvm.com/wiki/Roman_Numerals
Roman : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') then ; return '' parse arg number if number < 1 | number > 3999 then ; return '' parse value RIGHT(number, 4, '0') with m +1 c +1 x +1 i +1 roman = WORD('. M MM MMM', m + 1) || , WORD('. C CC CCC CD D DC DCC DCCC CM', c + 1) || , WORD('. X XX XXX XL L LX LXX LXXX XC', x + 1) || , WORD('. I II III IV V VI VII VIII IX', i + 1) return CHANGESTR('.', roman, '')
/* Unit Test Runner: t-rexx */ context('Checking the Roman function') /* Unit tests */ check('1 is I' 'Roman(1)',, 'Roman(1)',, '=', 'I') check('2 is II' 'Roman(2)',, 'Roman(2)',, '=', 'II') check('3 is III' 'Roman(3)',, 'Roman(3)',, '=', 'III') check('4 is IV' 'Roman(4)',, 'Roman(4)',, '=', 'IV') check('5 is V' 'Roman(5)',, 'Roman(5)',, '=', 'V') check('6 is VI' 'Roman(6)',, 'Roman(6)',, '=', 'VI') check('9 is IX' 'Roman(9)',, 'Roman(9)',, '=', 'IX') check('16 is XVI' 'Roman(16)',, 'Roman(16)',, '=', 'XVI') check('27 is XXVII' 'Roman(27)',, 'Roman(27)',, '=', 'XXVII') check('48 is XLVIII' 'Roman(48)',, 'Roman(48)',, '=', 'XLVIII') check('49 is XLIX' 'Roman(49)',, 'Roman(49)',, '=', 'XLIX') check('59 is LIX' 'Roman(59)',, 'Roman(59)',, '=', 'LIX') check('66 is LXVI' 'Roman(66)',, 'Roman(66)',, '=', 'LXVI') check('93 is XCIII' 'Roman(93)',, 'Roman(93)',, '=', 'XCIII') check('141 is CXLI' 'Roman(141)',, 'Roman(141)',, '=', 'CXLI') check('163 is CLXIII' 'Roman(163)',, 'Roman(163)',, '=', 'CLXIII') check('166 is CLXVI' 'Roman(166)',, 'Roman(166)',, '=', 'CLXVI') check('402 is CDII' 'Roman(402)',, 'Roman(402)',, '=', 'CDII') check('575 is DLXXV' 'Roman(575)',, 'Roman(575)',, '=', 'DLXXV') check('666 is DCLXVI' 'Roman(666)',, 'Roman(666)',, '=', 'DCLXVI') check('911 is CMXI' 'Roman(911)',, 'Roman(911)',, '=', 'CMXI') check('1024 is MXXIV' 'Roman(1024)',, 'Roman(1024)',, '=', 'MXXIV') check('1666 is MDCLXVI' 'Roman(1666)',, 'Roman(1666)',, '=', 'MDCLXVI') check('3000 is MMM' 'Roman(3000)',, 'Roman(3000)',, '=', 'MMM') check('3001 is MMMI' 'Roman(3001)',, 'Roman(3001)',, '=', 'MMMI') check('3999 is MMMCMXCIX' 'Roman(3999)',, 'Roman(3999)',, '=', 'MMMCMXCIX')
48
# Instructions Create an implementation of the rotational cipher, also sometimes called the Caesar cipher. The Caesar cipher is a simple shift cipher that relies on transposing all the letters in the alphabet using an integer key between `0` and `26`. Using a key of `0` or `26` will always yield the same output due to modular arithmetic. The letter is shifted for as many values as the value of the key. The general notation for rotational ciphers is `ROT + <key>`. The most commonly used rotational cipher is `ROT13`. A `ROT13` on the Latin alphabet would be as follows: ```text Plain: abcdefghijklmnopqrstuvwxyz Cipher: nopqrstuvwxyzabcdefghijklm ``` It is stronger than the Atbash cipher because it has 27 possible keys, and 25 usable keys. Ciphertext is written out in the same formatting as the input including spaces and punctuation. ## Examples - ROT5 `omg` gives `trl` - ROT0 `c` gives `c` - ROT26 `Cool` gives `Cool` - ROT13 `The quick brown fox jumps over the lazy dog.` gives `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.` - ROT13 `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.` gives `The quick brown fox jumps over the lazy dog.`
Convert : procedure if ARG() \= 2 | ARG(1) == '' | \DATATYPE(ARG(2), 'N') then ; return '' plaintext = ARG(1) ; rot = ARG(2) if rot < 0 then ; return '' if rot == 0 then ; return plaintext /* Setup constants to minimize conversion overhead and normalize `rot` */ parse value C2D('A') C2D('Z') C2D('a') C2D('z') , with codeUA codeUZ codeLA codeLZ rot = rot // 26 /* Parse-by-character, and selectively apply `rot` to plaintext */ ciphertext = '' ; do while plaintext \= '' parse var plaintext c +1 plaintext t = C2D(c) ; x = t + rot select /* Only letters are shifted */ when (t >= codeUA & t <= codeUZ) then ; if x > codeUZ then ; x -= 26 when (t >= codeLA & t <= codeLZ) then ; if x > codeLZ then ; x -= 26 otherwise ; x = t end ciphertext ||= D2C(x) end return ciphertext
/* Unit Test Runner: t-rexx */ context('Checking the Convert function') /* Unit tests */ check('rotate a by 0, same output as input' 'Convert("a", 0)',, 'Convert("a", 0)',, '=', 'a') check('rotate a by 1' 'Convert("a", 1)',, 'Convert("a", 1)',, '=', 'b') check('rotate a by 26, same output as input' 'Convert("a", 26)',, 'Convert("a", 26)',, '=', 'a') check('rotate m by 13' 'Convert("m", 13)',, 'Convert("m", 13)',, '=', 'z') check('rotate n by 13 with wrap around alphabet' 'Convert("n", 13)',, 'Convert("n", 13)',, '=', 'a') check('rotate capital letters' 'Convert("OMG", 5)',, 'Convert("OMG", 5)',, '=', 'TRL') check('rotate spaces' 'Convert("O M G", 5)',, 'Convert("O M G", 5)',, '=', 'T R L') check('rotate numbers' 'Convert("Testing 1 2 3 testing", 4)',, 'Convert("Testing 1 2 3 testing", 4)',, '=', 'Xiwxmrk 1 2 3 xiwxmrk') check('rotate punctuation' 'Convert("Let''s eat, Grandma!", 21)',, 'Convert("Let''s eat, Grandma!", 21)',, '=', "Gzo'n zvo, Bmviyhv!") check('rotate all letters' 'Convert("The quick brown fox jumps over the lazy dog.", 13)',, 'Convert("The quick brown fox jumps over the lazy dog.", 13)',, '=', 'Gur dhvpx oebja sbk whzcf bire gur ynml qbt.')
49
# Instructions Your task is to find the potential trees where you could build your tree house. The data company provides the data as grids that show the heights of the trees. The rows of the grid represent the east-west direction, and the columns represent the north-south direction. An acceptable tree will be the the largest in its row, while being the smallest in its column. A grid might not have any good trees at all. Or it might have one, or even several. Here is a grid that has exactly one candidate tree. 1 2 3 4 |----------- 1 | 9 8 7 8 2 | 5 3 2 4 <--- potential tree house at row 2, column 1, for tree with height 5 3 | 6 6 7 1 - Row 2 has values 5, 3, and 1. The largest value is 5. - Column 1 has values 9, 5, and 6. The smallest value is 5. So the point at `[2, 1]` (row: 2, column: 1) is a great spot for a tree house.
MatrixIsEmpty : ; return ARG(1) == 'MATRIX;0;0;' MatrixCreate : procedure if ARG(1) == '' then ; return 'MATRIX;0;0;' SEP = ',' ; parse arg matdata select when POS('\n', matdata) > 0 then datasep = '\n' when POS("0A"X, matdata) > 0 then datasep = "0A"X when POS(SEP, matdata) > 0 then datasep = SEP otherwise return 'MATRIX;1;' || WORDS(matdata) || ';' || STRIP(matdata) end rows = COUNTSTR(datasep, matdata) + 1 matdata = CHANGESTR(datasep, matdata, SEP) cols = WORDS(SUBSTR(matdata, 1, POS(SEP, matdata) - 1)) return 'MATRIX;' || rows || ';' || cols || ';' || SPACE(matdata) SaddlePoints : procedure parse arg matrix ; if MatrixIsEmpty(matrix) then ; return '' parse var matrix 'MATRIX;' rows ';' cols ';' data parse value GenerateMaxMinValues(matrix) , with maxValues ';' minValues saddlePoints = '' ; do r = 1 to rows parse var data row ',' data row = STRIP(row) do c = 1 to cols element = WORD(row, c) if element == WORD(maxValues, r) & element == WORD(minValues, c) then saddlePoints ||= r c '' end end return STRIP(saddlePoints) GenerateMaxMinValues : procedure parse value ARG(1) with 'MATRIX;' rows ';' cols ';' data maxrows = '' ; mincols = '' do r = 1 to rows parse var data row ',' data row = STRIP(row) ; rowmax = -1 do c = 1 to cols parse var row element row element = STRIP(element) column.r.c = element if element > rowmax then ; rowmax = element end maxrows ||= rowmax '' end do c = 1 to cols colmin = 999999 do r = 1 to rows if column.r.c < colmin then ; colmin = column.r.c end mincols ||= colmin '' end return STRIP(maxrows) ';' STRIP(mincols)
/* Unit Test Runner: t-rexx */ context('Checking the SaddlePoints function') /* Test Variables */ matrix_empty = MatrixCreate() matrix_sp_one = MatrixCreate("9 8 7, 5 3 2, 6 6 7") matrix_sp_zero = MatrixCreate("1 2 3, 3 1 2, 2 3 1") matrix_sp_multiple_col = MatrixCreate("4 5 4, 3 5 5, 1 5 4") matrix_sp_multiple_row = MatrixCreate("6 7 8, 5 5 5, 7 5 6") matrix_sp_bottom_right = MatrixCreate("8 7 9, 6 7 6, 3 2 5") matrix_sp_non_square = MatrixCreate("3 1 3, 3 2 4") matrix_sp_single_col = MatrixCreate("2, 1, 4, 1") matrix_sp_single_row = MatrixCreate("2 5 3 5") /* Unit tests */ check('Can identify single saddle point' 'SaddlePoints(matrix_sp_one)',, 'SaddlePoints(matrix_sp_one)',, '=', '2 1') check('Can identify that empty matrix has no saddle points' 'SaddlePoints(matrix_empty)',, 'SaddlePoints(matrix_empty)',, '=', '') check('Can identify lack of saddle points when there are none' 'SaddlePoints(matrix_sp_zero)',, 'SaddlePoints(matrix_sp_zero)',, '=', '') check('Can identify multiple saddle points in a column' 'SaddlePoints(matrix_sp_multiple_col)',, 'SaddlePoints(matrix_sp_multiple_col)',, '=', '1 2 2 2 3 2') check('Can identify multiple saddle points in a row' 'SaddlePoints(matrix_sp_multiple_row)',, 'SaddlePoints(matrix_sp_multiple_row)',, '=', '2 1 2 2 2 3') check('Can identify saddle point in bottom right corner' 'SaddlePoints(matrix_sp_bottom_right)',, 'SaddlePoints(matrix_sp_bottom_right)',, '=', '3 3') check('Can identify saddle points in a non square matrix' 'SaddlePoints(matrix_sp_non_square)',, 'SaddlePoints(matrix_sp_non_square)',, '=', '1 1 1 3') check('Can identify that saddle points in a single column matrix are those with the minimum value' 'SaddlePoints(matrix_sp_single_col)',, 'SaddlePoints(matrix_sp_single_col)',, '=', '2 1 4 1') check('Can identify that saddle points in a single row matrix are those with the maximum value' 'SaddlePoints(matrix_sp_single_row)',, 'SaddlePoints(matrix_sp_single_row)',, '=', '1 2 1 4')
50
# Instructions Your task is to compute a word's Scrabble score by summing the values of its letters. The letters are valued as follows: | Letter | Value | | ---------------------------- | ----- | | A, E, I, O, U, L, N, R, S, T | 1 | | D, G | 2 | | B, C, M, P | 3 | | F, H, V, W, Y | 4 | | K | 5 | | J, X | 8 | | Q, Z | 10 | For example, the word "cabbage" is worth 14 points: - 3 points for C - 1 point for A - 3 points for B - 3 points for B - 1 point for A - 2 points for G - 1 point for E
Score : procedure POINTS.A = 1 ; POINTS.B = 3 ; POINTS.C = 3 ; POINTS.D = 2 ; POINTS.E = 1 POINTS.F = 4 ; POINTS.G = 2 ; POINTS.H = 4 ; POINTS.I = 1 ; POINTS.J = 8 POINTS.K = 5 ; POINTS.L = 1 ; POINTS.M = 3 ; POINTS.N = 1 ; POINTS.O = 1 POINTS.P = 3 ; POINTS.Q = 10 ; POINTS.R = 1 ; POINTS.S = 1 ; POINTS.T = 1 POINTS.U = 1 ; POINTS.V = 4 ; POINTS.W = 4 ; POINTS.X = 8 ; POINTS.Y = 4 POINTS.Z = 10 parse upper arg input score = 0 do while input \= '' parse var input letter +1 input score = score + POINTS.letter end return score
/* Unit Test Runner: t-rexx */ context('Checking the Score function') /* Unit tests */ check('lowercase letter' 'Score("a")',, 'Score("a")',, '=', 1) check('uppercase letter' 'Score("A")',, 'Score("A")',, '=', 1) check('valuable letter' 'Score("f")',, 'Score("f")',, '=', 4) check('short word' 'Score("at")',, 'Score("at")',, '=', 2) check('short, valuable word' 'Score("zoo")',, 'Score("zoo")',, '=', 12) check('medium word' 'Score("street")',, 'Score("street")',, '=', 6) check('medium, valuable word' 'Score("quirky")',, 'Score("quirky")',, '=', 22) check('long, mixed-case word' 'Score("OxyphenButazone")',, 'Score("OxyphenButazone")',, '=', 41) check('english-like word' 'Score("pinata")',, 'Score("pinata")',, '=', 8) check('empty input' 'Score("")',, 'Score("")',, '=', 0) check('entire alphabet available' 'Score("abcdefghijklmnopqrstuvwxyz")',, 'Score("abcdefghijklmnopqrstuvwxyz")',, '=', 87)
51
# Instructions Your task is to convert a number between 1 and 31 to a sequence of actions in the secret handshake. The sequence of actions is chosen by looking at the rightmost five digits of the number once it's been converted to binary. Start at the right-most digit and move left. The actions for each number place are: ```plaintext 00001 = wink 00010 = double blink 00100 = close your eyes 01000 = jump 10000 = Reverse the order of the operations in the secret handshake. ``` Let's use the number `9` as an example: - 9 in binary is `1001`. - The digit that is farthest to the right is 1, so the first action is `wink`. - Going left, the next digit is 0, so there is no double-blink. - Going left again, the next digit is 0, so you leave your eyes open. - Going left again, the next digit is 1, so you jump. That was the last digit, so the final code is: ```plaintext wink, jump ``` Given the number 26, which is `11010` in binary, we get the following actions: - double blink - jump - reverse actions The secret handshake for 26 is therefore: ```plaintext jump, double blink ``` ~~~~exercism/note If you aren't sure what binary is or how it works, check out [this binary tutorial][intro-to-binary]. [intro-to-binary]: https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa ~~~~
Commands : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) == 0 then ; return '' RECSEP = ';' ; KEYSEP = ':' ; REVCMD_CODE = 16 ; codes = X2B(D2X(ARG(1), 2)) /* Orient code->command table depending on reverse code presence */ if BITAND(codes, X2B(D2X(REVCMD_CODE, 2))) \= 0 then cmdMap = '08:jump;04:close your eyes;02:double blink;01:wink' else cmdMap = '01:wink;02:double blink;04:close your eyes;08:jump' /* Build command list by parsing code->command table applying bit masks */ cmdStr = '' ; do while cmdMap \= '' parse value SPACE(cmdMap) with mask (KEYSEP) cmd (RECSEP) cmdMap if BITAND(codes, X2B(D2X(mask, 2))) \= 0 then ; cmdStr ||= RECSEP || cmd end return STRIP(cmdStr, 'L', RECSEP)
/* Unit Test Runner: t-rexx */ context('Checking the Commands function') /* Unit tests */ check('wink for 1' 'Commands(1)',, 'Commands(1)',, '=', 'wink') check('double blink for 10' 'Commands(2)',, 'Commands(2)',, '=', 'double blink') check('close your eyes for 100' 'Commands(4)',, 'Commands(4)',, '=', 'close your eyes') check('jump for 1000' 'Commands(8)',, 'Commands(8)',, '=', 'jump') check('combine two actions' 'Commands(3)',, 'Commands(3)',, '=', 'wink;double blink') check('reverse two actions' 'Commands(19)',, 'Commands(19)',, '=', 'double blink;wink') check('reversing one action gives the same action' 'Commands(24)',, 'Commands(24)',, '=', 'jump') check('reversing no actions still gives no actions' 'Commands(16)',, 'Commands(16)',, '=', '') check('all possible actions' 'Commands(15)',, 'Commands(15)',, '=', 'wink;double blink;close your eyes;jump') check('reverse all possible actions' 'Commands(31)',, 'Commands(31)',, '=', 'jump;close your eyes;double blink;wink') check('do nothing for zero' 'Commands(0)',, 'Commands(0)',, '=', '')
52
# Instructions Given a string of digits, output all the contiguous substrings of length `n` in that string in the order that they appear. For example, the string "49142" has the following 3-digit series: - "491" - "914" - "142" And the following 4-digit series: - "4914" - "9142" And if you ask for a 6-digit series from a 5-digit string, you deserve whatever you get. Note that these series are only required to occupy *adjacent positions* in the input; the digits need not be *numerically consecutive*.
Slices : procedure if ARG() \= 2 | \DATATYPE(ARG(1), 'N') | STRIP(ARG(2)) == '' then ; return '' parse value ARG(1) ARG(2) LENGTH(ARG(2)) 1 1 '', with reqlen input actlen pos stepsize output if reqlen < 1 | actlen < reqlen then ; return '' original = input do while pos <= actlen parse var input =(pos) slice +(reqlen) . if LENGTH(slice) < reqlen then ; leave output ||= slice '' pos += stepsize ; input = original end return STRIP(output, 'T')
/* Unit Test Runner: t-rexx */ context('Checking the Slices function') /* Unit tests */ check('slices of one from one' 'Slices(1, "1")',, 'Slices(1, "1")',, '=', '1') check('slices of one from two' 'Slices(1, "12")',, 'Slices(1, "12")',, '=', '1 2') check('slices of two' 'Slices(2, "35")',, 'Slices(2, "35")',, '=', '35') check('slices of two overlap' 'Slices(2, "9142")',, 'Slices(2, "9142")',, '=', '91 14 42') check('slices can include duplicates' 'Slices(3, "777777")',, 'Slices(3, "777777")',, '=', '777 777 777 777') check('slices of a long series' 'Slices(5, "918493904243")',, 'Slices(5, "918493904243")',, '=', '91849 18493 84939 49390 93904 39042 90424 04243') check('slice length is too large' 'Slices(6, "12345")',, 'Slices(6, "12345")',, '=', '') check('slice length is way too large' 'Slices(30, "12345")',, 'Slices(30, "12345")',, '=', '') check('slice length cannot be zero' 'Slices(0, "12345")',, 'Slices(0, "12345")',, '=', '') check('slice length cannot be negative' 'Slices(-1, "12345")',, 'Slices(-1, "12345")',, '=', '') check('empty series is invalid' 'Slices(1, "")',, 'Slices(1, "")',, '=', '')
53
# Instructions Use the Sieve of Eratosthenes to find all the primes from 2 up to a given number. The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. It does not use any division or remainder operation. Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit]) The algorithm consists of repeating the following over and over: - take the next available unmarked number in your list (it is prime) - mark all the multiples of that number (they are not prime) Repeat until you have processed each number in your range. When the algorithm terminates, all the numbers in the list that have not been marked are prime. [This wikipedia article][eratosthenes] has a useful graphic that explains the algorithm. Notice that this is a very specific algorithm, and the tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes. A good first test is to check that you do not use division or remainder operations (div, /, mod or % depending on the language). [eratosthenes]: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Sieve : procedure if ARG() \= 1 | \DATATYPE(ARG(1), 'N') | ARG(1) < 2 then ; return '' parse value ARG(1) with limit primes sieve.0 = limit ; do i = 1 to limit ; sieve.i = 1 ; end do i = 2 to limit if \sieve.i then ; iterate primes ||= i '' do j = (2 * i) to limit by i ; sieve.j = 0 ; end end return STRIP(primes, 'T')
/* Unit Test Runner: t-rexx */ context('Checking the Sieve function') /* Test Options */ numeric digits 6 /* Test Variables */ primes = '2 3 5 7 11 13 17 19 23 29 31 37 41 43' , '47 53 59 61 67 71 73 79 83 89 97 101 103 107' , '109 113 127 131 137 139 149 151 157 163 167 173 179 181' , '191 193 197 199 211 223 227 229 233 239 241 251 257 263' , '269 271 277 281 283 293 307 311 313 317 331 337 347 349' , '353 359 367 373 379 383 389 397 401 409 419 421 431 433' , '439 443 449 457 461 463 467 479 487 491 499 503 509 521' , '523 541 547 557 563 569 571 577 587 593 599 601 607 613' , '617 619 631 641 643 647 653 659 661 673 677 683 691 701' , '709 719 727 733 739 743 751 757 761 769 773 787 797 809' , '811 821 823 827 829 839 853 857 859 863 877 881 883 887' , '907 911 919 929 937 941 947 953 967 971 977 983 991 997' /* Unit tests */ check('no primes under two' 'Sieve(1)',, 'Sieve(1)',, '=', '') check('find first prime' 'Sieve(2)',, 'Sieve(2)',, '=', '2') check('find primes up to 10' 'Sieve(10)',, 'Sieve(10)',, '=', '2 3 5 7') check('limit is prime' 'Sieve(13)',, 'Sieve(13)',, '=', '2 3 5 7 11 13') check('find primes up to 1000' 'Sieve(1000)',, 'Sieve(1000)',, '=', primes)
54
# Instructions Implement a simple shift cipher like Caesar and a more secure substitution cipher. ## Step 1 "If he had anything confidential to say, he wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others." —Suetonius, Life of Julius Caesar Ciphers are very straight-forward algorithms that allow us to render text less readable while still allowing easy deciphering. They are vulnerable to many forms of cryptanalysis, but Caesar was lucky that his enemies were not cryptanalysts. The Caesar Cipher was used for some messages from Julius Caesar that were sent afield. Now Caesar knew that the cipher wasn't very good, but he had one ally in that respect: almost nobody could read well. So even being a couple letters off was sufficient so that people couldn't recognize the few words that they did know. Your task is to create a simple shift cipher like the Caesar Cipher. This image is a great example of the Caesar Cipher: ![Caesar Cipher][img-caesar-cipher] For example: Giving "iamapandabear" as input to the encode function returns the cipher "ldpdsdqgdehdu". Obscure enough to keep our message secret in transit. When "ldpdsdqgdehdu" is put into the decode function it would return the original "iamapandabear" letting your friend read your original message. ## Step 2 Shift ciphers quickly cease to be useful when the opposition commander figures them out. So instead, let's try using a substitution cipher. Try amending the code to allow us to specify a key and use that for the shift distance. Here's an example: Given the key "aaaaaaaaaaaaaaaaaa", encoding the string "iamapandabear" would return the original "iamapandabear". Given the key "ddddddddddddddddd", encoding our string "iamapandabear" would return the obscured "ldpdsdqgdehdu" In the example above, we've set a = 0 for the key value. So when the plaintext is added to the key, we end up with the same message coming out. So "aaaa" is not an ideal key. But if we set the key to "dddd", we would get the same thing as the Caesar Cipher. ## Step 3 The weakest link in any cipher is the human being. Let's make your substitution cipher a little more fault tolerant by providing a source of randomness and ensuring that the key contains only lowercase letters. If someone doesn't submit a key at all, generate a truly random key of at least 100 lowercase characters in length. ## Extensions Shift ciphers work by making the text slightly odd, but are vulnerable to frequency analysis. Substitution ciphers help that, but are still very vulnerable when the key is short or if spaces are preserved. Later on you'll see one solution to this problem in the exercise "crypto-square". If you want to go farther in this field, the questions begin to be about how we can exchange keys in a secure way. Take a look at [Diffie-Hellman on Wikipedia][dh] for one of the first implementations of this scheme. [img-caesar-cipher]: https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Caesar_cipher_left_shift_of_3.svg/320px-Caesar_cipher_left_shift_of_3.svg.png [dh]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
Encode : ; return Transform(ARG(1), ARG(2), "E") Decode : ; return Transform(ARG(1), ARG(2), "D") GetIndex : ; return ((ARG(1) + (ARG(2) - 1)) // ARG(2)) + 1 Transform : procedure parse value STRIP(ARG(1)) || ';' || ARG(2) || ';' || ARG(3) || , ';' || 'abcdefghijklmnopqrstuvwxyz' , with key ';' text ';' direction ';' alphabet if VERIFY(key, alphabet, 'N') > 0 then ; return text if VERIFY(direction, 'DE', 'N') > 0 then ; return text parse value LENGTH(key) LENGTH(text) '' , with keylen textlen output encodelen = textlen do i = 1 to encodelen parse value SUBSTR(text, i, 1) SUBSTR(key, GetIndex(i, keylen), 1) , with c k if direction == 'E' then z = SUBSTR(alphabet, GetIndex(POS(c, alphabet) + POS(k, alphabet) - 1, 26), 1) else z = SUBSTR(alphabet, GetIndex(POS(c, alphabet) - POS(k, alphabet) + 1, 26), 1) output ||= z end return output GenerateKey : procedure parse value STRIP(ARG(1)) || ';' || C2D('a') || ';' || C2D('z') || ';', with keysize ';' ascii_a ';' ascii_z ';' key if \DATATYPE(keysize, 'N') | keysize < 1 then ; keysize = 100 do keysize ; key ||= D2C(RANDOM(ascii_a, ascii_z)) ; end return STRIP(key)
/* Unit Test Runner: t-rexx */ context('Checking the Simple Cipher functions') /* Test Variables */ key_1_length = LENGTH(GenerateKey()) key_2 = GenerateKey() key_2_islowercase = VERIFY(key_2, 'abcdefghijklmnopqrstuvwxyz', 'N') > 0 key_3_4 = GenerateKey() plaintext_3_4 = 'aaaaaaaaaa' encoded_3_4 = Encode(key_3_4, plaintext_3_4) decoded_3_4 = Decode(key_3_4, encoded_3_4) key_5 = GenerateKey() plaintext_5 = 'zaaohgkaha' key_6 = 'abcdefghij' plaintext_6 = 'aaaaaaaaaa' expected_6 = 'abcdefghij' key_7 = 'abcdefghij' plaintext_7 = 'abcdefghij' expected_7 = 'aaaaaaaaaa' key_8 = 'abcdefghij' plaintext_8 = 'abcdefghij' expected_8 = 'abcdefghij' key_9 = 'iamapandabear' plaintext_9 = 'iamapandabear' expected_9 = 'qayaeaagaciai' key_10 = 'abcdefghij' plaintext_10 = 'zzzzzzzzzz' expected_10 = 'zabcdefghi' key_11 = 'abcdefghij' plaintext_11 = 'zabcdefghi' expected_11 = 'zzzzzzzzzz' key_12 = 'abc' plaintext_12 = 'iamapandabear' expected_12 = 'iboaqcnecbfcr' key_13 = 'abc' plaintext_13 = 'iboaqcnecbfcr' expected_13 = 'iamapandabear' /* Unit tests */ check('Can generate a random key' 'GenerateKey()',, 'GenerateKey()', key_1_length, '=', 100) check('Random key cipher -> Key is made only of lowercase letters' 'GenerateKey()',, 'GenerateKey()', key_2_islowercase, '=', 0) check('Random key cipher -> Can encode' 'Encode(key_3_4, plaintext_3_4)',, 'Encode(key_3_4, plaintext_3_4)',, '=', encoded_3_4) check('Random key cipher -> Can decode' 'Decode(key_3_4, encoded_3_4)',, 'Decode(key_3_4, encoded_3_4)',, '=', plaintext_3_4) check('Random key cipher -> Is reversible. i.e., decoding an encoded result yields original plaintext' 'Decode(key_5, Encode(key_5, plaintext_5))',, 'Decode(key_5, Encode(key_5, plaintext_5))',, '=', plaintext_5) check('Substitution cipher -> Can encode' 'Encode(key_6, plaintext_6)',, 'Encode(key_6, plaintext_6)',, '=', expected_6) check('Substitution cipher -> Can decode' 'Decode(key_7, plaintext_7)',, 'Decode(key_7, plaintext_7)',, '=', expected_7) check('Substitution cipher -> Is reversible. i.e., decoding an encoded result yields original plaintext' 'Decode(key_8, Encode(key_8, plaintext_8))',, 'Decode(key_8, Encode(key_8, plaintext_8))',, '=', expected_8) check('Substitution cipher -> Can double shift encode' 'Encode(key_9, plaintext_9)',, 'Encode(key_9, plaintext_9)',, '=', expected_9) check('Substitution cipher -> Can wrap on encode' 'Encode(key_10, plaintext_10)',, 'Encode(key_10, plaintext_10)',, '=', expected_10) check('Substitution cipher -> Can wrap on decode' 'Decode(key_11, plaintext_11)',, 'Decode(key_11, plaintext_11)',, '=', expected_11) check('Substitution cipher -> Can encode messages longer than the key' 'Encode(key_12, plaintext_12)',, 'Encode(key_12, plaintext_12)',, '=', expected_12) check('Substitution cipher -> Can decode messages longer than the key' 'Decode(key_13, plaintext_13)',, 'Decode(key_13, plaintext_13)',, '=', expected_13)
55
# Instructions Given an age in seconds, calculate how old someone would be on: - Mercury: orbital period 0.2408467 Earth years - Venus: orbital period 0.61519726 Earth years - Earth: orbital period 1.0 Earth years, 365.25 Earth days, or 31557600 seconds - Mars: orbital period 1.8808158 Earth years - Jupiter: orbital period 11.862615 Earth years - Saturn: orbital period 29.447498 Earth years - Uranus: orbital period 84.016846 Earth years - Neptune: orbital period 164.79132 Earth years So if you were told someone were 1,000,000,000 seconds old, you should be able to say that they're 31.69 Earth-years old. If you're wondering why Pluto didn't make the cut, go watch [this YouTube video][pluto-video]. Note: The actual length of one complete orbit of the Earth around the sun is closer to 365.256 days (1 sidereal year). The Gregorian calendar has, on average, 365.2425 days. While not entirely accurate, 365.25 is the value used in this exercise. See [Year on Wikipedia][year] for more ways to measure a year. [pluto-video]: https://www.youtube.com/watch?v=Z_2gbGXzFbs [year]: https://en.wikipedia.org/wiki/Year#Summary
AgeOn : procedure orbitmap = 'MERCURY:0.2408467 VENUS:0.61519726 EARTH:1.0 MARS:1.8808158' , 'JUPITER:11.862615 SATURN:29.447498 URANUS:84.016846' , 'NEPTUNE:164.79132' if ARG() \= 2 | ARG(1) == '' | \DATATYPE(ARG(2), 'N') then ; return -1 parse upper arg planet, seconds pos = POS(planet, orbitmap) ; if pos < 1 then ; return -1 parse value SUBSTR(orbitmap, pos) with . ':' period . return FORMAT(seconds / 31557600 / period,, 2)
/* Unit Test Runner: t-rexx */ context('Checking the AgeOn function') /* Unit tests */ check('age on Earth' 'AgeOn("Earth", 1000000000)',, 'AgeOn("Earth", 1000000000)',, '=', 31.69) check('age on Mercury' 'AgeOn("Mercury", 2134835688)',, 'AgeOn("Mercury", 2134835688)',, '=', 280.88) check('age on Venus' 'AgeOn("Venus", 189839836)',, 'AgeOn("Venus", 189839836)',, '=', 9.78) check('age on Mars' 'AgeOn("Mars", 2129871239)',, 'AgeOn("Mars", 2129871239)',, '=', 35.88) check('age on Jupiter' 'AgeOn("Jupiter", 901876382)',, 'AgeOn("Jupiter", 901876382)',, '=', 2.41) check('age on Saturn' 'AgeOn("Saturn", 2000000000)',, 'AgeOn("Saturn", 2000000000)',, '=', 2.15) check('age on Uranus' 'AgeOn("Uranus", 1210123456)',, 'AgeOn("Uranus", 1210123456)',, '=', 0.46) check('age on Neptune' 'AgeOn("Neptune", 1821023456)',, 'AgeOn("Neptune", 1821023456)',, '=', 0.35) check('invalid planet causes error' 'AgeOn("Pluto", 680804807)',, 'AgeOn("Pluto", 680804807)',, '=', -1)
56
# Instructions Given a natural radicand, return its square root. Note that the term "radicand" refers to the number for which the root is to be determined. That is, it is the number under the root symbol. Check out the Wikipedia pages on [square root][square-root] and [methods of computing square roots][computing-square-roots]. Recall also that natural numbers are positive real whole numbers (i.e. 1, 2, 3 and up). [square-root]: https://en.wikipedia.org/wiki/Square_root [computing-square-roots]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
SquareRoot : procedure parse value ABS(ARG(1)) 1 0 with x r r1 if x == 0 then ; return 0 do while r \= r1 ; parse value r (x / r + r) / 2 with r1 r ; end return r
/* Unit Test Runner: t-rexx */ context('Checking the SquareRoot function') /* Unit tests */ check('root of 1' 'SquareRoot(1)',, 'SquareRoot(1)',, '=', 1) check('root of 4' 'SquareRoot(4)',, 'SquareRoot(4)',, '=', 2) check('root of 25' 'SquareRoot(25)',, 'SquareRoot(25)',, '=', 5) check('root of 81''SquareRoot(81)',, 'SquareRoot(81)',, '=', 9) check('root of 196' 'SquareRoot(196)',, 'SquareRoot(196)',, '=', 14) check('root of 65025' 'SquareRoot(65025)',, 'SquareRoot(65025)',, '=', 255)
57
# Instructions Implement the `keep` and `discard` operation on collections. Given a collection and a predicate on the collection's elements, `keep` returns a new collection containing those elements where the predicate is true, while `discard` returns a new collection containing those elements where the predicate is false. For example, given the collection of numbers: - 1, 2, 3, 4, 5 And the predicate: - is the number even? Then your keep operation should produce: - 2, 4 While your discard operation should produce: - 1, 3, 5 Note that the union of keep and discard is all the elements. The functions may be called `keep` and `discard`, or they may need different names in order to not clash with existing functions or concepts in your language. ## Restrictions Keep your hands off that filter/reject/whatchamacallit functionality provided by your standard library! Solve this one yourself using other basic tools instead.
Keep : procedure parse arg input, function output = '' ; do while input \= '' parse var input token input cmd = 'isTrue =' function || '(' || ''''token'''' || ')' ; interpret cmd if isTrue then ; output ||= token '' end return STRIP(output, 'T') Discard : procedure parse arg input, function output = '' ; do while input \= '' parse var input token input cmd = 'isTrue =' function || '(' || ''''token'''' || ')' ; interpret cmd if \isTrue then ; output ||= token '' end return STRIP(output, 'T')
/* Unit Test Runner: t-rexx */ context('Checking the Keep and Discard functions') /* Unit tests */ check('empty keep test' 'Keep("", "LessThan10")',, 'Keep("", "LessThan10")',, '=', '') check('keep everything test' 'Keep("1 2 3", "LessThan10")',, 'Keep("1 2 3", "LessThan10")',, '=', '1 2 3') check('keep first last test' 'Keep("1 2 3", "IsOdd")',, 'Keep("1 2 3", "IsOdd")',, '=', '1 3') check('keep nothin test' 'Keep("1 3 5 7", "IsEven")',, 'Keep("1 3 5 7", "IsEven")',, '=', '') check('keep neither first nor last test' 'Keep("1 2 3", "IsEven")',, 'Keep("1 2 3", "IsEven")',, '=', '2') check('keep strings test' 'Keep("apple zebra banana zombies cheri zealot", "StartsWithZ")',, 'Keep("apple zebra banana zombies cheri zealot", "StartsWithZ")',, '=', 'zebra zombies zealot') check('empty discard test' 'Discard("", "LessThan10")',, 'Discard("", "LessThan10")',, '=', '') check('discard everything test' 'Discard("1 2 3", "LessThan10")',, 'Discard("1 2 3", "LessThan10")',, '=', '') check('discard first and last test' 'Discard("1 2 3", "IsOdd")',, 'Discard("1 2 3", "IsOdd")',, '=', '2') check('discard nothing test' 'Discard("1 3 5 7", "IsEven")',, 'Discard("1 3 5 7", "IsEven")',, '=', '1 3 5 7') check('discard neither first nor last test' 'Discard("1 2 3", "IsEven")',, 'Discard("1 2 3", "IsEven")',, '=', '1 3') check('discard strings test' 'Discard("apple zebra banana zombies cheri zealot", "StartsWithZ")',, 'Discard("apple zebra banana zombies cheri zealot", "StartsWithZ")',, '=', 'apple banana cheri')
58
# Instructions Given any two lists `A` and `B`, determine if: - List `A` is equal to list `B`; or - List `A` contains list `B` (`A` is a superlist of `B`); or - List `A` is contained by list `B` (`A` is a sublist of `B`); or - None of the above is true, thus lists `A` and `B` are unequal Specifically, list `A` is equal to list `B` if both lists have the same values in the same order. List `A` is a superlist of `B` if `A` contains a sub-sequence of values equal to `B`. List `A` is a sublist of `B` if `B` contains a sub-sequence of values equal to `A`. Examples: - If `A = []` and `B = []` (both lists are empty), then `A` and `B` are equal - If `A = [1, 2, 3]` and `B = []`, then `A` is a superlist of `B` - If `A = []` and `B = [1, 2, 3]`, then `A` is a sublist of `B` - If `A = [1, 2, 3]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B` - If `A = [3, 4, 5]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B` - If `A = [3, 4]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B` - If `A = [1, 2, 3]` and `B = [1, 2, 3]`, then `A` and `B` are equal - If `A = [1, 2, 3, 4, 5]` and `B = [2, 3, 4]`, then `A` is a superlist of `B` - If `A = [1, 2, 4]` and `B = [1, 2, 3, 4, 5]`, then `A` and `B` are unequal - If `A = [1, 2, 3]` and `B = [1, 3, 2]`, then `A` and `B` are unequal
ClassifyList : procedure parse value SPACE(ARG(1)) || ';' || SPACE(ARG(2)) , with L ';' R select when IsEqual(L, R) then ; listType = 'EQUAL' when IsSublist(L, L, R) then ; listType = 'SUBLIST' when IsSublist(R, R, L) then ; listType = 'SUPERLIST' otherwise listType = 'UNEQUAL' end return listType Head : ; return WORD(ARG(1), 1) Tail : ; return DELWORD(ARG(1), 1, 1) IsEqual : procedure parse arg L, R if L == '' & R == '' then ; return 1 if Head(L) == Head(R) then ; return IsEqual(Tail(L), Tail(R)) return 0 IsSublist : procedure parse arg S, L, R if L == '' then ; return 1 if L \= '' & R == '' then ; return 0 if Head(L) == Head(R) then ; return IsSublist(S, Tail(L), Tail(R)) if Head(S) == Head(R) then ; return IsSublist(S, Tail(S), R) return IsSublist(S, S, Tail(R))
/* Unit Test Runner: t-rexx */ context('Checking the ClassifyList function') /* Unit tests */ check('empty lists' 'ClassifyList("", "")',, 'ClassifyList("", "")',, '=', 'EQUAL') check('empty list within non empty list' 'ClassifyList("", "1 2 3")',, 'ClassifyList("", "1 2 3")',, '=', 'SUBLIST') check('non empty list contains empty list' 'ClassifyList("1 2 3", "")',, 'ClassifyList("1 2 3", "")',, '=', 'SUPERLIST') check('list EQUALs itself' 'ClassifyList("1 2 3", "1 2 3")',, 'ClassifyList("1 2 3", "1 2 3")',, '=', 'EQUAL') check('different lists' 'ClassifyList("1 2 3", "2 3 4")',, 'ClassifyList("1 2 3", "2 3 4")',, '=', 'UNEQUAL') check('false start' 'ClassifyList("1 2 5", "0 1 2 3 1 2 5 6")',, 'ClassifyList("1 2 5", "0 1 2 3 1 2 5 6")',, '=', 'SUBLIST') check('consecutive' 'ClassifyList("1 1 2", "0 1 1 1 2 1 2")',, 'ClassifyList("1 1 2", "0 1 1 1 2 1 2")',, '=', 'SUBLIST') check('SUBLIST at start' 'ClassifyList("0 1 2", "0 1 2 3 4 5")',, 'ClassifyList("0 1 2", "0 1 2 3 4 5")',, '=', 'SUBLIST') check('SUBLIST in middle' 'ClassifyList("2 3 4", "0 1 2 3 4 5")',, 'ClassifyList("2 3 4", "0 1 2 3 4 5")',, '=', 'SUBLIST') check('SUBLIST at end' 'ClassifyList("3 4 5", "0 1 2 3 4 5")',, 'ClassifyList("3 4 5", "0 1 2 3 4 5")',, '=', 'SUBLIST') check('at start of SUPERLIST' 'ClassifyList("0 1 2 3 4 5", "0 1 2")',, 'ClassifyList("0 1 2 3 4 5", "0 1 2")',, '=', 'SUPERLIST') check('in middle of SUPERLIST' 'ClassifyList("0 1 2 3 4 5", "2 3")',, 'ClassifyList("0 1 2 3 4 5", "2 3")',, '=', 'SUPERLIST') check('at end of SUPERLIST' 'ClassifyList("0 1 2 3 4 5", "3 4 5")',, 'ClassifyList("0 1 2 3 4 5", "3 4 5")',, '=', 'SUPERLIST') check('first list missing element from second list' 'ClassifyList("1 3", "1 2 3")',, 'ClassifyList("1 3", "1 2 3")',, '=', 'UNEQUAL') check('second list missing element from first list' 'ClassifyList("1 2 3", "1 3")',, 'ClassifyList("1 2 3", "1 3")',, '=', 'UNEQUAL') check('first list missing additional digits from second list' 'ClassifyList("1 2", "1 22")',, 'ClassifyList("1 2", "1 22")',, '=', 'UNEQUAL') check('order matters to a list' 'ClassifyList("1 2 3", "3 2 1")',, 'ClassifyList("1 2 3", "3 2 1")',, '=', 'UNEQUAL') check('same digits but different numbers' 'ClassifyList("1 0 1", "10 1")',, 'ClassifyList("1 0 1", "10 1")',, '=', 'UNEQUAL')
59
# Instructions Your task is to write the code that calculates the energy points that get awarded to players when they complete a level. The points awarded depend on two things: - The level (a number) that the player completed. - The base value of each magical item collected by the player during that level. The energy points are awarded according to the following rules: 1. For each magical item, take the base value and find all the multiples of that value that are less than the level number. 2. Combine the sets of numbers. 3. Remove any duplicates. 4. Calculate the sum of all the numbers that are left. Let's look at an example: **The player completed level 20 and found two magical items with base values of 3 and 5.** To calculate the energy points earned by the player, we need to find all the unique multiples of these base values that are less than level 20. - Multiples of 3 less than 20: `{3, 6, 9, 12, 15, 18}` - Multiples of 5 less than 20: `{5, 10, 15}` - Combine the sets and remove duplicates: `{3, 5, 6, 9, 10, 12, 15, 18}` - Sum the unique multiples: `3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 = 78` - Therefore, the player earns **78** energy points for completing level 20 and finding the two magical items with base values of 3 and 5.
Sum : procedure parse value ARG(1) || ';' || ARG(2) || ';' || 0 , with factors ';' limit ';' sum if VERIFY(factors, ' 0123456789', 'N') > 0 | , \DATATYPE(limit, 'N') | limit < 2 then ; return 0 limit -= 1 ; do i = 1 to limit do while factors \= '' parse var factors factor factors if factor < 1 then ; iterate if i // factor == 0 then do ; sum += i ; leave ; end end factors = ARG(1) end return sum
/* Unit Test Runner: t-rexx */ context('Checking the Sum function') /* Unit tests */ check('no multiples within limit' 'Sum("3 5", 1)',, 'Sum("3 5", 1)',, '=', 0) check('one factor has multiples within limit' 'Sum("3 5", 4)',, 'Sum("3 5", 4)',, '=', 3) check('more than one multiple within limit' 'Sum("3", 7)',, 'Sum("3", 7)',, '=', 9) check('more than one factor with multiples within limit' 'Sum("3 5", 10)',, 'Sum("3 5", 10)',, '=', 23) check('each multiple is only counted once' 'Sum("3 5", 100)',, 'Sum("3 5", 100)',, '=', 2318) check('a much larger limit' 'Sum("3 5", 1000)',, 'Sum("3 5", 1000)',, '=', 233168) check('three factors' 'Sum("7 13 17", 20)',, 'Sum("7 13 17", 20)',, '=', 51) check('factors not relatively prime' 'Sum("4 6", 15)',, 'Sum("4 6", 15)',, '=', 30) check('some pairs of factors relatively prime and some not' 'Sum("5 6 8", 150)',, 'Sum("5 6 8", 150)',, '=', 4419) check('one factor is a multiple of another' 'Sum("5 25", 51)',, 'Sum("5 25", 51)',, '=', 275) check('much larger factors' 'Sum("43 47", 10000)',, 'Sum("43 47", 10000)',, '=', 2203160) check('all numbers are multiples of 1' 'Sum("1", 100)',, 'Sum("1", 100)',, '=', 4950) check('no factors means an empty sum' 'Sum("", 10000)',, 'Sum("", 10000)',, '=', 0) check('the only multiple of 0 is 0' 'Sum("0", 1)',, 'Sum("0", 1)',, '=', 0) check('the factor 0 does not affect the sum of multiples of other factors' 'Sum("0 3", 4)',, 'Sum("0 3", 4)',, '=', 3) check('solutions using include-exclude must extend to cardinality greater than 3' 'Sum("2 3 5 7 11", 10000)',, 'Sum("2 3 5 7 11", 10000)',, '=', 39614537)
60
# Instructions Given an input text output it transposed. Roughly explained, the transpose of a matrix: ```text ABC DEF ``` is given by: ```text AD BE CF ``` Rows become columns and columns become rows. See [transpose][]. If the input has rows of different lengths, this is to be solved as follows: - Pad to the left with spaces. - Don't pad to the right. Therefore, transposing this matrix: ```text ABC DE ``` results in: ```text AD BE C ``` And transposing: ```text AB DEF ``` results in: ```text AD BE F ``` In general, all characters from the input should also be present in the transposed output. That means that if a column in the input text contains only spaces on its bottom-most row(s), the corresponding output row should contain the spaces in its right-most column(s). [transpose]: https://en.wikipedia.org/wiki/Transpose
Transpose : procedure if ARG(1) == '' then ; return '' NEWLINE = ARG(2); if ARG(2) == '' then ; NEWLINE = '\n' SEP = ';' ; input = CHANGESTR(NEWLINE, ARG(1), SEP) cols = -1 ; rows.0 = COUNTSTR(SEP, input) + 1 do row = 1 to rows.0 parse var input rowdata (SEP) input cols = MAX(cols, LENGTH(rowdata)) rows.row = rowdata end output = '' ; do col = 1 to cols do row = 1 to rows.0 output ||= SUBSTR(rows.row, col, 1) end output ||= SEP end return STRIP(CHANGESTR(SEP, STRIP(output, 'T', SEP), NEWLINE))
/* Unit Test Runner: t-rexx */ context('Checking the Transpose function') /* Unit tests */ check('empty string' 'Transpose("")',, 'Transpose("")',, '=', '') check('two characters in a row' 'Transpose("A1")',, 'Transpose("A1")',, '=', 'A\n1') check('two characters in a column' 'Transpose("A\n1")',, 'Transpose("A\n1")',, '=', 'A1') check('simple' 'Transpose("ABC\n123")',, 'Transpose("ABC\n123")',, '=', 'A1\nB2\nC3') check('single line' 'Transpose("Single line.")',, 'Transpose("Single line.")',, '=', 'S\ni\nn\ng\nl\ne\n \nl\ni\nn\ne\n.') check('first line longer than second line' 'Transpose("The fourth line.\nThe fifth line.")',, 'Transpose("The fourth line.\nThe fifth line.")',, '=', 'TT\nhh\nee\n \nff\noi\nuf\nrt\nth\nh \n l\nli\nin\nne\ne.\n.') check('second line longer than first line' 'Transpose("The first line.\nThe second line.")',, 'Transpose("The first line.\nThe second line.")',, '=', 'TT\nhh\nee\n \nfs\nie\nrc\nso\ntn\n d\nl \nil\nni\nen\n.e\n .') check('mixed line length' 'Transpose("The longest line.\nA long line.\nA longer line.\nA line.")',, 'Transpose("The longest line.\nA long line.\nA longer line.\nA line.")',, '=', 'TAAA\nh \nelll\n ooi\nlnnn\nogge\nn e.\nglr \nei \nsnl \ntei \n .n \nl e \ni . \nn \ne \n.') check('square' 'Transpose("HEART\nEMBER\nABUSE\nRESIN\nTREND")',, 'Transpose("HEART\nEMBER\nABUSE\nRESIN\nTREND")',, '=', 'HEART\nEMBER\nABUSE\nRESIN\nTREND') check('rectangle' 'Transpose("FRACTURE\nOUTLINED\nBLOOMING\nSEPTETTE")',, 'Transpose("FRACTURE\nOUTLINED\nBLOOMING\nSEPTETTE")',, '=', 'FOBS\nRULE\nATOP\nCLOT\nTIME\nUNIT\nRENT\nEDGE') check('triangle' 'Transpose("T\nEE\nAAA\nSSSS\nEEEEE\nRRRRRR")',, 'Transpose("T\nEE\nAAA\nSSSS\nEEEEE\nRRRRRR")',, '=', 'TEASER\n EASER\n ASER\n SER\n ER\n R') check('jagged triangle' 'Transpose("11\n2\n3333\n444\n555555\n66666")',, 'Transpose("11\n2\n3333\n444\n555555\n66666")',, '=', '123456\n1 3456\n 3456\n 3 56\n 56\n 5')
61
# Instructions Determine if a triangle is equilateral, isosceles, or scalene. An _equilateral_ triangle has all three sides the same length. An _isosceles_ triangle has at least two sides the same length. (It is sometimes specified as having exactly two sides the same length, but for the purposes of this exercise we'll say at least two.) A _scalene_ triangle has all sides of different lengths. ## Note For a shape to be a triangle at all, all sides have to be of length > 0, and the sum of the lengths of any two sides must be greater than or equal to the length of the third side. In equations: Let `a`, `b`, and `c` be sides of the triangle. Then all three of the following expressions must be true: ```text a + b ≥ c b + c ≥ a a + c ≥ b ``` See [Triangle Inequality][triangle-inequality] [triangle-inequality]: https://en.wikipedia.org/wiki/Triangle_inequality
IsTriangleType : procedure /* Validate input values */ if ARG() \= 4 then ; return -1 parse arg sideA, sideB, sideC, triangleType if \DATATYPE(sideA, 'N') | \DATATYPE(sideB, 'N') | \DATATYPE(sideC, 'N'), then ; return -1 /* Determine degeneracy */ if sideA < 1 | sideB < 1 | sideC < 1 then ; return -1 if sideA + sideB <= sideC | sideA + sideC <= sideB | sideB + sideC <= sideA, then ; return -1 /* Evaluate triangle type */ isEquilateral = (sideA == sideB & sideA == sideC) isIsosceles = (sideA == sideB | sideA == sideC | sideB == sideC) isScalene = (sideA \= sideB & sideA \= sideC & sideB \= sideC) /* Report criterion match */ parse upper var triangleType triangleType select when triangleType == 'EQUILATERAL' then isTriangle = isEquilateral when triangleType == 'ISOSCELES' then isTriangle = isIsosceles when triangleType == 'SCALENE' then isTriangle = isScalene otherwise return -1 end return isTriangle
/* Unit Test Runner: t-rexx */ context('Checking the IsTriangleType function') /* Unit tests */ check('equilateral triangle - all side are equal' 'IsTriangleType(2, 2, 2, "equilateral")',, 'IsTriangleType(2, 2, 2, "equilateral")',, '=', 1) check('equilateral triangle - any side is unequal' 'IsTriangleType(4, 4, 6, "equilateral")',, 'IsTriangleType(4, 4, 6, "equilateral")',, '=', 0) check('equilateral triangle - no sides are equal' 'IsTriangleType(4, 5, 6, "equilateral")',, 'IsTriangleType(4, 5, 6, "equilateral")',, '=', 0) check('equilateral triangle - all zero sides is not a triangle' 'IsTriangleType(0, 0, 0, "equilateral")',, 'IsTriangleType(0, 0, 0, "equilateral")',, '=', -1) check('equilateral triangle - sides may be floats' 'IsTriangleType(1.5, 1.5, 1.5, "equilateral")',, 'IsTriangleType(1.5, 1.5, 1.5, "equilateral")',, '=', 1) check('isosceles triangle - last two sides are equal' 'IsTriangleType(6, 4, 4, "isosceles")',, 'IsTriangleType(6, 4, 4, "isosceles")',, '=', 1) check('isosceles triangle - first two sides are equal' 'IsTriangleType(4, 4, 6, "isosceles")',, 'IsTriangleType(4, 4, 6, "isosceles")',, '=', 1) check('isosceles triangle - first and last sides are equal' 'IsTriangleType(4, 6, 4, "isosceles")',, 'IsTriangleType(4, 6, 4, "isosceles")',, '=', 1) check('isosceles triangle - equilaterl triangles are also isosceles' 'IsTriangleType(4, 4, 4, "isosceles")',, 'IsTriangleType(4, 4, 4, "isosceles")',, '=', 1) check('isosceles triangle - no sides are equal' 'IsTriangleType(4, 5, 6, "isosceles")',, 'IsTriangleType(4, 5, 6, "isosceles")',, '=', 0) check('isosceles triangle - first triangle inequality violation' 'IsTriangleType(1, 1, 3, "isosceles")',, 'IsTriangleType(1, 1, 3, "isosceles")',, '=', -1) check('isosceles triangle - second triangle inequality violation' 'IsTriangleType(1, 3, 1, "isosceles")',, 'IsTriangleType(1, 3, 1, "isosceles")',, '=', -1) check('isosceles triangle - third triangle inequality violation' 'IsTriangleType(3, 1, 1, "isosceles")',, 'IsTriangleType(3, 1, 1, "isosceles")',, '=', -1) check('isosceles triangle - sides may be floats' 'IsTriangleType(1.5, 1.5, 2.5, "isosceles")',, 'IsTriangleType(1.5, 1.5, 2.5, "isosceles")',, '=', 1) check('scalene triangle - all side are equal' 'IsTriangleType(2, 2, 2, "scalene")',, 'IsTriangleType(2, 2, 2, "scalene")',, '=', 0) check('scalene triangle - no sides are equal' 'IsTriangleType(4, 5, 6, "scalene")',, 'IsTriangleType(4, 5, 6, "scalene")',, '=', 1) check('scalene triangle - last two sides are equal' 'IsTriangleType(6, 4, 4, "scalene")',, 'IsTriangleType(6, 4, 4, "scalene")',, '=', 0) check('scalene triangle - first two sides are equal' 'IsTriangleType(4, 4, 6, "scalene")',, 'IsTriangleType(4, 4, 6, "scalene")',, '=', 0) check('scalene triangle - first and last sides are equal' 'IsTriangleType(4, 6, 4, "scalene")',, 'IsTriangleType(4, 6, 4, "scalene")',, '=', 0) check('scalene triangle - sides may be floats' 'IsTriangleType(4.5, 5.5, 6.5, "scalene")',, 'IsTriangleType(4.5, 5.5, 6.5, "scalene")',, '=', 1)
62
# Instructions Your task in this exercise is to write code that returns the lyrics of the song: "The Twelve Days of Christmas." "The Twelve Days of Christmas" is a common English Christmas carol. Each subsequent verse of the song builds on the previous verse. The lyrics your code returns should _exactly_ match the full song text shown below. ## Lyrics ```text On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree. On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree. On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. ```
Sing : procedure parse arg from, to parse value DATATYPE(from, 'N') DATATYPE(to, 'N') , with isFromNumeric isToNumeric if \isFromNumeric | from < 1 | from > 12 then ; return '' if \isToNumeric | to < 1 | to > 12 then ; to = from if from > to then ; return '' if from == to then ; return Verses(from) versesSung = '' ; stop = to do n = from to stop ; versesSung ||= Verses(n) ; end return versesSung Verses : procedure parse arg nthDay parse value (13 - nthDay) 27 GetVerses() , with nthDay verseLen verses versesSung = 'On the' WORD(GetNthDays(), nthDay) , 'day of Christmas my true love gave to me: ' verses = SUBSTR(verses, verseLen * nthDay - (verseLen - 1)) do while verses \= '' parse var verses verse +(verseLen) verses versesSung ||= STRIP(verse) '' ; nthDay += 1 end return STRIP(versesSung) || "0A"X GetVerses : return , 'twelve Drummers Drumming, ' || , 'eleven Pipers Piping, ' || , 'ten Lords-a-Leaping, ' || , 'nine Ladies Dancing, ' || , 'eight Maids-a-Milking, ' || , 'seven Swans-a-Swimming, ' || , 'six Geese-a-Laying, ' || , 'five Gold Rings, ' || , 'four Calling Birds, ' || , 'three French Hens, ' || , 'two Turtle Doves, and ' || , 'a Partridge in a Pear Tree.' GetNthdays : return , 'twelfth eleventh tenth ninth eighth seventh' , 'sixth fifth fourth third second first'
/* Unit Test Runner: t-rexx */ context('Checking the Verses and Sing functions') /* Test Variables */ verse_1 = , 'On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.' || "0A"X verse_2 = , 'On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_3 = , 'On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_4 = , 'On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_5 = , 'On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_6 = , 'On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_7 = , 'On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_8 = , 'On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_9 = , 'On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_10 = , 'On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_11 = , 'On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_12 = , 'On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_1_to_3 = , 'On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.' || "0A"X || , 'On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X || , 'On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_4_to_6 = , 'On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X || , 'On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X || , 'On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.' || "0A"X verse_1_to_12_length = 2370 /* Unit tests */ check('verse -> first day a partridge in a pear tree' 'Verses(1)',, 'Verses(1)',, '=', verse_1) check('verse -> second day two turtle doves' 'Verses(2)',, 'Verses(2)',, '=', verse_2) check('verse -> third day three french hens' 'Verses(3)',, 'Verses(3)',, '=', verse_3) check('verse -> fourth day four calling birds' 'Verses(4)',, 'Verses(4)',, '=', verse_4) check('verse -> fifth day five gold rings' 'Verses(5)',, 'Verses(5)',, '=', verse_5) check('verse -> sixth day six geese-a-laying' 'Verses(6)',, 'Verses(6)',, '=', verse_6) check('verse -> seventh day seven swans-a-swimming' 'Verses(7)',, 'Verses(7)',, '=', verse_7) check('verse -> eighth day eight maids-a-milking' 'Verses(8)',, 'Verses(8)',, '=', verse_8) check('verse -> ninth day nine ladies dancing' 'Verses(9)',, 'Verses(9)',, '=', verse_9) check('verse -> tenth day ten lords-a-leaping' 'Verses(10)',, 'Verses(10)',, '=', verse_10) check('verse -> eleventh day eleven pipers piping' 'Verses(11)',, 'Verses(11)',, '=', verse_11) check('verse -> twelfth day twelve drummers drumming' 'Verses(12)',, 'Verses(12)',, '=', verse_12) check('lyrics -> recites first three verses of the song' 'Sing(1, 3)',, 'Sing(1, 3)',, '=', verse_1_to_3) check('lyrics -> recites three verses from the middle of the song' 'Sing(4, 6)',, 'Sing(4, 6)',, '=', verse_4_to_6) cmd = 'actual = ' 'Sing(1, 12)' ; interpret cmd check('lyrics -> recites the whole song' 'Sing(1, 12)',, 'Sing(1, 12)', LENGTH(actual), '=', verse_1_to_12_length)
63
# Instructions Your task is to determine what you will say as you give away the extra cookie. If your friend likes cookies, and is named Do-yun, then you will say: ```text One for Do-yun, one for me. ``` If your friend doesn't like cookies, you give the cookie to the next person in line at the bakery. Since you don't know their name, you will say _you_ instead. ```text One for you, one for me. ``` Here are some examples: |Name |Dialogue |:-------|:------------------ |Alice |One for Alice, one for me. |Bohdan |One for Bohdan, one for me. | |One for you, one for me. |Zaphod |One for Zaphod, one for me.
TwoFer : procedure if ARG() < 1 then ; name = 'you' ; else name = ARG(1) return 'One for' name || ', one for me.'
/* Unit Test Runner: t-rexx */ context('Checking the TwoFer function') /* Unit tests */ check('no name given' 'TwoFer()',, 'TwoFer()',, '=', 'One for you, one for me.') check('a name given' 'TwoFer("Brad")',, 'TwoFer("Brad")',, '=', 'One for Brad, one for me.') check('another name given' 'TwoFer("Janet")',, 'TwoFer("Janet")',, '=', 'One for Janet, one for me.')
64
# Instructions Your task is to count how many times each word occurs in a subtitle of a drama. The subtitles from these dramas use only ASCII characters. The characters often speak in casual English, using contractions like _they're_ or _it's_. Though these contractions come from two words (e.g. _we are_), the contraction (_we're_) is considered a single word. Words can be separated by any form of punctuation (e.g. ":", "!", or "?") or whitespace (e.g. "\t", "\n", or " "). The only punctuation that does not separate words is the apostrophe in contractions. Numbers are considered words. If the subtitles say _It costs 100 dollars._ then _100_ will be its own word. Words are case insensitive. For example, the word _you_ occurs three times in the following sentence: > You come back, you hear me? DO YOU HEAR ME? The ordering of the word counts in the results doesn't matter. Here's an example that incorporates several of the elements discussed above: - simple words - contractions - numbers - case insensitive words - punctuation (including apostrophes) to separate words - different forms of whitespace to separate words `"That's the password: 'PASSWORD 123'!", cried the Special Agent.\nSo I fled.` The mapping for this subtitle would be: ```text 123: 1 agent: 1 cried: 1 fled: 1 i: 1 password: 2 so: 1 special: 1 that's: 1 the: 2 ```
WordCount : procedure /* Validate, then sanitize, input */ if ARG() < 1 | ARG(1) == '' then ; return '' sanitized = STRIP(CHANGESTR(';',, TRANSLATE(ARG(1),, '~`!@#$%^&*()_-+=<,>.?/:;"',, ';'),, '')) /* Perform input analysis and tally up word count */ keys = '' ; freq.0 = 0 ; idx = 0 do while sanitized \= '' parse lower var sanitized token sanitized token = STRIP(token, 'B', "'") if WORDPOS(token, keys) == 0 then do keys = keys token ; idx = WORDPOS(token, keys) freq.0 = freq.0 + 1 ; freq.idx = 1 end ; else do idx = WORDPOS(token, keys) ; freq.idx = freq.idx + 1 end end /* Assemble, then return, word count result table */ freqtbl = '' ; idx = 1 do while idx <= freq.0 freqtbl = freqtbl WORD(keys, idx) freq.idx idx = idx + 1 end return STRIP(freqtbl)
/* Unit Test Runner: t-rexx */ context('Checking the WordCount function') /* Unit tests */ check('count one word' 'WordCount("word")',, 'WordCount("word")',, '=', 'word 1') check('count one of each word' 'WordCount("one of each")',, 'WordCount("one of each")',, '=', 'one 1 of 1 each 1') check('multiple occurrences of a word' 'WordCount("one fish two fish red fish blue fish")',, 'WordCount("one fish two fish red fish blue fish")',, '=', 'one 1 fish 4 two 1 red 1 blue 1') check('handles cramped lists' 'WordCount("one,two,three")',, 'WordCount("one,two,three")',, '=', 'onetwothree 1') check('handles expanded lists' 'WordCount("one,"||"0A"X||"two,"||"0A"X||"three")',, 'WordCount("one,"||"0A"X||"two,"||"0A"X||"three")',, '=', 'one 1 two 1 three 1') check('ignore punctuation' 'WordCount("car: carpet as java: javascript!!&@$%^&")',, 'WordCount("car: carpet as java: javascript!!&@$%^&")',, '=', 'car 1 carpet 1 as 1 java 1 javascript 1') check('include numbers' 'WordCount("testing, 1, 2 testing")',, 'WordCount("testing, 1, 2 testing")',, '=', 'testing 2 1 1 2 1') check('normalize case' 'WordCount("go Go GO Stop stop")',, 'WordCount("go Go GO Stop stop")',, '=', 'go 3 stop 2') check('with quotations' 'WordCount("Joe can''t tell between ''large'' and large.")',, 'WordCount("Joe can''t tell between ''large'' and large.")',, '=', "joe 1 can't 1 tell 1 between 1 large 2 and 1") check('with apostrophes' 'WordCount("First: don''t laugh. Then: don''t cry.")',, 'WordCount("First: don''t laugh. Then: don''t cry.")',, '=', "first 1 don't 2 laugh 1 then 1 cry 1") check('multiple spaces not detected as a word' 'WordCount(" multiple whitespaces")',, 'WordCount(" multiple whitespaces")',, '=', 'multiple 1 whitespaces 1') check('alternating word separators not detected as a word' 'WordCount("one onetwothree one, one;two;three one; ")',, 'WordCount("one onetwothree one, one;two;three one; ")',, '=', 'one 3 onetwothree 2')