diff --git a/README.md b/README.md index 542fa63a0d8f74ecb7d0b3656bf8fe246317ba3e..894332f46fac6c67b744b665c97d1eaeb3294fa9 100644 --- a/README.md +++ b/README.md @@ -50,4 +50,5 @@ models: - deepseek-ai/deepseek-coder-33b-base - deepseek-ai/deepseek-coder-6.7b-instruct - deepseek-ai/deepseek-coder-33b-instruct +- codefuse-ai/CodeFuse-DeepSeek-33B --- \ No newline at end of file diff --git a/app.py b/app.py index 38985deb6f6e0bb88a2aa64deea33c88bc6579c3..9e3e65487e50ea075eb5b8b6e9786c0f2e7f73cf 100644 --- a/app.py +++ b/app.py @@ -116,7 +116,7 @@ def filter_items(df, leaderboard_table, query): def search_table(df, leaderboard_table, query): - filtered_df = df[(df["Models"].str.contains(query, case=False))] + filtered_df = df[(df["Model"].str.contains(query, case=False))] return filtered_df[leaderboard_table.columns] diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/codefuse-ai_CodeFuse-DeepSeek-33b_codefuse-admin.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/codefuse-ai_CodeFuse-DeepSeek-33b_codefuse-admin.json new file mode 100644 index 0000000000000000000000000000000000000000..0b949d212e3e411cf5e661e97e17501308d8ec0f --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/codefuse-ai_CodeFuse-DeepSeek-33b_codefuse-admin.json @@ -0,0 +1 @@ +{"results": [{"task": "multiple-r", "pass@1": 0.40372670807453415}, {"task": "humaneval", "pass@1": 0.7682926829268293}, {"task": "multiple-lua", "pass@1": 0.5279503105590062}, {"task": "multiple-php", "pass@1": 0.577639751552795}, {"task": "multiple-d", "pass@1": 0.24358974358974358}, {"task": "multiple-jl", "pass@1": 0.3836477987421384}, {"task": "multiple-cpp", "pass@1": 0.6521739130434783}, {"task": "multiple-java", "pass@1": 0.6075949367088608}, {"task": "multiple-rs", "pass@1": 0.5384615384615384}, {"task": "multiple-swift", "pass@1": 0.4936708860759494}, {"task": "multiple-js", "pass@1": 0.6645962732919255}, {"task": "multiple-rkt", "pass@1": 0.3416149068322981}], "meta": {"model": "codefuse-ai/CodeFuse-DeepSeek-33B"}} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_humaneval_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_humaneval_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..4ca50a911dd141e160ecb52fe7c1e69482a095e4 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_humaneval_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["from typing import List\n\n\ndef has_close_elements(numbers: List[float], threshold: float) -> bool:\n \"\"\" Check if in given list of numbers, are any two numbers closer to each other than\n given threshold.\n >>> has_close_elements([1.0, 2.0, 3.0], 0.5)\n False\n >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n True\n \"\"\"\n for i in range(len(numbers)):\n for j in range(i + 1, len(numbers)):\n if abs(numbers[i] - numbers[j]) <= threshold:\n return True\n return False\n"], ["from typing import List\n\n\ndef separate_paren_groups(paren_string: str) -> List[str]:\n \"\"\" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n separate those group into separate strings and return the list of those.\n Separate groups are balanced (each open brace is properly closed) and not nested within each other\n Ignore any spaces in the input string.\n >>> separate_paren_groups('( ) (( )) (( )( ))')\n ['()', '(())', '(()())']\n \"\"\"\n groups = []\n current_group = []\n open_count = 0\n for char in paren_string:\n if char == '(':\n open_count += 1\n current_group.append(char)\n elif char == ')':\n open_count -= 1\n current_group.append(char)\n if open_count == 0:\n groups.append(''.join(current_group))\n current_group = []\n return groups\n"], ["def truncate_number(number: float) -> float:\n \"\"\" Given a positive floating point number, it can be decomposed into\n and integer part (largest integer smaller than given number) and decimals\n (leftover part always smaller than 1).\n\n Return the decimal part of the number.\n >>> truncate_number(3.5)\n 0.5\n \"\"\"\n return number - int(number)\n"], ["from typing import List\n\n\ndef below_zero(operations: List[int]) -> bool:\n \"\"\" You're given a list of deposit and withdrawal operations on a bank account that starts with\n zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n at that point function should return True. Otherwise it should return False.\n >>> below_zero([1, 2, 3])\n False\n >>> below_zero([1, 2, -4, 5])\n True\n \"\"\"\n balance = 0\n for op in operations:\n balance += op\n if balance < 0:\n return True\n return False\n"], ["from typing import List\n\n\ndef mean_absolute_deviation(numbers: List[float]) -> float:\n \"\"\" For a given list of input numbers, calculate Mean Absolute Deviation\n around the mean of this dataset.\n Mean Absolute Deviation is the average absolute difference between each\n element and a centerpoint (mean in this case):\n MAD = average | x - x_mean |\n >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n 1.0\n \"\"\"\n mean = sum(numbers) / len(numbers)\n absolute_differences = [abs(x - mean) for x in numbers]\n mad = sum(absolute_differences) / len(absolute_differences)\n return mad\n"], ["from typing import List\n\n\ndef intersperse(numbers: List[int], delimeter: int) -> List[int]:\n \"\"\" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n >>> intersperse([], 4)\n []\n >>> intersperse([1, 2, 3], 4)\n [1, 4, 2, 4, 3]\n \"\"\"\n result = []\n for i, num in enumerate(numbers):\n result.append(num)\n if i != len(numbers) - 1:\n result.append(delimeter)\n return result\n"], ["from typing import List\n\n\ndef parse_nested_parens(paren_string: str) -> List[int]:\n \"\"\" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n For each of the group, output the deepest level of nesting of parentheses.\n E.g. (()()) has maximum two levels of nesting while ((())) has three.\n\n >>> parse_nested_parens('(()()) ((())) () ((())()())')\n [2, 3, 1, 3]\n \"\"\"\n groups = paren_string.split()\n max_depths = []\n for group in groups:\n depth = 0\n max_depth = 0\n for char in group:\n if char == '(':\n depth += 1\n max_depth = max(max_depth, depth)\n elif char == ')':\n depth -= 1\n max_depths.append(max_depth)\n return max_depths\n"], ["from typing import List\n\n\ndef filter_by_substring(strings: List[str], substring: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that contain given substring\n >>> filter_by_substring([], 'a')\n []\n >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')\n ['abc', 'bacd', 'array']\n \"\"\"\n return [s for s in strings if substring in s]\n"], ["from typing import List, Tuple\n\n\ndef sum_product(numbers: List[int]) -> Tuple[int, int]:\n \"\"\" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.\n Empty sum should be equal to 0 and empty product should be equal to 1.\n >>> sum_product([])\n (0, 1)\n >>> sum_product([1, 2, 3, 4])\n (10, 24)\n \"\"\"\n if not numbers:\n return 0, 1\n else:\n return sum(numbers), eval('*'.join(str(n) for n in numbers))\n"], ["from typing import List, Tuple\n\n\ndef rolling_max(numbers: List[int]) -> List[int]:\n \"\"\" From a given list of integers, generate a list of rolling maximum element found until given moment\n in the sequence.\n >>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n [1, 2, 3, 3, 3, 4, 4]\n \"\"\"\n rolling_max_list = []\n for i in range(len(numbers)):\n rolling_max_list.append(max(numbers[:i+1]))\n return rolling_max_list\n"], ["def is_palindrome(string: str) -> bool:\n \"\"\" Test if given string is a palindrome \"\"\"\n return string == string[::-1]\n\n\ndef make_palindrome(string: str) -> str:\n \"\"\" Find the shortest palindrome that begins with a supplied string.\n Algorithm idea is simple:\n - Find the longest postfix of supplied string that is a palindrome.\n - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n >>> make_palindrome('')\n ''\n >>> make_palindrome('cat')\n 'catac'\n >>> make_palindrome('cata')\n 'catac'\n \"\"\"\n if not string:\n return ''\n for i in range(len(string)):\n suffix = string[i:]\n if is_palindrome(suffix):\n prefix = string[:i][::-1]\n return string + prefix\n return string + string[::-1]\n"], ["from typing import List\n\n\ndef string_xor(a: str, b: str) -> str:\n \"\"\" Input are two strings a and b consisting only of 1s and 0s.\n Perform binary XOR on these inputs and return result also as a string.\n >>> string_xor('010', '110')\n '100'\n \"\"\"\n result = ''\n for i in range(len(a)):\n if a[i] == b[i]:\n result += '0'\n else:\n result += '1'\n return result\n"], ["from typing import List, Optional\n\n\ndef longest(strings: List[str]) -> Optional[str]:\n \"\"\" Out of list of strings, return the longest one. Return the first one in case of multiple\n strings of the same length. Return None in case the input list is empty.\n >>> longest([])\n\n >>> longest(['a', 'b', 'c'])\n 'a'\n >>> longest(['a', 'bb', 'ccc'])\n 'ccc'\n \"\"\"\n if not strings:\n return None\n max_len = 0\n longest_str = None\n for s in strings:\n if len(s) > max_len:\n max_len = len(s)\n longest_str = s\n return longest_str\n"], ["def greatest_common_divisor(a: int, b: int) -> int:\n \"\"\" Return a greatest common divisor of two integers a and b\n >>> greatest_common_divisor(3, 5)\n 1\n >>> greatest_common_divisor(25, 15)\n 5\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n"], ["from typing import List\n\n\ndef all_prefixes(string: str) -> List[str]:\n \"\"\" Return list of all prefixes from shortest to longest of the input string\n >>> all_prefixes('abc')\n ['a', 'ab', 'abc']\n \"\"\"\n return [string[:i] for i in range(1, len(string)+1)]\n"], ["def string_sequence(n: int) -> str:\n \"\"\" Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n >>> string_sequence(0)\n '0'\n >>> string_sequence(5)\n '0 1 2 3 4 5'\n \"\"\"\n return ' '.join(str(i) for i in range(n+1))\n"], ["def count_distinct_characters(string: str) -> int:\n \"\"\" Given a string, find out how many distinct characters (regardless of case) does it consist of\n >>> count_distinct_characters('xyzXYZ')\n 3\n >>> count_distinct_characters('Jerry')\n 4\n \"\"\"\n distinct_characters = set(string.lower())\n return len(distinct_characters)\n"], ["from typing import List\n\n\ndef parse_music(music_string: str) -> List[int]:\n \"\"\" Input to this function is a string representing musical notes in a special ASCII format.\n Your task is to parse this string and return list of integers corresponding to how many beats does each\n not last.\n\n Here is a legend:\n 'o' - whole note, lasts four beats\n 'o|' - half note, lasts two beats\n '.|' - quater note, lasts one beat\n\n >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\n \"\"\"\n notes = music_string.split()\n beats = []\n for note in notes:\n if note == 'o':\n beats.append(4)\n elif note == 'o|':\n beats.append(2)\n elif note == '.|':\n beats.append(1)\n return beats\n"], ["def how_many_times(string: str, substring: str) -> int:\n \"\"\" Find how many times a given substring can be found in the original string. Count overlaping cases.\n >>> how_many_times('', 'a')\n 0\n >>> how_many_times('aaa', 'a')\n 3\n >>> how_many_times('aaaa', 'aa')\n 3\n \"\"\"\n count = 0\n start = 0\n while True:\n start = string.find(substring, start) + 1\n if start > 0:\n count += 1\n else:\n return count\n"], ["from typing import List\n\n\ndef sort_numbers(numbers: str) -> str:\n \"\"\" Input is a space-delimited string of numberals from 'zero' to 'nine'.\n Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n Return the string with numbers sorted from smallest to largest\n >>> sort_numbers('three one five')\n 'one three five'\n \"\"\"\n num_dict = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}\n num_list = numbers.split()\n num_list.sort(key=lambda x: num_dict[x])\n return ' '.join(num_list)\n"], ["from typing import List, Tuple\n\n\ndef find_closest_elements(numbers: List[float]) -> Tuple[float, float]:\n \"\"\" From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n other and return them in order (smaller number, larger number).\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n (2.0, 2.2)\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n (2.0, 2.0)\n \"\"\"\n numbers.sort()\n closest_diff = float('inf')\n closest_pair = None\n for i in range(len(numbers) - 1):\n diff = numbers[i+1] - numbers[i]\n if diff < closest_diff:\n closest_diff = diff\n closest_pair = (numbers[i], numbers[i+1])\n return closest_pair\n"], ["from typing import List\n\n\ndef rescale_to_unit(numbers: List[float]) -> List[float]:\n \"\"\" Given list of numbers (of at least two elements), apply a linear transform to that list,\n such that the smallest number will become 0 and the largest will become 1\n >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n [0.0, 0.25, 0.5, 0.75, 1.0]\n \"\"\"\n min_num = min(numbers)\n max_num = max(numbers)\n if min_num == max_num:\n return [0.0] * len(numbers)\n else:\n return [(num - min_num) / (max_num - min_num) for num in numbers]\n"], ["from typing import List, Any\n\n\ndef filter_integers(values: List[Any]) -> List[int]:\n \"\"\" Filter given list of any python values only for integers\n >>> filter_integers(['a', 3.14, 5])\n [5]\n >>> filter_integers([1, 2, 3, 'abc', {}, []])\n [1, 2, 3]\n \"\"\"\n return [value for value in values if isinstance(value, int)]\n"], ["def strlen(string: str) -> int:\n \"\"\" Return length of given string\n >>> strlen('')\n 0\n >>> strlen('abc')\n 3\n \"\"\"\n return len(string)\n"], ["def largest_divisor(n: int) -> int:\n \"\"\" For a given number n, find the largest number that divides n evenly, smaller than n\n >>> largest_divisor(15)\n 5\n \"\"\"\n for i in range(n-1, 0, -1):\n if n % i == 0:\n return i\n return 1\n"], ["from typing import List\n\n\ndef factorize(n: int) -> List[int]:\n \"\"\" Return list of prime factors of given integer in the order from smallest to largest.\n Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n Input number should be equal to the product of all factors\n >>> factorize(8)\n [2, 2, 2]\n >>> factorize(25)\n [5, 5]\n >>> factorize(70)\n [2, 5, 7]\n \"\"\"\n factors = []\n divisor = 2\n while divisor <= n:\n if n % divisor == 0:\n factors.append(divisor)\n n = n / divisor\n else:\n divisor += 1\n return factors\n"], ["from typing import List\n\n\ndef remove_duplicates(numbers: List[int]) -> List[int]:\n \"\"\" From a list of integers, remove all elements that occur more than once.\n Keep order of elements left the same as in the input.\n >>> remove_duplicates([1, 2, 3, 2, 4])\n [1, 3, 4]\n \"\"\"\n unique_numbers = []\n for num in numbers:\n if num not in unique_numbers:\n unique_numbers.append(num)\n return unique_numbers\n"], ["def flip_case(string: str) -> str:\n \"\"\" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n >>> flip_case('Hello')\n 'hELLO'\n \"\"\"\n return string.swapcase()\n"], ["from typing import List\n\n\ndef concatenate(strings: List[str]) -> str:\n \"\"\" Concatenate list of strings into a single string\n >>> concatenate([])\n ''\n >>> concatenate(['a', 'b', 'c'])\n 'abc'\n \"\"\"\n return ''.join(strings)\n"], ["from typing import List\n\n\ndef filter_by_prefix(strings: List[str], prefix: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that start with a given prefix.\n >>> filter_by_prefix([], 'a')\n []\n >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')\n ['abc', 'array']\n \"\"\"\n return [s for s in strings if s.startswith(prefix)]\n"], ["def get_positive(l: list):\n \"\"\"Return only positive numbers in the list.\n >>> get_positive([-1, 2, -4, 5, 6])\n [2, 5, 6]\n >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n [5, 3, 2, 3, 9, 123, 1]\n \"\"\"\n return [x for x in l if x > 0]\n"], ["def is_prime(n):\n \"\"\"Return true if a given number is prime, and false otherwise.\n >>> is_prime(6)\n False\n >>> is_prime(101)\n True\n >>> is_prime(11)\n True\n >>> is_prime(13441)\n True\n >>> is_prime(61)\n True\n >>> is_prime(4)\n False\n >>> is_prime(1)\n False\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n"], ["import math\n\n\ndef poly(xs: list, x: float):\n \"\"\"\n Evaluates polynomial with coefficients xs at point x.\n return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n\n \"\"\"\n return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)])\n\n\ndef find_zero(xs: list):\n \"\"\" xs are coefficients of a polynomial.\n find_zero find x such that poly(x) = 0.\n find_zero returns only only zero point, even if there are many.\n Moreover, find_zero only takes list xs having even number of coefficients\n and largest non zero coefficient as it guarantees\n a solution.\n >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x\n -0.5\n >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3\n 1.0\n \"\"\"\n n = len(xs)\n a = xs[n - 2]\n b = xs[n - 1]\n return -b / a\n"], ["def sort_third(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n to the values of the corresponding indicies of l, but sorted.\n >>> sort_third([1, 2, 3])\n [1, 2, 3]\n >>> sort_third([5, 6, 3, 4, 8, 9, 2])\n [2, 6, 3, 4, 8, 9, 5]\n \"\"\"\n l_prime = []\n for i in range(len(l)):\n if (i+1) % 3 == 0:\n l_prime.append(sorted(l[i-2:i+1])[1])\n else:\n l_prime.append(l[i])\n return l_prime\n"], ["def unique(l: list):\n \"\"\"Return sorted unique elements in a list\n >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [0, 2, 3, 5, 9, 123]\n \"\"\"\n return sorted(list(set(l)))\n"], ["def max_element(l: list):\n \"\"\"Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n \"\"\"\n return max(l)\n"], ["def fizz_buzz(n: int):\n \"\"\"Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n >>> fizz_buzz(50)\n 0\n >>> fizz_buzz(78)\n 2\n >>> fizz_buzz(79)\n 3\n \"\"\"\n count = 0\n for i in range(n):\n if i % 11 == 0 or i % 13 == 0:\n count += str(i).count('7')\n return count\n"], ["def sort_even(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the odd indicies, while its values at the even indicies are equal\n to the values of the even indicies of l, but sorted.\n >>> sort_even([1, 2, 3])\n [1, 2, 3]\n >>> sort_even([5, 6, 3, 4])\n [3, 6, 5, 4]\n \"\"\"\n even_values = sorted(l[::2])\n l[::2] = even_values\n return l\n"], ["def encode_cyclic(s: str):\n \"\"\"\n returns encoded string by cycling groups of three characters.\n \"\"\"\n # split string to groups. Each of length 3.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n # cycle elements in each group. Unless group has fewer elements than 3.\n groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups]\n return \"\".join(groups)\n\n\ndef decode_cyclic(s: str):\n \"\"\"\n takes as input string encoded with encode_cyclic function. Returns decoded string.\n \"\"\"\n # split string to groups. Each of length 3.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n # undo cycling in each group. Unless group has fewer elements than 3.\n groups = [(group[-1] + group[:-1]) if len(group) == 3 else group for group in groups]\n return \"\".join(groups)\n"], ["def prime_fib(n: int):\n \"\"\"\n prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n >>> prime_fib(1)\n 2\n >>> prime_fib(2)\n 3\n >>> prime_fib(3)\n 5\n >>> prime_fib(4)\n 13\n >>> prime_fib(5)\n 89\n \"\"\"\n def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5)+1):\n if num % i == 0:\n return False\n return True\n \n fib_nums = [0, 1]\n count = 0\n i = 2\n while count < n:\n fib_nums.append(fib_nums[i-1] + fib_nums[i-2])\n if is_prime(fib_nums[i]):\n count += 1\n i += 1\n return fib_nums[n]\n"], ["def triples_sum_to_zero(l: list):\n \"\"\"\n triples_sum_to_zero takes a list of integers as an input.\n it returns True if there are three distinct elements in the list that\n sum to zero, and False otherwise.\n\n >>> triples_sum_to_zero([1, 3, 5, 0])\n False\n >>> triples_sum_to_zero([1, 3, -2, 1])\n True\n >>> triples_sum_to_zero([1, 2, 3, 7])\n False\n >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\n True\n >>> triples_sum_to_zero([1])\n False\n \"\"\"\n for i in range(len(l)):\n for j in range(i+1, len(l)):\n for k in range(j+1, len(l)):\n if l[i] + l[j] + l[k] == 0:\n return True\n return False\n"], ["def car_race_collision(n: int):\n \"\"\"\n Imagine a road that's a perfectly straight infinitely long line.\n n cars are driving left to right; simultaneously, a different set of n cars\n are driving right to left. The two sets of cars start out being very far from\n each other. All cars move in the same speed. Two cars are said to collide\n when a car that's moving left to right hits a car that's moving right to left.\n However, the cars are infinitely sturdy and strong; as a result, they continue moving\n in their trajectory as if they did not collide.\n\n This function outputs the number of such collisions.\n \"\"\"\n return n\n"], ["def incr_list(l: list):\n \"\"\"Return list with elements incremented by 1.\n >>> incr_list([1, 2, 3])\n [2, 3, 4]\n >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [6, 4, 6, 3, 4, 4, 10, 1, 124]\n \"\"\"\n return [x+1 for x in l]\n"], ["def pairs_sum_to_zero(l):\n \"\"\"\n pairs_sum_to_zero takes a list of integers as an input.\n it returns True if there are two distinct elements in the list that\n sum to zero, and False otherwise.\n >>> pairs_sum_to_zero([1, 3, 5, 0])\n False\n >>> pairs_sum_to_zero([1, 3, -2, 1])\n False\n >>> pairs_sum_to_zero([1, 2, 3, 7])\n False\n >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\n True\n >>> pairs_sum_to_zero([1])\n False\n \"\"\"\n for i in range(len(l)):\n for j in range(i+1, len(l)):\n if l[i] + l[j] == 0:\n return True\n return False\n"], ["def change_base(x: int, base: int):\n \"\"\"Change numerical base of input number x to base.\n return string representation after the conversion.\n base numbers are less than 10.\n >>> change_base(8, 3)\n '22'\n >>> change_base(8, 2)\n '1000'\n >>> change_base(7, 2)\n '111'\n \"\"\"\n if base < 2 or base > 10:\n raise ValueError(\"Base must be between 2 and 10\")\n result = \"\"\n while x > 0:\n result = str(x % base) + result\n x //= base\n return result\n"], ["def triangle_area(a, h):\n \"\"\"Given length of a side and high return area for a triangle.\n >>> triangle_area(5, 3)\n 7.5\n \"\"\"\n return 0.5 * a * h\n"], ["def fib4(n: int):\n \"\"\"The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fib4(0) -> 0\n fib4(1) -> 0\n fib4(2) -> 2\n fib4(3) -> 0\n fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n >>> fib4(5)\n 4\n >>> fib4(6)\n 8\n >>> fib4(7)\n 14\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 0\n elif n == 2:\n return 2\n elif n == 3:\n return 0\n else:\n a, b, c, d = 0, 0, 2, 0\n for i in range(4, n+1):\n temp = a + b + c + d\n a, b, c, d = b, c, d, temp\n return temp\n"], ["def median(l: list):\n \"\"\"Return median of elements in the list l.\n >>> median([3, 1, 2, 4, 5])\n 3\n >>> median([-10, 4, 6, 1000, 10, 20])\n 15.0\n \"\"\"\n l.sort()\n n = len(l)\n if n % 2 == 0:\n return (l[n//2 - 1] + l[n//2]) / 2\n else:\n return l[n//2]\n"], ["def is_palindrome(text: str):\n \"\"\"\n Checks if given string is a palindrome\n >>> is_palindrome('')\n True\n >>> is_palindrome('aba')\n True\n >>> is_palindrome('aaaaa')\n True\n >>> is_palindrome('zbcd')\n False\n \"\"\"\n return text == text[::-1]\n"], ["def modp(n: int, p: int):\n \"\"\"Return 2^n modulo p (be aware of numerics).\n >>> modp(3, 5)\n 3\n >>> modp(1101, 101)\n 2\n >>> modp(0, 101)\n 1\n >>> modp(3, 11)\n 8\n >>> modp(100, 101)\n 1\n \"\"\"\n return pow(2, n, p)\n"], ["def encode_shift(s: str):\n \"\"\"\n returns encoded string by shifting every character by 5 in the alphabet.\n \"\"\"\n return \"\".join([chr(((ord(ch) + 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])\n\n\ndef decode_shift(s: str):\n \"\"\"\n takes as input string encoded with encode_shift function. Returns decoded string.\n \"\"\"\n return \"\".join([chr(((ord(ch) - 5 - ord(\"a\") + 26) % 26) + ord(\"a\")) for ch in s])\n"], ["def remove_vowels(text):\n \"\"\"\n remove_vowels is a function that takes string and returns string without vowels.\n >>> remove_vowels('')\n ''\n >>> remove_vowels(\"abcdef\\nghijklm\")\n 'bcdf\\nghjklm'\n >>> remove_vowels('abcdef')\n 'bcdf'\n >>> remove_vowels('aaaaa')\n ''\n >>> remove_vowels('aaBAA')\n 'B'\n >>> remove_vowels('zbcd')\n 'zbcd'\n \"\"\"\n vowels = 'aeiouAEIOU'\n new_text = ''\n for char in text:\n if char not in vowels:\n new_text += char\n return new_text\n"], ["def below_threshold(l: list, t: int):\n \"\"\"Return True if all numbers in the list l are below threshold t.\n >>> below_threshold([1, 2, 4, 10], 100)\n True\n >>> below_threshold([1, 20, 4, 10], 5)\n False\n \"\"\"\n return all(num < t for num in l)\n"], ["def add(x: int, y: int):\n \"\"\"Add two numbers x and y\n >>> add(2, 3)\n 5\n >>> add(5, 7)\n 12\n \"\"\"\n return x + y\n"], ["def same_chars(s0: str, s1: str):\n \"\"\"\n Check if two words have the same characters.\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n True\n >>> same_chars('abcd', 'dddddddabc')\n True\n >>> same_chars('dddddddabc', 'abcd')\n True\n >>> same_chars('eabcd', 'dddddddabc')\n False\n >>> same_chars('abcd', 'dddddddabce')\n False\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n False\n \"\"\"\n return set(s0) == set(s1)\n"], ["def fib(n: int):\n \"\"\"Return n-th Fibonacci number.\n >>> fib(10)\n 55\n >>> fib(1)\n 1\n >>> fib(8)\n 21\n \"\"\"\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n"], ["def correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"<\" and \">\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"<\")\n False\n >>> correct_bracketing(\"<>\")\n True\n >>> correct_bracketing(\"<<><>>\")\n True\n >>> correct_bracketing(\"><<>\")\n False\n \"\"\"\n stack = []\n for bracket in brackets:\n if bracket == \"<\":\n stack.append(bracket)\n elif bracket == \">\" and stack:\n stack.pop()\n else:\n return False\n return not stack\n"], ["def monotonic(l: list):\n \"\"\"Return True is list elements are monotonically increasing or decreasing.\n >>> monotonic([1, 2, 4, 20])\n True\n >>> monotonic([1, 20, 4, 10])\n False\n >>> monotonic([4, 1, 0, -10])\n True\n \"\"\"\n increasing = decreasing = True\n for i in range(len(l)-1):\n if l[i] > l[i+1]:\n increasing = False\n if l[i] < l[i+1]:\n decreasing = False\n return increasing or decreasing\n"], ["def common(l1: list, l2: list):\n \"\"\"Return sorted unique common elements for two lists.\n >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n [1, 5, 653]\n >>> common([5, 3, 2, 8], [3, 2])\n [2, 3]\n\n \"\"\"\n return sorted(list(set(l1) & set(l2)))\n"], ["def largest_prime_factor(n: int):\n \"\"\"Return the largest prime factor of n. Assume n > 1 and is not a prime.\n >>> largest_prime_factor(13195)\n 29\n >>> largest_prime_factor(2048)\n 2\n \"\"\"\n i = 2\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n return n\n"], ["def sum_to_n(n: int):\n \"\"\"sum_to_n is a function that sums numbers from 1 to n.\n >>> sum_to_n(30)\n 465\n >>> sum_to_n(100)\n 5050\n >>> sum_to_n(5)\n 15\n >>> sum_to_n(10)\n 55\n >>> sum_to_n(1)\n 1\n \"\"\"\n return sum(range(1, n+1))\n"], ["def correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"(\" and \")\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"(\")\n False\n >>> correct_bracketing(\"()\")\n True\n >>> correct_bracketing(\"(()())\")\n True\n >>> correct_bracketing(\")(()\")\n False\n \"\"\"\n stack = []\n for bracket in brackets:\n if bracket == \"(\":\n stack.append(bracket)\n elif bracket == \")\":\n if not stack:\n return False\n stack.pop()\n return not stack\n"], ["def derivative(xs: list):\n \"\"\" xs represent coefficients of a polynomial.\n xs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n >>> derivative([3, 1, 2, 4, 5])\n [1, 4, 12, 20]\n >>> derivative([1, 2, 3])\n [2, 6]\n \"\"\"\n result = []\n for i in range(1, len(xs)):\n result.append(i * xs[i])\n return result\n"], ["def fibfib(n: int):\n \"\"\"The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fibfib(0) == 0\n fibfib(1) == 0\n fibfib(2) == 1\n fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n >>> fibfib(1)\n 0\n >>> fibfib(5)\n 4\n >>> fibfib(8)\n 24\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n a, b, c = 0, 0, 1\n for i in range(3, n+1):\n d = a + b + c\n a, b, c = b, c, d\n return d\n"], ["FIX = \"\"\"\nAdd more test cases.\n\"\"\"\n\ndef vowels_count(s):\n \"\"\"Write a function vowels_count which takes a string representing\n a word as input and returns the number of vowels in the string.\n Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n vowel, but only when it is at the end of the given word.\n\n Example:\n >>> vowels_count(\"abcde\")\n 2\n >>> vowels_count(\"ACEDY\")\n 3\n \"\"\"\n count = 0\n for char in s:\n if char.lower() in 'aeiouy':\n count += 1\n return count\n"], ["def circular_shift(x, shift):\n \"\"\"Circular shift the digits of the integer x, shift the digits right by shift\n and return the result as a string.\n If shift > number of digits, return digits reversed.\n >>> circular_shift(12, 1)\n \"21\"\n >>> circular_shift(12, 2)\n \"12\"\n \"\"\"\n digits = str(x)\n n = len(digits)\n if shift > n:\n return digits[::-1]\n else:\n shifted_digits = digits[-shift:] + digits[:-shift]\n return shifted_digits\n"], ["def digitSum(s):\n \"\"\"Task\n Write a function that takes a string as input and returns the sum of the upper characters only'\n ASCII codes.\n\n Examples:\n digitSum(\"\") => 0\n digitSum(\"abAB\") => 131\n digitSum(\"abcCd\") => 67\n digitSum(\"helloE\") => 69\n digitSum(\"woArBld\") => 131\n digitSum(\"aAaaaXa\") => 153\n \"\"\"\n sum = 0\n for i in s:\n if i.isupper():\n sum += ord(i)\n return sum\n"], ["def fruit_distribution(s,n):\n \"\"\"\n In this task, you will be given a string that represents a number of apples and oranges \n that are distributed in a basket of fruit this basket contains \n apples, oranges, and mango fruits. Given the string that represents the total number of \n the oranges and apples and an integer that represent the total number of the fruits \n in the basket return the number of the mango fruits in the basket.\n for examble:\n fruit_distribution(\"5 apples and 6 oranges\", 19) ->19 - 5 - 6 = 8\n fruit_distribution(\"0 apples and 1 oranges\",3) -> 3 - 0 - 1 = 2\n fruit_distribution(\"2 apples and 3 oranges\", 100) -> 100 - 2 - 3 = 95\n fruit_distribution(\"100 apples and 1 oranges\",120) -> 120 - 100 - 1 = 19\n \"\"\"\n # split the string into a list of words\n words = s.split()\n # get the number of apples and oranges\n apples = int(words[0])\n oranges = int(words[2])\n # calculate the number of mango fruits\n mango = n - apples - oranges\n # return the number of mango fruits\n return mango\n"], ["def pluck(arr):\n \"\"\"\n \"Given an array representing a branch of a tree that has non-negative integer nodes\n your task is to pluck one of the nodes and return it.\n The plucked node should be the node with the smallest even value.\n If multiple nodes with the same smallest even value are found return the node that has smallest index.\n\n The plucked node should be returned in a list, [ smalest_value, its index ],\n If there are no even values or the given array is empty, return [].\n\n Example 1:\n Input: [4,2,3]\n Output: [2, 1]\n Explanation: 2 has the smallest even value, and 2 has the smallest index.\n\n Example 2:\n Input: [1,2,3]\n Output: [2, 1]\n Explanation: 2 has the smallest even value, and 2 has the smallest index. \n\n Example 3:\n Input: []\n Output: []\n \n Example 4:\n Input: [5, 0, 3, 0, 4, 2]\n Output: [0, 1]\n Explanation: 0 is the smallest value, but there are two zeros,\n so we will choose the first zero, which has the smallest index.\n\n Constraints:\n * 1 <= nodes.length <= 10000\n * 0 <= node.value\n \"\"\"\n even_nodes = [(i, node) for i, node in enumerate(arr) if node % 2 == 0]\n if not even_nodes:\n return []\n smallest_even_node = min(even_nodes, key=lambda x: (x[1], x[0]))\n return [smallest_even_node[1], smallest_even_node[0]]\n"], ["def search(lst):\n '''\n You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n zero, and has a frequency greater than or equal to the value of the integer itself. \n The frequency of an integer is the number of times it appears in the list.\n If no such a value exist, return -1.\n Examples:\n search([4, 1, 2, 2, 3, 1]) == 2\n search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3\n search([5, 5, 4, 4, 4]) == -1\n '''\n freq = {}\n for num in lst:\n freq[num] = freq.get(num, 0) + 1\n for num in sorted(freq, reverse=True):\n if num <= freq[num]:\n return num\n return -1\n"], ["def strange_sort_list(lst):\n '''\n Given list of integers, return list in strange order.\n Strange sorting, is when you start with the minimum value,\n then maximum of the remaining integers, then minimum and so on.\n\n Examples:\n strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]\n strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]\n strange_sort_list([]) == []\n '''\n result = []\n while lst:\n result.append(min(lst))\n lst.remove(min(lst))\n if lst:\n result.append(max(lst))\n lst.remove(max(lst))\n return result\n"], ["def triangle_area(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return the area of\n the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n Otherwise return -1\n Three sides make a valid triangle when the sum of any two sides is greater \n than the third side.\n Example:\n triangle_area(3, 4, 5) == 6.00\n triangle_area(1, 2, 10) == -1\n '''\n if a + b > c and b + c > a and c + a > b:\n s = (a + b + c) / 2\n area = (s * (s - a) * (s - b) * (s - c)) ** 0.5\n return round(area, 2)\n else:\n return -1\n"], ["def will_it_fly(q,w):\n '''\n Write a function that returns True if the object q will fly, and False otherwise.\n The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n\n Example:\n will_it_fly([1, 2], 5) \u279e False \n # 1+2 is less than the maximum possible weight, but it's unbalanced.\n\n will_it_fly([3, 2, 3], 1) \u279e False\n # it's balanced, but 3+2+3 is more than the maximum possible weight.\n\n will_it_fly([3, 2, 3], 9) \u279e True\n # 3+2+3 is less than the maximum possible weight, and it's balanced.\n\n will_it_fly([3], 5) \u279e True\n # 3 is less than the maximum possible weight, and it's balanced.\n '''\n if q == q[::-1] and sum(q) <= w:\n return True\n else:\n return False\n"], ["def smallest_change(arr):\n \"\"\"\n Given an array arr of integers, find the minimum number of elements that\n need to be changed to make the array palindromic. A palindromic array is an array that\n is read the same backwards and forwards. In one change, you can change one element to any other element.\n\n For example:\n smallest_change([1,2,3,5,4,7,9,6]) == 4\n smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n smallest_change([1, 2, 3, 2, 1]) == 0\n \"\"\"\n n = len(arr)\n count = 0\n for i in range(n//2):\n if arr[i] != arr[n-i-1]:\n count += 1\n return count\n"], ["def total_match(lst1, lst2):\n '''\n Write a function that accepts two lists of strings and returns the list that has \n total number of chars in the all strings of the list less than the other list.\n\n if the two lists have the same number of chars, return the first list.\n\n Examples\n total_match([], []) \u279e []\n total_match(['hi', 'admin'], ['hI', 'Hi']) \u279e ['hI', 'Hi']\n total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) \u279e ['hi', 'admin']\n total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) \u279e ['hI', 'hi', 'hi']\n total_match(['4'], ['1', '2', '3', '4', '5']) \u279e ['4']\n '''\n total1 = sum(len(s) for s in lst1)\n total2 = sum(len(s) for s in lst2)\n if total1 < total2:\n return lst1\n elif total2 < total1:\n return lst2\n else:\n return lst1\n"], ["def is_multiply_prime(a):\n \"\"\"Write a function that returns true if the given number is the multiplication of 3 prime numbers\n and false otherwise.\n Knowing that (a) is less then 100. \n Example:\n is_multiply_prime(30) == True\n 30 = 2 * 3 * 5\n \"\"\"\n 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]\n for i in range(len(primes)):\n for j in range(i, len(primes)):\n for k in range(j, len(primes)):\n if primes[i] * primes[j] * primes[k] == a:\n return True\n return False\n"], ["def is_simple_power(x, n):\n \"\"\"Your task is to write a function that returns true if a number x is a simple\n power of n and false in other cases.\n x is a simple power of n if n**int=x\n For example:\n is_simple_power(1, 4) => true\n is_simple_power(2, 2) => true\n is_simple_power(8, 2) => true\n is_simple_power(3, 2) => false\n is_simple_power(3, 1) => false\n is_simple_power(5, 3) => false\n \"\"\"\n if x == 1:\n return True\n elif n == 1:\n return False\n elif x % n != 0:\n return False\n else:\n return is_simple_power(x // n, n)\n"], ["def iscube(a):\n '''\n Write a function that takes an integer a and returns True \n if this ingeger is a cube of some integer number.\n Note: you may assume the input is always valid.\n Examples:\n iscube(1) ==> True\n iscube(2) ==> False\n iscube(-1) ==> True\n iscube(64) ==> True\n iscube(0) ==> True\n iscube(180) ==> False\n '''\n return round(a ** (1 / 3)) ** 3 == a\n"], ["def hex_key(num):\n \"\"\"You have been tasked to write a function that receives \n a hexadecimal number as a string and counts the number of hexadecimal \n digits that are primes (prime number, or a prime, is a natural number \n greater than 1 that is not a product of two smaller natural numbers).\n Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n So you have to determine a number of the following digits: 2, 3, 5, 7, \n B (=decimal 11), D (=decimal 13).\n Note: you may assume the input is always correct or empty string, \n and symbols A,B,C,D,E,F are always uppercase.\n Examples:\n For num = \"AB\" the output should be 1.\n For num = \"1077E\" the output should be 2.\n For num = \"ABED1A33\" the output should be 4.\n For num = \"123456789ABCDEF0\" the output should be 6.\n For num = \"2020\" the output should be 2.\n \"\"\"\n primes = ['2', '3', '5', '7', 'B', 'D']\n count = 0\n for digit in num:\n if digit.upper() in primes:\n count += 1\n return count\n"], ["def decimal_to_binary(decimal):\n \"\"\"You will be given a number in decimal form and your task is to convert it to\n binary format. The function should return a string, with each character representing a binary\n number. Each character in the string will be '0' or '1'.\n\n There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n The extra characters are there to help with the format.\n\n Examples:\n decimal_to_binary(15) # returns \"db1111db\"\n decimal_to_binary(32) # returns \"db100000db\"\n \"\"\"\n binary = bin(decimal)[2:] # convert decimal to binary and remove the '0b' prefix\n return \"db\" + binary + \"db\" # add the 'db' prefix and suffix\n"], ["def is_happy(s):\n \"\"\"You are given a string s.\n Your task is to check if the string is happy or not.\n A string is happy if its length is at least 3 and every 3 consecutive letters are distinct\n For example:\n is_happy(a) => False\n is_happy(aa) => False\n is_happy(abcd) => True\n is_happy(aabb) => False\n is_happy(adb) => True\n is_happy(xyy) => False\n \"\"\"\n if len(s) < 3:\n return False\n for i in range(len(s)-2):\n if s[i] == s[i+1] or s[i] == s[i+2] or s[i+1] == s[i+2]:\n return False\n return True\n"], ["def numerical_letter_grade(grades):\n \"\"\"It is the last week of the semester and the teacher has to give the grades\n to students. The teacher has been making her own algorithm for grading.\n The only problem is, she has lost the code she used for grading.\n She has given you a list of GPAs for some students and you have to write \n a function that can output a list of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\n \n\n Example:\n grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']\n \"\"\"\n letter_grades = []\n for gpa in grades:\n if gpa == 4.0:\n letter_grades.append('A+')\n elif gpa > 3.7:\n letter_grades.append('A')\n elif gpa > 3.3:\n letter_grades.append('A-')\n elif gpa > 3.0:\n letter_grades.append('B+')\n elif gpa > 2.7:\n letter_grades.append('B')\n elif gpa > 2.3:\n letter_grades.append('B-')\n elif gpa > 2.0:\n letter_grades.append('C+')\n elif gpa > 1.7:\n letter_grades.append('C')\n elif gpa > 1.3:\n letter_grades.append('C-')\n elif gpa > 1.0:\n letter_grades.append('D+')\n elif gpa > 0.7:\n letter_grades.append('D')\n elif gpa > 0.0:\n letter_grades.append('D-')\n else:\n letter_grades.append('E')\n return letter_grades\n"], ["def prime_length(string):\n \"\"\"Write a function that takes a string and returns True if the string\n length is a prime number or False otherwise\n Examples\n prime_length('Hello') == True\n prime_length('abcdcba') == True\n prime_length('kittens') == True\n prime_length('orange') == False\n \"\"\"\n length = len(string)\n if length < 2:\n return False\n for i in range(2, int(length**0.5)+1):\n if length % i == 0:\n return False\n return True\n"], ["def starts_one_ends(n):\n \"\"\"\n Given a positive integer n, return the count of the numbers of n-digit\n positive integers that start or end with 1.\n \"\"\"\n count = 0\n for i in range(10**(n-1), 10**n):\n if str(i)[0] == '1' or str(i)[-1] == '1':\n count += 1\n return count\n"], ["def solve(N):\n \"\"\"Given a positive integer N, return the total sum of its digits in binary.\n \n Example\n For N = 1000, the sum of digits will be 1 the output should be \"1\".\n For N = 150, the sum of digits will be 6 the output should be \"110\".\n For N = 147, the sum of digits will be 12 the output should be \"1100\".\n \n Variables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\n Output:\n a string of binary number\n \"\"\"\n # Convert the integer to a string\n N_str = str(N)\n \n # Initialize the sum of digits in binary\n binary_sum = 0\n \n # Iterate through each digit in the string\n for digit in N_str:\n # Convert the digit to an integer\n digit_int = int(digit)\n \n # Add the binary representation of the digit to the sum\n binary_sum += int(bin(digit_int)[2:])\n \n # Convert the sum to a binary string and return it\n return bin(binary_sum)[2:]\n"], ["def add(lst):\n \"\"\"Given a non-empty list of integers lst. add the even elements that are at odd indices..\n\n\n Examples:\n add([4, 2, 6, 7]) ==> 2 \n \"\"\"\n sum = 0\n for i in range(len(lst)):\n if i % 2 != 0 and lst[i] % 2 == 0:\n sum += lst[i]\n return sum\n"], ["def anti_shuffle(s):\n \"\"\"\n Write a function that takes a string and returns an ordered version of it.\n Ordered version of string, is a string where all words (separated by space)\n are replaced by a new word where all the characters arranged in\n ascending order based on ascii value.\n Note: You should keep the order of words and blank spaces in the sentence.\n\n For example:\n anti_shuffle('Hi') returns 'Hi'\n anti_shuffle('hello') returns 'ehllo'\n anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n \"\"\"\n words = s.split()\n new_words = []\n for word in words:\n new_word = ''.join(sorted(word))\n new_words.append(new_word)\n return ' '.join(new_words)\n"], ["def get_row(lst, x):\n \"\"\"\n You are given a 2 dimensional data, as a nested lists,\n which is similar to matrix, however, unlike matrices,\n each row may contain a different number of columns.\n Given lst, and integer x, find integers x in the list,\n and return list of tuples, [(x1, y1), (x2, y2) ...] such that\n each tuple is a coordinate - (row, columns), starting with 0.\n Sort coordinates initially by rows in ascending order.\n Also, sort coordinates of the row by columns in descending order.\n \n Examples:\n get_row([\n [1,2,3,4,5,6],\n [1,2,3,4,1,6],\n [1,2,3,4,5,1]\n ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n get_row([], 1) == []\n get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)]\n \"\"\"\n result = []\n for i in range(len(lst)):\n for j in range(len(lst[i])):\n if lst[i][j] == x:\n result.append((i, j))\n result.sort(key=lambda x: (x[0], -x[1]))\n return result\n"], ["def sort_array(array):\n \"\"\"\n Given an array of non-negative integers, return a copy of the given array after sorting,\n you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n or sort it in descending order if the sum( first index value, last index value) is even.\n\n Note:\n * don't change the given array.\n\n Examples:\n * sort_array([]) => []\n * sort_array([5]) => [5]\n * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]\n * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]\n \"\"\"\n if len(array) < 2:\n return array\n sorted_array = sorted(array)\n if (array[0] + array[-1]) % 2 == 0:\n return sorted_array[::-1]\n else:\n return sorted_array\n"], ["def encrypt(s):\n \"\"\"Create a function encrypt that takes a string as an argument and\n returns a string encrypted with the alphabet being rotated. \n The alphabet should be rotated in a manner such that the letters \n shift down by two multiplied to two places.\n For example:\n encrypt('hi') returns 'lm'\n encrypt('asdfghjkl') returns 'ewhjklnop'\n encrypt('gf') returns 'kj'\n encrypt('et') returns 'ix'\n \"\"\"\n result = ''\n for char in s:\n if char.isalpha():\n ascii_offset = 65 if char.isupper() else 97\n new_char = chr((ord(char) - ascii_offset + 2*2) % 26 + ascii_offset)\n result += new_char\n else:\n result += char\n return result\n"], ["def next_smallest(lst):\n \"\"\"\n You are given a list of integers.\n Write a function next_smallest() that returns the 2nd smallest element of the list.\n Return None if there is no such element.\n \n next_smallest([1, 2, 3, 4, 5]) == 2\n next_smallest([5, 1, 4, 3, 2]) == 2\n next_smallest([]) == None\n next_smallest([1, 1]) == None\n \"\"\"\n if len(lst) < 2:\n return None\n smallest = min(lst)\n return min([num for num in lst if num != smallest], default=None)\n"], ["def is_bored(S):\n \"\"\"\n You'll be given a string of words, and your task is to count the number\n of boredoms. A boredom is a sentence that starts with the word \"I\".\n Sentences are delimited by '.', '?' or '!'.\n \n For example:\n >>> is_bored(\"Hello world\")\n 0\n >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n 1\n \"\"\"\n count = 0\n sentences = S.split(\". \")\n sentences = [s.split(\"! \") for s in sentences]\n sentences = [s.split(\"? \") for s in sentences]\n sentences = [item for sublist in sentences for item in sublist]\n for sentence in sentences:\n if sentence.startswith(\"I\"):\n count += 1\n return count\n"], ["def any_int(x, y, z):\n '''\n Create a function that takes 3 numbers.\n Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n Returns false in any other cases.\n \n Examples\n any_int(5, 2, 7) \u279e True\n \n any_int(3, 2, 2) \u279e False\n\n any_int(3, -2, 1) \u279e True\n \n any_int(3.6, -2.2, 2) \u279e False\n \n\n \n '''\n if isinstance(x, int) and isinstance(y, int) and isinstance(z, int):\n if x == y + z or y == x + z or z == x + y:\n return True\n else:\n return False\n else:\n return False\n"], ["def encode(message):\n \"\"\"\n Write a function that takes a message, and encodes in such a \n way that it swaps case of all letters, replaces all vowels in \n the message with the letter that appears 2 places ahead of that \n vowel in the english alphabet. \n Assume only letters. \n \n Examples:\n >>> encode('test')\n 'TGST'\n >>> encode('This is a message')\n 'tHKS KS C MGSSCGG'\n \"\"\"\n vowels = 'aeiouAEIOU'\n encoded_message = ''\n for letter in message:\n if letter.isalpha():\n if letter in vowels:\n vowel_index = vowels.index(letter)\n encoded_letter = vowels[(vowel_index + 2) % len(vowels)]\n encoded_message += encoded_letter\n else:\n encoded_message += letter.swapcase()\n else:\n encoded_message += letter\n return encoded_message\n"], ["def skjkasdkd(lst):\n \"\"\"You are given a list of integers.\n You need to find the largest prime value and return the sum of its digits.\n\n Examples:\n For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10\n For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25\n For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13\n For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11\n For lst = [0,81,12,3,1,21] the output should be 3\n For lst = [0,8,1,2,1,7] the output should be 7\n \"\"\"\n def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n \n primes = [n for n in lst if is_prime(n)]\n if not primes:\n return 0\n largest_prime = max(primes)\n return sum(int(digit) for digit in str(largest_prime))\n"], ["def check_dict_case(dict):\n \"\"\"\n Given a dictionary, return True if all keys are strings in lower \n case or all keys are strings in upper case, else return False.\n The function should return False is the given dictionary is empty.\n Examples:\n check_dict_case({\"a\":\"apple\", \"b\":\"banana\"}) should return True.\n check_dict_case({\"a\":\"apple\", \"A\":\"banana\", \"B\":\"banana\"}) should return False.\n check_dict_case({\"a\":\"apple\", 8:\"banana\", \"a\":\"apple\"}) should return False.\n check_dict_case({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}) should return False.\n check_dict_case({\"STATE\":\"NC\", \"ZIP\":\"12345\" }) should return True.\n \"\"\"\n if not dict:\n return False\n keys = list(dict.keys())\n if all(isinstance(key, str) and key.islower() for key in keys):\n return True\n elif all(isinstance(key, str) and key.isupper() for key in keys):\n return True\n else:\n return False\n"], ["def count_up_to(n):\n \"\"\"Implement a function that takes an non-negative integer and returns an array of the first n\n integers that are prime numbers and less than n.\n for example:\n count_up_to(5) => [2,3]\n count_up_to(11) => [2,3,5,7]\n count_up_to(0) => []\n count_up_to(20) => [2,3,5,7,11,13,17,19]\n count_up_to(1) => []\n count_up_to(18) => [2,3,5,7,11,13,17]\n \"\"\"\n primes = []\n for num in range(2, n):\n if all(num%i!=0 for i in range(2,num)):\n primes.append(num)\n return primes\n"], ["def multiply(a, b):\n \"\"\"Complete the function that takes two integers and returns \n the product of their unit digits.\n Assume the input is always valid.\n Examples:\n multiply(148, 412) should return 16.\n multiply(19, 28) should return 72.\n multiply(2020, 1851) should return 0.\n multiply(14,-15) should return 20.\n \"\"\"\n return (abs(a) % 10) * (abs(b) % 10)\n"], ["def count_upper(s):\n \"\"\"\n Given a string s, count the number of uppercase vowels in even indices.\n \n For example:\n count_upper('aBCdEf') returns 1\n count_upper('abcdefg') returns 0\n count_upper('dBBE') returns 0\n \"\"\"\n count = 0\n for i in range(len(s)):\n if i % 2 == 0 and s[i].isupper() and s[i] in 'AEIOU':\n count += 1\n return count\n"], ["def closest_integer(value):\n '''\n Create a function that takes a value (string) representing a number\n and returns the closest integer to it. If the number is equidistant\n from two integers, round it away from zero.\n\n Examples\n >>> closest_integer(\"10\")\n 10\n >>> closest_integer(\"15.3\")\n 15\n\n Note:\n Rounding away from zero means that if the given number is equidistant\n from two integers, the one you should return is the one that is the\n farthest from zero. For example closest_integer(\"14.5\") should\n return 15 and closest_integer(\"-14.5\") should return -15.\n '''\n num = float(value)\n if num >= 0:\n return int(num + 0.5)\n else:\n return int(num - 0.5)\n"], ["def make_a_pile(n):\n \"\"\"\n Given a positive integer n, you have to make a pile of n levels of stones.\n The first level has n stones.\n The number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\n Return the number of stones in each level in a list, where element at index\n i represents the number of stones in the level (i+1).\n\n Examples:\n >>> make_a_pile(3)\n [3, 5, 7]\n \"\"\"\n stones = [n]\n for i in range(1, n):\n if n % 2 == 0:\n stones.append(n + (2*i))\n else:\n stones.append(n + (2*i) - 1)\n return stones\n"], ["def words_string(s):\n \"\"\"\n You will be given a string of words separated by commas or spaces. Your task is\n to split the string into words and return an array of the words.\n \n For example:\n words_string(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n words_string(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n \"\"\"\n return s.replace(\",\", \" \").split()\n"], ["def choose_num(x, y):\n \"\"\"This function takes two positive numbers x and y and returns the\n biggest even integer number that is in the range [x, y] inclusive. If \n there's no such number, then the function should return -1.\n\n For example:\n choose_num(12, 15) = 14\n choose_num(13, 12) = -1\n \"\"\"\n for i in range(y, x-1, -1):\n if i % 2 == 0:\n return i\n return -1\n"], ["def rounded_avg(n, m):\n \"\"\"You are given two positive integers n and m, and your task is to compute the\n average of the integers from n through m (including n and m). \n Round the answer to the nearest integer and convert that to binary.\n If n is greater than m, return -1.\n Example:\n rounded_avg(1, 5) => \"0b11\"\n rounded_avg(7, 5) => -1\n rounded_avg(10, 20) => \"0b1111\"\n rounded_avg(20, 33) => \"0b11010\"\n \"\"\"\n if n > m:\n return -1\n avg = round((n + m) / 2)\n return bin(avg)\n"], ["def unique_digits(x):\n \"\"\"Given a list of positive integers x. return a sorted list of all \n elements that hasn't any even digit.\n\n Note: Returned list should be sorted in increasing order.\n \n For example:\n >>> unique_digits([15, 33, 1422, 1])\n [1, 15, 33]\n >>> unique_digits([152, 323, 1422, 10])\n []\n \"\"\"\n result = []\n for num in x:\n has_even_digit = False\n for digit in str(num):\n if int(digit) % 2 == 0:\n has_even_digit = True\n break\n if not has_even_digit:\n result.append(num)\n return sorted(result)\n"], ["def by_length(arr):\n \"\"\"\n Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n reverse the resulting array, and then replace each digit by its corresponding name from\n \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n\n For example:\n arr = [2, 1, 1, 4, 5, 8, 2, 3] \n -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] \n -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]\n return [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n \n If the array is empty, return an empty array:\n arr = []\n return []\n \n If the array has any strange number ignore it:\n arr = [1, -1 , 55] \n -> sort arr -> [-1, 1, 55]\n -> reverse arr -> [55, 1, -1]\n return = ['One']\n \"\"\"\n num_names = {1: \"One\", 2: \"Two\", 3: \"Three\", 4: \"Four\", 5: \"Five\", 6: \"Six\", 7: \"Seven\", 8: \"Eight\", 9: \"Nine\"}\n sorted_arr = sorted([num for num in arr if 1 <= num <= 9])\n reversed_arr = sorted_arr[::-1]\n return [num_names[num] for num in reversed_arr]\n"], ["def f(n):\n \"\"\" Implement the function f that takes n as a parameter,\n and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n or the sum of numbers from 1 to i otherwise.\n i starts from 1.\n the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n Example:\n f(5) == [1, 2, 6, 24, 15]\n \"\"\"\n result = []\n for i in range(1, n+1):\n if i % 2 == 0:\n factorial = 1\n for j in range(1, i+1):\n factorial *= j\n result.append(factorial)\n else:\n result.append(sum(range(1, i+1)))\n return result\n"], ["def even_odd_palindrome(n):\n \"\"\"\n Given a positive integer n, return a tuple that has the number of even and odd\n integer palindromes that fall within the range(1, n), inclusive.\n\n Example 1:\n\n Input: 3\n Output: (1, 2)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n\n Example 2:\n\n Input: 12\n Output: (4, 6)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n\n Note:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\n \"\"\"\n even_count = 0\n odd_count = 0\n for i in range(1, n+1):\n if str(i) == str(i)[::-1]:\n if i % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n return (even_count, odd_count)\n"], ["def count_nums(arr):\n \"\"\"\n Write a function count_nums which takes an array of integers and returns\n the number of elements which has a sum of digits > 0.\n If a number is negative, then its first signed digit will be negative:\n e.g. -123 has signed digits -1, 2, and 3.\n >>> count_nums([]) == 0\n >>> count_nums([-1, 11, -11]) == 1\n >>> count_nums([1, 1, 2]) == 3\n \"\"\"\n count = 0\n for num in arr:\n if num < 0:\n num = -num\n if sum(int(digit) for digit in str(num)) > 0:\n count += 1\n return count\n"], ["def move_one_ball(arr):\n \"\"\"We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n numbers in the array will be randomly ordered. Your task is to determine if\n it is possible to get an array sorted in non-decreasing order by performing \n the following operation on the given array:\n You are allowed to perform right shift operation any number of times.\n \n One right shift operation means shifting all elements of the array by one\n position in the right direction. The last element of the array will be moved to\n the starting position in the array i.e. 0th index. \n\n If it is possible to obtain the sorted array by performing the above operation\n then return True else return False.\n If the given array is empty then return True.\n\n Note: The given list is guaranteed to have unique elements.\n\n For Example:\n \n move_one_ball([3, 4, 5, 1, 2])==>True\n Explanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given array.\n move_one_ball([3, 5, 4, 1, 2])==>False\n Explanation:It is not possible to get non-decreasing order for the given\n array by performing any number of right shift operations.\n \n \"\"\"\n if len(arr) == 0:\n return True\n else:\n sorted_arr = sorted(arr)\n for i in range(len(arr)):\n if arr == sorted_arr:\n return True\n else:\n arr = [arr[-1]] + arr[:-1]\n return False\n"], ["def exchange(lst1, lst2):\n \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n and determines whether it is possible to perform an exchange of elements\n between them to make lst1 a list of only even numbers.\n There is no limit on the number of exchanged elements between lst1 and lst2.\n If it is possible to exchange elements between the lst1 and lst2 to make\n all the elements of lst1 to be even, return \"YES\".\n Otherwise, return \"NO\".\n For example:\n exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n It is assumed that the input lists will be non-empty.\n \"\"\"\n # Count the number of odd numbers in lst1\n odd_count = sum(1 for num in lst1 if num % 2 != 0)\n \n # Count the number of even numbers in lst2\n even_count = sum(1 for num in lst2 if num % 2 == 0)\n \n # If there are more odd numbers in lst1 than even numbers in lst2,\n # it is not possible to exchange elements to make lst1 all even\n if odd_count > even_count:\n return \"NO\"\n \n return \"YES\"\n"], ["def histogram(test):\n \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n of the letter with the most repetition and containing the corresponding count.\n If several letters have the same occurrence, return all of them.\n \n Example:\n histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n histogram('a b b a') == {'a': 2, 'b': 2}\n histogram('a b c a b') == {'a': 2, 'b': 2}\n histogram('b b b b a') == {'b': 4}\n histogram('') == {}\n\n \"\"\"\n # Split the string into a list of words\n words = test.split()\n \n # Create a dictionary to store the count of each letter\n letter_count = {}\n \n # Loop through each word in the list\n for word in words:\n # Loop through each letter in the word\n for letter in word:\n # If the letter is already in the dictionary, increment its count\n if letter in letter_count:\n letter_count[letter] += 1\n # Otherwise, add the letter to the dictionary with a count of 1\n else:\n letter_count[letter] = 1\n \n # Find the maximum count in the dictionary\n max_count = max(letter_count.values())\n \n # Create a new dictionary to store the letters with the maximum count\n max_letters = {}\n \n # Loop through each letter in the dictionary\n for letter, count in letter_count.items():\n # If the count is equal to the maximum count, add the letter to the new dictionary\n if count == max_count:\n max_letters[letter] = count\n \n # Return the new dictionary\n return max_letters\n"], ["def reverse_delete(s,c):\n \"\"\"Task\n We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n then check if the result string is palindrome.\n A string is called palindrome if it reads the same backward as forward.\n You should return a tuple containing the result string and True/False for the check.\n Example\n For s = \"abcde\", c = \"ae\", the result should be ('bcd',False)\n For s = \"abcdef\", c = \"b\" the result should be ('acdef',False)\n For s = \"abcdedcba\", c = \"ab\", the result should be ('cdedc',True)\n \"\"\"\n for char in c:\n s = s.replace(char, '')\n is_palindrome = s == s[::-1]\n return (s, is_palindrome)\n"], ["def odd_count(lst):\n \"\"\"Given a list of strings, where each string consists of only digits, return a list.\n Each element i of the output should be \"the number of odd elements in the\n string i of the input.\" where all the i's should be replaced by the number\n of odd digits in the i'th string of the input.\n\n >>> odd_count(['1234567'])\n [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n >>> odd_count(['3',\"11111111\"])\n [\"the number of odd elements 1n the str1ng 1 of the 1nput.\",\n \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\n \"\"\"\n output = []\n for s in lst:\n count = 0\n for c in s:\n if int(c) % 2 != 0:\n count += 1\n output.append(\"the number of odd elements {}n the str{}ng {} of the {}nput.\".format(count, count, count, count))\n return output\n"], ["def minSubArraySum(nums):\n \"\"\"\n Given an array of integers nums, find the minimum sum of any non-empty sub-array\n of nums.\n Example\n minSubArraySum([2, 3, 4, 1, 2, 4]) == 1\n minSubArraySum([-1, -2, -3]) == -6\n \"\"\"\n min_sum = float('inf')\n curr_sum = 0\n for num in nums:\n curr_sum = min(num, curr_sum + num)\n min_sum = min(min_sum, curr_sum)\n return min_sum\n"], ["def max_fill(grid, capacity):\n import math\n \"\"\"\n You are given a rectangular grid of wells. Each row represents a single well,\n and each 1 in a row represents a single unit of water.\n Each well has a corresponding bucket that can be used to extract water from it, \n and all buckets have the same capacity.\n Your task is to use the buckets to empty the wells.\n Output the number of times you need to lower the buckets.\n\n Example 1:\n Input: \n grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n bucket_capacity : 1\n Output: 6\n\n Example 2:\n Input: \n grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n bucket_capacity : 2\n Output: 5\n \n Example 3:\n Input: \n grid : [[0,0,0], [0,0,0]]\n bucket_capacity : 5\n Output: 0\n\n Constraints:\n * all wells have the same length\n * 1 <= grid.length <= 10^2\n * 1 <= grid[:,1].length <= 10^2\n * grid[i][j] -> 0 | 1\n * 1 <= capacity <= 10\n \"\"\"\n num_wells = len(grid)\n num_units = len(grid[0])\n total_units = sum(sum(row) for row in grid)\n num_buckets = math.ceil(total_units / capacity)\n return num_buckets\n"], ["def sort_array(arr):\n \"\"\"\n In this Kata, you have to sort an array of non-negative integers according to\n number of ones in their binary representation in ascending order.\n For similar number of ones, sort based on decimal value.\n\n It must be implemented like this:\n >>> sort_array([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]\n >>> sort_array([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]\n >>> sort_array([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4]\n \"\"\"\n def count_ones(n):\n return bin(n).count('1')\n return sorted(arr, key=lambda x: (count_ones(x), x))\n"], ["def select_words(s, n):\n \"\"\"Given a string s and a natural number n, you have been tasked to implement \n a function that returns a list of all words from string s that contain exactly \n n consonants, in order these words appear in the string s.\n If the string s is empty then the function should return an empty list.\n Note: you may assume the input string contains only letters and spaces.\n Examples:\n select_words(\"Mary had a little lamb\", 4) ==> [\"little\"]\n select_words(\"Mary had a little lamb\", 3) ==> [\"Mary\", \"lamb\"]\n select_words(\"simple white space\", 2) ==> []\n select_words(\"Hello world\", 4) ==> [\"world\"]\n select_words(\"Uncle sam\", 3) ==> [\"Uncle\"]\n \"\"\"\n vowels = ['a', 'e', 'i', 'o', 'u']\n words = s.split()\n result = []\n for word in words:\n consonants_count = 0\n for char in word:\n if char.lower() not in vowels and char.isalpha():\n consonants_count += 1\n if consonants_count == n:\n result.append(word)\n return result\n"], ["def get_closest_vowel(word):\n \"\"\"You are given a word. Your task is to find the closest vowel that stands between \n two consonants from the right side of the word (case sensitive).\n \n Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n find any vowel met the above condition. \n\n You may assume that the given string contains English letter only.\n\n Example:\n get_closest_vowel(\"yogurt\") ==> \"u\"\n get_closest_vowel(\"FULL\") ==> \"U\"\n get_closest_vowel(\"quick\") ==> \"\"\n get_closest_vowel(\"ab\") ==> \"\"\n \"\"\"\n vowels = \"aeiouAEIOU\"\n closest_vowel = \"\"\n for i in range(len(word)-2, 0, -1):\n if word[i] not in vowels and word[i+1] in vowels and word[i-1] not in vowels:\n closest_vowel = word[i+1]\n break\n return closest_vowel\n"], ["def match_parens(lst):\n '''\n You are given a list of two strings, both strings consist of open\n parentheses '(' or close parentheses ')' only.\n Your job is to check if it is possible to concatenate the two strings in\n some order, that the resulting string will be good.\n A string S is considered to be good if and only if all parentheses in S\n are balanced. For example: the string '(())()' is good, while the string\n '())' is not.\n Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n\n Examples:\n match_parens(['()(', ')']) == 'Yes'\n match_parens([')', ')']) == 'No'\n '''\n def is_balanced(s):\n stack = []\n for c in s:\n if c == '(':\n stack.append(c)\n elif c == ')':\n if not stack:\n return False\n stack.pop()\n return not stack\n \n for perm in itertools.permutations(lst):\n if is_balanced(''.join(perm)):\n return 'Yes'\n return 'No'\n"], ["def maximum(arr, k):\n \"\"\"\n Given an array arr of integers and a positive integer k, return a sorted list \n of length k with the maximum k numbers in arr.\n\n Example 1:\n\n Input: arr = [-3, -4, 5], k = 3\n Output: [-4, -3, 5]\n\n Example 2:\n\n Input: arr = [4, -4, 4], k = 2\n Output: [4, 4]\n\n Example 3:\n\n Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1\n Output: [2]\n\n Note:\n 1. The length of the array will be in the range of [1, 1000].\n 2. The elements in the array will be in the range of [-1000, 1000].\n 3. 0 <= k <= len(arr)\n \"\"\"\n arr.sort(reverse=True)\n return arr[:k]\n"], ["def solution(lst):\n \"\"\"Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n \n\n Examples\n solution([5, 8, 7, 1]) ==> 12\n solution([3, 3, 3, 3, 3]) ==> 9\n solution([30, 13, 24, 321]) ==>0\n \"\"\"\n return sum(lst[i] for i in range(0, len(lst), 2) if lst[i] % 2 != 0)\n"], ["def add_elements(arr, k):\n \"\"\"\n Given a non-empty array of integers arr and an integer k, return\n the sum of the elements with at most two digits from the first k elements of arr.\n\n Example:\n\n Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4\n Output: 24 # sum of 21 + 3\n\n Constraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\n \"\"\"\n total = 0\n for i in range(k):\n if len(str(arr[i])) <= 2:\n total += arr[i]\n return total\n"], ["def get_odd_collatz(n):\n \"\"\"\n Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n\n The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n as follows: start with any positive integer n. Then each term is obtained from the \n previous term as follows: if the previous term is even, the next term is one half of \n the previous term. If the previous term is odd, the next term is 3 times the previous\n term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n\n Note: \n 1. Collatz(1) is [1].\n 2. returned list sorted in increasing order.\n\n For example:\n get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n \"\"\"\n collatz_seq = [n]\n while n != 1:\n if n % 2 == 0:\n n = n // 2\n else:\n n = 3 * n + 1\n collatz_seq.append(n)\n odd_collatz = [num for num in collatz_seq if num % 2 != 0]\n return sorted(set(odd_collatz))\n"], ["def valid_date(date):\n \"\"\"You have to write a function which validates a given date string and\n returns True if the date is valid otherwise False.\n The date is valid if all of the following rules are satisfied:\n 1. The date string is not empty.\n 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n 3. The months should not be less than 1 or higher than 12.\n 4. The date should be in the format: mm-dd-yyyy\n\n for example: \n valid_date('03-11-2000') => True\n\n valid_date('15-01-2012') => False\n\n valid_date('04-0-2040') => False\n\n valid_date('06-04-2020') => True\n\n valid_date('06/04/2020') => False\n \"\"\"\n if not date:\n return False\n try:\n month, day, year = map(int, date.split('-'))\n except ValueError:\n return False\n if month < 1 or month > 12:\n return False\n if day < 1 or day > 31:\n return False\n if month in [4, 6, 9, 11] and day > 30:\n return False\n if month == 2:\n if day > 29:\n return False\n if day == 29 and year % 4 != 0:\n return False\n return True\n"], ["def split_words(txt):\n '''\n Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n Examples\n split_words(\"Hello world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"Hello,world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"abcdef\") == 3 \n '''\n if ' ' in txt:\n return txt.split(' ')\n elif ',' in txt:\n return txt.split(',')\n else:\n count = 0\n for char in txt:\n if char.islower() and ord(char) % 2 != 0:\n count += 1\n return count\n"], ["def is_sorted(lst):\n '''\n Given a list of numbers, return whether or not they are sorted\n in ascending order. If list has more than 1 duplicate of the same\n number, return False. Assume no negative numbers and only integers.\n\n Examples\n is_sorted([5]) \u279e True\n is_sorted([1, 2, 3, 4, 5]) \u279e True\n is_sorted([1, 3, 2, 4, 5]) \u279e False\n is_sorted([1, 2, 3, 4, 5, 6]) \u279e True\n is_sorted([1, 2, 3, 4, 5, 6, 7]) \u279e True\n is_sorted([1, 3, 2, 4, 5, 6, 7]) \u279e False\n is_sorted([1, 2, 2, 3, 3, 4]) \u279e True\n is_sorted([1, 2, 2, 2, 3, 4]) \u279e False\n '''\n if len(lst) == len(set(lst)):\n return lst == sorted(lst)\n else:\n return False\n"], ["def intersection(interval1, interval2):\n \"\"\"You are given two intervals,\n where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n The given intervals are closed which means that the interval (start, end)\n includes both start and end.\n For each given interval, it is assumed that its start is less or equal its end.\n Your task is to determine whether the length of intersection of these two \n intervals is a prime number.\n Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n which its length is 1, which not a prime number.\n If the length of the intersection is a prime number, return \"YES\",\n otherwise, return \"NO\".\n If the two intervals don't intersect, return \"NO\".\n\n\n [input/output] samples:\n intersection((1, 2), (2, 3)) ==> \"NO\"\n intersection((-1, 1), (0, 4)) ==> \"NO\"\n intersection((-3, -1), (-5, 5)) ==> \"YES\"\n \"\"\"\n start1, end1 = interval1\n start2, end2 = interval2\n intersection_start = max(start1, start2)\n intersection_end = min(end1, end2)\n intersection_length = max(0, intersection_end - intersection_start + 1)\n if intersection_length < 2:\n return \"NO\"\n for i in range(2, int(intersection_length ** 0.5) + 1):\n if intersection_length % i == 0:\n return \"NO\"\n return \"YES\"\n"], ["def prod_signs(arr):\n \"\"\"\n You are given an array arr of integers and you need to return\n sum of magnitudes of integers multiplied by product of all signs\n of each number in the array, represented by 1, -1 or 0.\n Note: return None for empty arr.\n\n Example:\n >>> prod_signs([1, 2, 2, -4]) == -9\n >>> prod_signs([0, 1]) == 0\n >>> prod_signs([]) == None\n \"\"\"\n if not arr:\n return None\n product = 1\n for num in arr:\n if num > 0:\n product *= 1\n elif num < 0:\n product *= -1\n else:\n product *= 0\n return sum(abs(num) for num in arr) * product\n"], ["def minPath(grid, k):\n \"\"\"\n Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n each cell of the grid contains a value. Every integer in the range [1, N * N]\n inclusive appears exactly once on the cells of the grid.\n\n You have to find the minimum path of length k in the grid. You can start\n from any cell, and in each step you can move to any of the neighbor cells,\n in other words, you can go to cells which share an edge with you current\n cell.\n Please note that a path of length k means visiting exactly k cells (not\n necessarily distinct).\n You CANNOT go off the grid.\n A path A (of length k) is considered less than a path B (of length k) if\n after making the ordered lists of the values on the cells that A and B go\n through (let's call them lst_A and lst_B), lst_A is lexicographically less\n than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n lst_A[j] = lst_B[j].\n It is guaranteed that the answer is unique.\n Return an ordered list of the values on the cells that the minimum path go through.\n\n Examples:\n\n Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n Output: [1, 2, 1]\n\n Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n Output: [1]\n \"\"\"\n n = len(grid)\n dp = [[[float('inf')] * (k + 1) for _ in range(n)] for _ in range(n)]\n dp[0][0][0] = grid[0][0]\n for step in range(1, k + 1):\n for i in range(n):\n for j in range(n):\n for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n ni, nj = i + di, j + dj\n if 0 <= ni < n and 0 <= nj < n:\n dp[i][j][step] = min(dp[i][j][step], dp[ni][nj][step - 1] + grid[i][j])\n res = []\n i, j, step = 0, 0, k\n while step > 0:\n res.append(grid[i][j])\n for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n ni, nj = i + di, j + dj\n if 0 <= ni < n and 0 <= nj < n and dp[ni][nj][step - 1] + grid[i][j] == dp[i][j][step]:\n i, j, step = ni, nj, step - 1\n break\n return res\n"], ["def tri(n):\n \"\"\"Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n the last couple centuries. However, what people don't know is Tribonacci sequence.\n Tribonacci sequence is defined by the recurrence:\n tri(1) = 3\n tri(n) = 1 + n / 2, if n is even.\n tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n For example:\n tri(2) = 1 + (2 / 2) = 2\n tri(4) = 3\n tri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \n You are given a non-negative integer number n, you have to a return a list of the \n first n + 1 numbers of the Tribonacci sequence.\n Examples:\n tri(3) = [1, 3, 2, 8]\n \"\"\"\n if n == 1:\n return [3]\n elif n == 2:\n return [3, 1]\n else:\n seq = [3, 1, 8]\n for i in range(3, n+1):\n if i % 2 == 0:\n seq.append(1 + i//2)\n else:\n seq.append(seq[i-2] + seq[i-3] + seq[i-1])\n return seq\n"], ["def digits(n):\n \"\"\"Given a positive integer n, return the product of the odd digits.\n Return 0 if all digits are even.\n For example:\n digits(1) == 1\n digits(4) == 0\n digits(235) == 15\n \"\"\"\n product = 1\n for digit in str(n):\n if int(digit) % 2 != 0:\n product *= int(digit)\n if product == 1:\n return 0\n else:\n return product\n"], ["def is_nested(string):\n '''\n Create a function that takes a string as input which contains only square brackets.\n The function should return True if and only if there is a valid subsequence of brackets \n where at least one bracket in the subsequence is nested.\n\n is_nested('[[]]') \u279e True\n is_nested('[]]]]]]][[[[[]') \u279e False\n is_nested('[][]') \u279e False\n is_nested('[]') \u279e False\n is_nested('[[][]]') \u279e True\n is_nested('[[]][[') \u279e True\n '''\n stack = []\n for char in string:\n if char == '[':\n stack.append(char)\n elif char == ']':\n if len(stack) > 0 and stack[-1] == '[':\n stack.pop()\n else:\n return True\n return False\n"], ["def sum_squares(lst):\n \"\"\"You are given a list of numbers.\n You need to return the sum of squared numbers in the given list,\n round each element in the list to the upper int(Ceiling) first.\n Examples:\n For lst = [1,2,3] the output should be 14\n For lst = [1,4,9] the output should be 98\n For lst = [1,3,5,7] the output should be 84\n For lst = [1.4,4.2,0] the output should be 29\n For lst = [-2.4,1,1] the output should be 6\n \n\n \"\"\"\n return sum([int(num**2) for num in lst])\n"], ["def check_if_last_char_is_a_letter(txt):\n '''\n Create a function that returns True if the last character\n of a given string is an alphabetical character and is not\n a part of a word, and False otherwise.\n Note: \"word\" is a group of characters separated by space.\n\n Examples:\n check_if_last_char_is_a_letter(\"apple pie\") \u279e False\n check_if_last_char_is_a_letter(\"apple pi e\") \u279e True\n check_if_last_char_is_a_letter(\"apple pi e \") \u279e False\n check_if_last_char_is_a_letter(\"\") \u279e False \n '''\n if not txt:\n return False\n last_char = txt.strip()[-1]\n if last_char.isalpha() and txt.rindex(last_char) == len(txt.strip()) - 1:\n return True\n else:\n return False\n"], ["def can_arrange(arr):\n \"\"\"Create a function which returns the largest index of an element which\n is not greater than or equal to the element immediately preceding it. If\n no such element exists then return -1. The given array will not contain\n duplicate values.\n\n Examples:\n can_arrange([1,2,4,3,5]) = 3\n can_arrange([1,2,3]) = -1\n \"\"\"\n max_index = -1\n for i in range(1, len(arr)):\n if arr[i] < arr[i-1]:\n max_index = i-1\n return max_index\n"], ["def largest_smallest_integers(lst):\n '''\n Create a function that returns a tuple (a, b), where 'a' is\n the largest of negative integers, and 'b' is the smallest\n of positive integers in a list.\n If there is no negative or positive integers, return them as None.\n\n Examples:\n largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)\n largest_smallest_integers([]) == (None, None)\n largest_smallest_integers([0]) == (None, None)\n '''\n negatives = [num for num in lst if num < 0]\n positives = [num for num in lst if num > 0]\n if not negatives and not positives:\n return (None, None)\n elif not negatives:\n return (None, min(positives))\n elif not positives:\n return (max(negatives), None)\n else:\n return (max(negatives), min(positives))\n"], ["def compare_one(a, b):\n \"\"\"\n Create a function that takes integers, floats, or strings representing\n real numbers, and returns the larger variable in its given variable type.\n Return None if the values are equal.\n Note: If a real number is represented as a string, the floating point might be . or ,\n\n compare_one(1, 2.5) \u279e 2.5\n compare_one(1, \"2,3\") \u279e \"2,3\"\n compare_one(\"5,1\", \"6\") \u279e \"6\"\n compare_one(\"1\", 1) \u279e None\n \"\"\"\n if isinstance(a, str):\n a = float(a.replace(',', '.'))\n if isinstance(b, str):\n b = float(b.replace(',', '.'))\n if a > b:\n return a\n elif b > a:\n return b\n else:\n return None\n"], ["def is_equal_to_sum_even(n):\n \"\"\"Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n Example\n is_equal_to_sum_even(4) == False\n is_equal_to_sum_even(6) == False\n is_equal_to_sum_even(8) == True\n \"\"\"\n return n % 4 == 0 and n > 0\n"], ["def special_factorial(n):\n \"\"\"The Brazilian factorial is defined as:\n brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n where n > 0\n\n For example:\n >>> special_factorial(4)\n 288\n\n The function will receive an integer as input and should return the special\n factorial of this integer.\n \"\"\"\n result = 1\n for i in range(1, n+1):\n result *= i\n result *= factorial(i-1)\n return result\n"], ["def fix_spaces(text):\n \"\"\"\n Given a string text, replace all spaces in it with underscores, \n and if a string has more than 2 consecutive spaces, \n then replace all consecutive spaces with - \n \n fix_spaces(\"Example\") == \"Example\"\n fix_spaces(\"Example 1\") == \"Example_1\"\n fix_spaces(\" Example 2\") == \"_Example_2\"\n fix_spaces(\" Example 3\") == \"_Example-3\"\n \"\"\"\n text = text.replace(\" \", \"-\").replace(\" \", \"_\")\n return text\n"], ["def file_name_check(file_name):\n \"\"\"Create a function which takes a string representing a file's name, and returns\n 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n A file's name is considered to be valid if and only if all the following conditions \n are met:\n - There should not be more than three digits ('0'-'9') in the file's name.\n - The file's name contains exactly one dot '.'\n - The substring before the dot should not be empty, and it starts with a letter from \n the latin alphapet ('a'-'z' and 'A'-'Z').\n - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n Examples:\n file_name_check(\"example.txt\") # => 'Yes'\n file_name_check(\"1example.dll\") # => 'No' (the name should start with a latin alphapet letter)\n \"\"\"\n if len(file_name) > 255: # file name length should not exceed 255 characters\n return 'No'\n if sum(c.isdigit() for c in file_name) > 3: # there should not be more than three digits\n return 'No'\n if file_name.count('.') != 1: # there should be exactly one dot\n return 'No'\n name, ext = file_name.split('.')\n if not name or not name[0].isalpha(): # substring before dot should not be empty and start with a letter\n return 'No'\n if ext not in ['txt', 'exe', 'dll']: # substring after dot should be one of these: ['txt', 'exe', 'dll']\n return 'No'\n return 'Yes'\n"], ["def sum_squares(lst):\n \"\"\"\"\n This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n \n Examples:\n For lst = [1,2,3] the output should be 6\n For lst = [] the output should be 0\n For lst = [-1,-5,2,-1,-5] the output should be -126\n \"\"\"\n result = 0\n for i in range(len(lst)):\n if i % 3 == 0:\n result += lst[i] ** 2\n elif i % 4 == 0:\n result += lst[i] ** 3\n else:\n result += lst[i]\n return result\n"], ["def words_in_sentence(sentence):\n \"\"\"\n You are given a string representing a sentence,\n the sentence contains some words separated by a space,\n and you have to return a string that contains the words from the original sentence,\n whose lengths are prime numbers,\n the order of the words in the new string should be the same as the original one.\n\n Example 1:\n Input: sentence = \"This is a test\"\n Output: \"is\"\n\n Example 2:\n Input: sentence = \"lets go for swimming\"\n Output: \"go for\"\n\n Constraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n \"\"\"\n def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n\n words = sentence.split()\n prime_words = [word for word in words if is_prime(len(word))]\n return ' '.join(prime_words)\n"], ["def simplify(x, n):\n \"\"\"Your task is to implement a function that will simplify the expression\n x * n. The function returns True if x * n evaluates to a whole number and False\n otherwise. Both x and n, are string representation of a fraction, and have the following format,\n / where both numerator and denominator are positive whole numbers.\n\n You can assume that x, and n are valid fractions, and do not have zero as denominator.\n\n simplify(\"1/5\", \"5/1\") = True\n simplify(\"1/6\", \"2/1\") = False\n simplify(\"7/10\", \"10/2\") = False\n \"\"\"\n x_num, x_denom = map(int, x.split('/'))\n n_num, n_denom = map(int, n.split('/'))\n product_num = x_num * n_num\n product_denom = x_denom * n_denom\n return product_num % product_denom == 0\n"], ["def order_by_points(nums):\n \"\"\"\n Write a function which sorts the given list of integers\n in ascending order according to the sum of their digits.\n Note: if there are several items with similar sum of their digits,\n order them based on their index in original list.\n\n For example:\n >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n >>> order_by_points([]) == []\n \"\"\"\n def sum_digits(n):\n return sum(int(digit) for digit in str(abs(n)))\n return sorted(nums, key=lambda x: (sum_digits(x), nums.index(x)))\n"], ["def specialFilter(nums):\n \"\"\"Write a function that takes an array of numbers as input and returns \n the number of elements in the array that are greater than 10 and both \n first and last digits of a number are odd (1, 3, 5, 7, 9).\n For example:\n specialFilter([15, -73, 14, -15]) => 1 \n specialFilter([33, -2, -3, 45, 21, 109]) => 2\n \"\"\"\n count = 0\n for num in nums:\n if num > 10 and str(num)[0] in '13579' and str(num)[-1] in '13579':\n count += 1\n return count\n"], ["def get_max_triples(n):\n \"\"\"\n You are given a positive integer n. You have to create an integer array a of length n.\n For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n\n Example :\n Input: n = 5\n Output: 1\n Explanation: \n a = [1, 3, 7, 13, 21]\n The only valid triple is (1, 7, 13).\n \"\"\"\n a = [i*i - i + 1 for i in range(1, n+1)]\n count = 0\n for i in range(n-2):\n for j in range(i+1, n-1):\n for k in range(j+1, n):\n if (a[i] + a[j] + a[k]) % 3 == 0:\n count += 1\n return count\n"], ["def bf(planet1, planet2):\n '''\n There are eight planets in our solar system: the closerst to the Sun \n is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n Uranus, Neptune.\n Write a function that takes two planet names as strings planet1 and planet2. \n The function should return a tuple containing all planets whose orbits are \n located between the orbit of planet1 and the orbit of planet2, sorted by \n the proximity to the sun. \n The function should return an empty tuple if planet1 or planet2\n are not correct planet names. \n Examples\n bf(\"Jupiter\", \"Neptune\") ==> (\"Saturn\", \"Uranus\")\n bf(\"Earth\", \"Mercury\") ==> (\"Venus\")\n bf(\"Mercury\", \"Uranus\") ==> (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\n '''\n planets = (\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\")\n if planet1 not in planets or planet2 not in planets:\n return ()\n else:\n start = planets.index(planet1)\n end = planets.index(planet2)\n if start > end:\n start, end = end, start\n return tuple(planets[start+1:end])\n"], ["def sorted_list_sum(lst):\n \"\"\"Write a function that accepts a list of strings as a parameter,\n deletes the strings that have odd lengths from it,\n and returns the resulted list with a sorted order,\n The list is always a list of strings and never an array of numbers,\n and it may contain duplicates.\n The order of the list should be ascending by length of each word, and you\n should return the list sorted by that rule.\n If two words have the same length, sort the list alphabetically.\n The function should return a list of strings in sorted order.\n You may assume that all words will have the same length.\n For example:\n assert list_sort([\"aa\", \"a\", \"aaa\"]) => [\"aa\"]\n assert list_sort([\"ab\", \"a\", \"aaa\", \"cd\"]) => [\"ab\", \"cd\"]\n \"\"\"\n lst = [word for word in lst if len(word) % 2 == 0]\n lst.sort(key=lambda x: (len(x), x))\n return lst\n"], ["def x_or_y(n, x, y):\n \"\"\"A simple program which should return the value of x if n is \n a prime number and should return the value of y otherwise.\n\n Examples:\n for x_or_y(7, 34, 12) == 34\n for x_or_y(15, 8, 5) == 5\n \n \"\"\"\n if n < 2:\n return y\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return y\n return x\n"], ["def double_the_difference(lst):\n '''\n Given a list of numbers, return the sum of squares of the numbers\n in the list that are odd. Ignore numbers that are negative or not integers.\n \n double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10\n double_the_difference([-1, -2, 0]) == 0\n double_the_difference([9, -2]) == 81\n double_the_difference([0]) == 0 \n \n If the input list is empty, return 0.\n '''\n result = 0\n for num in lst:\n if isinstance(num, int) and num % 2 != 0:\n result += num ** 2\n return result\n"], ["def compare(game,guess):\n \"\"\"I think we all remember that feeling when the result of some long-awaited\n event is finally known. The feelings and thoughts you have at that moment are\n definitely worth noting down and comparing.\n Your task is to determine if a person correctly guessed the results of a number of matches.\n You are given two arrays of scores and guesses of equal length, where each index shows a match. \n Return an array of the same length denoting how far off each guess was. If they have guessed correctly,\n the value is 0, and if not, the value is the absolute difference between the guess and the score.\n \n \n example:\n\n compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]\n compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]\n \"\"\"\n diff = []\n for i in range(len(game)):\n if game[i] == guess[i]:\n diff.append(0)\n else:\n diff.append(abs(game[i]-guess[i]))\n return diff\n"], ["def Strongest_Extension(class_name, extensions):\n \"\"\"You will be given the name of a class (a string) and a list of extensions.\n The extensions are to be used to load additional classes to the class. The\n strength of the extension is as follows: Let CAP be the number of the uppercase\n letters in the extension's name, and let SM be the number of lowercase letters \n in the extension's name, the strength is given by the fraction CAP - SM. \n You should find the strongest extension and return a string in this \n format: ClassName.StrongestExtensionName.\n If there are two or more extensions with the same strength, you should\n choose the one that comes first in the list.\n For example, if you are given \"Slices\" as the class and a list of the\n extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n (its strength is -1).\n Example:\n for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'\n \"\"\"\n max_strength = float('-inf')\n strongest_extension = ''\n for extension in extensions:\n cap_count = sum(1 for c in extension if c.isupper())\n sm_count = sum(1 for c in extension if c.islower())\n strength = cap_count - sm_count\n if strength > max_strength:\n max_strength = strength\n strongest_extension = extension\n return f\"{class_name}.{strongest_extension}\"\n"], ["def cycpattern_check(a , b):\n \"\"\"You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word\n cycpattern_check(\"abcd\",\"abd\") => False\n cycpattern_check(\"hello\",\"ell\") => True\n cycpattern_check(\"whassup\",\"psus\") => False\n cycpattern_check(\"abab\",\"baa\") => True\n cycpattern_check(\"efef\",\"eeff\") => False\n cycpattern_check(\"himenss\",\"simen\") => True\n\n \"\"\"\n if b in a*2:\n return True\n else:\n return False\n"], ["def even_odd_count(num):\n \"\"\"Given an integer. return a tuple that has the number of even and odd digits respectively.\n\n Example:\n even_odd_count(-12) ==> (1, 1)\n even_odd_count(123) ==> (1, 2)\n \"\"\"\n num = abs(num)\n even_count = 0\n odd_count = 0\n for digit in str(num):\n if int(digit) % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n return (even_count, odd_count)\n"], ["def int_to_mini_roman(number):\n \"\"\"\n Given a positive integer, obtain its roman numeral equivalent as a string,\n and return it in lowercase.\n Restrictions: 1 <= num <= 1000\n\n Examples:\n >>> int_to_mini_roman(19) == 'xix'\n >>> int_to_mini_roman(152) == 'clii'\n >>> int_to_mini_roman(426) == 'cdxxvi'\n \"\"\"\n roman_numerals = {1000: 'm', 900: 'cm', 500: 'd', 400: 'cd', 100: 'c', 90: 'xc', 50: 'l', 40: 'xl', 10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i'}\n result = ''\n for value, numeral in roman_numerals.items():\n while number >= value:\n result += numeral\n number -= value\n return result.lower()\n"], ["def right_angle_triangle(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return True if the three\n sides form a right-angled triangle, False otherwise.\n A right-angled triangle is a triangle in which one angle is right angle or \n 90 degree.\n Example:\n right_angle_triangle(3, 4, 5) == True\n right_angle_triangle(1, 2, 3) == False\n '''\n sides = [a, b, c]\n sides.sort()\n return sides[0]**2 + sides[1]**2 == sides[2]**2\n"], ["def find_max(words):\n \"\"\"Write a function that accepts a list of strings.\n The list contains different words. Return the word with maximum number\n of unique characters. If multiple strings have maximum number of unique\n characters, return the one which comes first in lexicographical order.\n\n find_max([\"name\", \"of\", \"string\"]) == \"string\"\n find_max([\"name\", \"enam\", \"game\"]) == \"enam\"\n find_max([\"aaaaaaa\", \"bb\" ,\"cc\"]) == \"\"aaaaaaa\"\n \"\"\"\n max_word = \"\"\n max_unique_chars = 0\n for word in words:\n unique_chars = set(word)\n num_unique_chars = len(unique_chars)\n if num_unique_chars > max_unique_chars or (num_unique_chars == max_unique_chars and word < max_word):\n max_word = word\n max_unique_chars = num_unique_chars\n return max_word\n"], ["def eat(number, need, remaining):\n \"\"\"\n You're a hungry rabbit, and you already have eaten a certain number of carrots,\n but now you need to eat more carrots to complete the day's meals.\n you should return an array of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\n if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n \n Example:\n * eat(5, 6, 10) -> [11, 4]\n * eat(4, 8, 9) -> [12, 1]\n * eat(1, 10, 10) -> [11, 0]\n * eat(2, 11, 5) -> [7, 0]\n \n Variables:\n @number : integer\n the number of carrots that you have eaten.\n @need : integer\n the number of carrots that you need to eat.\n @remaining : integer\n the number of remaining carrots thet exist in stock\n \n Constrain:\n * 0 <= number <= 1000\n * 0 <= need <= 1000\n * 0 <= remaining <= 1000\n\n Have fun :)\n \"\"\"\n total = number + need\n left = remaining - need\n if left < 0:\n left = 0\n return [total, left]\n"], ["def do_algebra(operator, operand):\n \"\"\"\n Given two lists operator, and operand. The first list has basic algebra operations, and \n the second list is a list of integers. Use the two given lists to build the algebric \n expression and return the evaluation of this expression.\n\n The basic algebra operations:\n Addition ( + ) \n Subtraction ( - ) \n Multiplication ( * ) \n Floor division ( // ) \n Exponentiation ( ** ) \n\n Example:\n operator['+', '*', '-']\n array = [2, 3, 4, 5]\n result = 2 + 3 * 4 - 5\n => result = 9\n\n Note:\n The length of operator list is equal to the length of operand list minus one.\n Operand is a list of of non-negative integers.\n Operator list has at least one operator, and operand list has at least two operands.\n\n \"\"\"\n expression = str(operand[0])\n for i in range(len(operator)):\n expression += operator[i] + str(operand[i+1])\n return eval(expression)\n"], ["def solve(s):\n \"\"\"You are given a string s.\n if s[i] is a letter, reverse its case from lower to upper or vise versa, \n otherwise keep it as it is.\n If the string contains no letters, reverse the string.\n The function should return the resulted string.\n Examples\n solve(\"1234\") = \"4321\"\n solve(\"ab\") = \"AB\"\n solve(\"#a@C\") = \"#A@c\"\n \"\"\"\n if not any(c.isalpha() for c in s):\n return s[::-1]\n else:\n result = \"\"\n for c in s:\n if c.isalpha():\n if c.islower():\n result += c.upper()\n else:\n result += c.lower()\n else:\n result += c\n return result\n"], ["def string_to_md5(text):\n \"\"\"\n Given a string 'text', return its md5 hash equivalent string.\n If 'text' is an empty string, return None.\n\n >>> string_to_md5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'\n \"\"\"\n if not text:\n return None\n else:\n md5_hash = hashlib.md5(text.encode('utf-8')).hexdigest()\n return md5_hash\n"], ["def generate_integers(a, b):\n \"\"\"\n Given two positive integers a and b, return the even digits between a\n and b, in ascending order.\n\n For example:\n generate_integers(2, 8) => [2, 4, 6, 8]\n generate_integers(8, 2) => [2, 4, 6, 8]\n generate_integers(10, 14) => []\n \"\"\"\n result = []\n for i in range(a, b+1):\n if i % 2 == 0:\n result.append(i)\n return result\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-cpp_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-cpp_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..8ca2c131edb86e1b76e7a5eda56e440b2bb1d599 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-cpp_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["#include\n#include\n// Check if in given vector of numbers, are any two numbers closer to each other than\n// given threshold.\n// >>> has_close_elements((std::vector({(float)1.0f, (float)2.0f, (float)3.0f})), (0.5f))\n// (false)\n// >>> has_close_elements((std::vector({(float)1.0f, (float)2.8f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f})), (0.3f))\n// (true)\nbool has_close_elements(std::vector numbers, float threshold) {\n for (int i = 0; i < numbers.size(); i++) {\n for (int j = i + 1; j < numbers.size(); j++) {\n if (std::abs(numbers[i] - numbers[j]) <= threshold) {\n return true;\n }\n }\n }\n return false;"], ["#include\n#include\n// Given a positive integer n, you have to make a pile of n levels of stones.\n// The first level has n stones.\n// The number of stones in the next level is:\n// - the next odd number if n is odd.\n// - the next even number if n is even.\n// Return the number of stones in each level in a vector, where element at index\n// i represents the number of stones in the level (i+1).\n// Examples:\n// >>> make_a_pile((3))\n// (std::vector({(long)3, (long)5, (long)7}))\nstd::vector make_a_pile(long n) {\n std::vector result;\n result.push_back(n);\n while (n > 1) {\n if (n % 2 == 0) {\n n = n / 2;\n } else {\n n = n * 3 + 1;\n }\n result.push_back(n);\n }\n return result;"], ["#include\n#include\n// You will be given a string of words separated by commas or spaces. Your task is\n// to split the string into words and return a vector of the words.\n// For example:\n// >>> words_string((\"Hi, my name is John\"))\n// (std::vector({(std::string)\"Hi\", (std::string)\"my\", (std::string)\"name\", (std::string)\"is\", (std::string)\"John\"}))\n// >>> words_string((\"One, two, three, four, five, six\"))\n// (std::vector({(std::string)\"One\", (std::string)\"two\", (std::string)\"three\", (std::string)\"four\", (std::string)\"five\", (std::string)\"six\"}))\nstd::vector words_string(std::string s) {\n std::vector words;\n std::stringstream ss(s);\n std::string word;\n while (ss >> word) {\n words.push_back(word);\n }\n return words;"], ["#include\n#include\n// This function takes two positive numbers x and y and returns the\n// biggest even integer number that is in the range [x, y] inclusive. If \n// there's no such number, then the function should return -1.\n// For example:\n// >>> choose_num((12), (15))\n// (14)\n// >>> choose_num((13), (12))\n// (-1)\nlong choose_num(long x, long y) {\n if (x % 2 != 0) {\n x++; // make x even\n }\n if (x > y) {\n return -1; // no even number in range\n }\n return x;"], ["#include\n#include\nunion Union_std_string_long{\n std::string f0;\n long f1; Union_std_string_long(std::string _f0) : f0(_f0) {}\n Union_std_string_long(long _f1) : f1(_f1) {}\n ~Union_std_string_long() {}\n bool operator==(std::string f) {\n return f0 == f ;\n } bool operator==(long f) {\n return f1 == f ;\n }\n};\n// You are given two positive integers n and m, and your task is to compute the\n// average of the integers from n through m (including n and m). \n// Round the answer to the nearest integer and convert that to binary.\n// If n is greater than m, return -1.\n// Example:\n// >>> rounded_avg((1), (5))\n// \"0b11\"\n// >>> rounded_avg((7), (5))\n// -1\n// >>> rounded_avg((10), (20))\n// \"0b1111\"\n// >>> rounded_avg((20), (33))\n// \"0b11010\"\nUnion_std_string_long rounded_avg(long n, long m) {\n if (n > m) {\n return -1;\n }\n long sum = 0;\n for (long i = n; i <= m; i++) {\n sum += i;\n }\n long avg = (sum + m - n) / 2;\n std::string binary = std::bitset<64>(avg).to_string();\n return binary;"], ["#include\n#include\n// Given a vector of positive integers x. return a sorted vector of all \n// elements that hasn't any even digit.\n// Note: Returned vector should be sorted in increasing order.\n// For example:\n// >>> unique_digits((std::vector({(long)15, (long)33, (long)1422, (long)1})))\n// (std::vector({(long)1, (long)15, (long)33}))\n// >>> unique_digits((std::vector({(long)152, (long)323, (long)1422, (long)10})))\n// (std::vector())\nstd::vector unique_digits(std::vector x) {\n std::vector result;\n for (auto num : x) {\n bool has_even_digit = false;\n while (num > 0) {\n int digit = num % 10;\n if (digit % 2 == 0) {\n has_even_digit = true;\n break;\n }\n num /= 10;\n }\n if (!has_even_digit) {\n result.push_back(num);\n }\n }\n std::sort(result.begin(), result.end());\n return result;"], ["#include\n#include\n// Given a vector of integers, sort the integers that are between 1 and 9 inclusive,\n// reverse the resulting vector, and then replace each digit by its corresponding name from\n// \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n// For example:\n// >>> by_length((std::vector({(long)2, (long)1, (long)1, (long)4, (long)5, (long)8, (long)2, (long)3})))\n// (std::vector({(std::string)\"Eight\", (std::string)\"Five\", (std::string)\"Four\", (std::string)\"Three\", (std::string)\"Two\", (std::string)\"Two\", (std::string)\"One\", (std::string)\"One\"}))\n// If the vector is empty, return an empty vector:\n// >>> by_length((std::vector()))\n// (std::vector())\n// If the vector has any strange number ignore it:\n// >>> by_length((std::vector({(long)1, (long)-1, (long)55})))\n// (std::vector({(std::string)\"One\"}))\nstd::vector by_length(std::vector arr) {\n std::vector result;\n std::vector temp;\n for(int i=0;i=1 && arr[i]<=9){\n temp.push_back(arr[i]);\n }\n }\n std::sort(temp.begin(),temp.end());\n std::reverse(temp.begin(),temp.end());\n for(int i=0;i\n#include\n// Implement the function f that takes n as a parameter,\n// and returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even\n// or the sum of numbers from 1 to i otherwise.\n// i starts from 1.\n// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n// Example:\n// >>> f((5))\n// (std::vector({(long)1, (long)2, (long)6, (long)24, (long)15}))\nstd::vector f(long n) {\n std::vector result(n);\n for (long i = 1; i <= n; i++) {\n if (i % 2 == 0) {\n long factorial = 1;\n for (long j = 2; j <= i; j++) {\n factorial *= j;\n }\n result[i-1] = factorial;\n } else {\n long sum = 0;\n for (long j = 1; j <= i; j++) {\n sum += j;\n }\n result[i-1] = sum;\n }\n }\n return result;"], ["#include\n#include\n// Given a positive integer n, return a tuple that has the number of even and odd\n// integer palindromes that fall within the range(1, n), inclusive.\n// Example 1:\n// >>> even_odd_palindrome((3))\n// (std::make_tuple(1, 2))\n// Explanation:\n// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n// Example 2:\n// >>> even_odd_palindrome((12))\n// (std::make_tuple(4, 6))\n// Explanation:\n// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n// Note:\n// 1. 1 <= n <= 10^3\n// 2. returned tuple has the number of even and odd integer palindromes respectively.\nstd::tuple even_odd_palindrome(long n) {\n long even_count = 0, odd_count = 0;\n for (long i = 1; i <= n; i++) {\n std::string num_str = std::to_string(i);\n std::string rev_num_str = num_str;\n std::reverse(rev_num_str.begin(), rev_num_str.end());\n if (num_str == rev_num_str) {\n if (i % 2 == 0) {\n even_count++;\n } else {\n odd_count++;\n }\n }\n }\n return std::make_tuple(even_count, odd_count);"], ["#include\n#include\n// Write a function count_nums which takes a vector of integers and returns\n// the number of elements which has a sum of digits > 0.\n// If a number is negative, then its first signed digit will be negative:\n// e.g. -123 has signed digits -1, 2, and 3.\n// >>> count_nums((std::vector()))\n// (0)\n// >>> count_nums((std::vector({(long)-1, (long)11, (long)-11})))\n// (1)\n// >>> count_nums((std::vector({(long)1, (long)1, (long)2})))\n// (3)\nlong count_nums(std::vector arr) {\n long count = 0;\n for (long num : arr) {\n long sum = 0;\n long n = abs(num);\n while (n > 0) {\n sum += n % 10;\n n /= 10;\n }\n if (sum > 0) {\n count++;\n }\n }\n return count;"], ["#include\n#include\n// We have a vector 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n// numbers in the vector will be randomly ordered. Your task is to determine if\n// it is possible to get a vector sorted in non-decreasing order by performing \n// the following operation on the given vector:\n// You are allowed to perform right shift operation any number of times.\n// One right shift operation means shifting all elements of the vector by one\n// position in the right direction. The last element of the vector will be moved to\n// the starting position in the vector i.e. 0th index. \n// If it is possible to obtain the sorted vector by performing the above operation\n// then return true else return false.\n// If the given vector is empty then return true.\n// Note: The given vector is guaranteed to have unique elements.\n// For Example:\n// >>> move_one_ball((std::vector({(long)3, (long)4, (long)5, (long)1, (long)2})))\n// (true)\n// Explanation: By performin 2 right shift operations, non-decreasing order can\n// be achieved for the given vector.\n// >>> move_one_ball((std::vector({(long)3, (long)5, (long)4, (long)1, (long)2})))\n// (false)\n// Explanation:It is not possible to get non-decreasing order for the given\n// vector by performing any number of right shift operations.\nbool move_one_ball(std::vector arr) {\n int n = arr.size();\n if(n == 0) return true;\n int max_index = 0;\n for(int i = 1; i < n; i++) {\n if(arr[i] > arr[max_index]) {\n max_index = i;\n }\n }\n int count = 0;\n for(int i = max_index; i < n; i++) {\n if(arr[i] < arr[i-1]) {\n count++;\n }\n }\n for(int i = 0; i < max_index; i++) {\n if(arr[i] > arr[i+1]) {\n count++;\n }\n }\n return count <= 1;"], ["#include\n#include\n// Find the shortest palindrome that begins with a supplied string.\n// Algorithm idea is simple:\n// - Find the longest postfix of supplied string that is a palindrome.\n// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n// >>> make_palindrome((\"\"))\n// (\"\")\n// >>> make_palindrome((\"cat\"))\n// (\"catac\")\n// >>> make_palindrome((\"cata\"))\n// (\"catac\")\nstd::string make_palindrome(std::string string) {\n int n = string.length();\n int i = 0;\n int j = n - 1;\n while (i < j) {\n if (string[i] == string[j]) {\n i++;\n j--;\n } else {\n i = 0;\n j--;\n }\n }\n std::string prefix = string.substr(0, i);\n std::string suffix = string.substr(i, n - i);\n std::reverse(prefix.begin(), prefix.end());\n return prefix + suffix;"], ["#include\n#include\n// In this problem, you will implement a function that takes two vectors of numbers,\n// and determines whether it is possible to perform an exchange of elements\n// between them to make lst1 a vector of only even numbers.\n// There is no limit on the number of exchanged elements between lst1 and lst2.\n// If it is possible to exchange elements between the lst1 and lst2 to make\n// all the elements of lst1 to be even, return \"YES\".\n// Otherwise, return \"NO\".\n// For example:\n// >>> exchange((std::vector({(long)1, (long)2, (long)3, (long)4})), (std::vector({(long)1, (long)2, (long)3, (long)4})))\n// (\"YES\")\n// >>> exchange((std::vector({(long)1, (long)2, (long)3, (long)4})), (std::vector({(long)1, (long)5, (long)3, (long)4})))\n// (\"NO\")\n// It is assumed that the input vectors will be non-empty.\nstd::string exchange(std::vector lst1, std::vector lst2) {\n int even_count = 0;\n int odd_count = 0;\n for (auto num : lst1) {\n if (num % 2 == 0) {\n even_count++;\n } else {\n odd_count++;\n }\n }\n for (auto num : lst2) {\n if (num % 2 == 0) {\n even_count++;\n } else {\n odd_count++;\n }\n }\n if (even_count == lst1.size()) {\n return \"YES\";\n } else if (odd_count == lst1.size()) {\n return \"NO\";\n } else {\n return \"YES\";\n }"], ["#include\n#include\n// Given a string representing a space separated lowercase letters, return a map\n// of the letter with the most repetition and containing the corresponding count.\n// If several letters have the same occurrence, return all of them.\n// Example:\n// >>> histogram((\"a b c\"))\n// (std::map({{\"a\", 1}, {\"b\", 1}, {\"c\", 1}}))\n// >>> histogram((\"a b b a\"))\n// (std::map({{\"a\", 2}, {\"b\", 2}}))\n// >>> histogram((\"a b c a b\"))\n// (std::map({{\"a\", 2}, {\"b\", 2}}))\n// >>> histogram((\"b b b b a\"))\n// (std::map({{\"b\", 4}}))\n// >>> histogram((\"\"))\n// (std::map())\nstd::map histogram(std::string test) {\n std::map result;\n std::istringstream iss(test);\n std::string word;\n while(iss >> word) {\n result[word]++;\n }\n long max_count = 0;\n for(auto it = result.begin(); it != result.end(); it++) {\n if(it->second > max_count) {\n max_count = it->second;\n }\n }\n std::map final_result;\n for(auto it = result.begin(); it != result.end(); it++) {\n if(it->second == max_count) {\n final_result[it->first] = it->second;\n }\n }\n return final_result;"], ["#include\n#include\n// Task\n// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n// then check if the result string is palindrome.\n// A string is called palindrome if it reads the same backward as forward.\n// You should return a tuple containing the result string and true/false for the check.\n// Example\n// >>> reverse_delete((\"abcde\"), (\"ae\"))\n// (std::make_tuple(\"bcd\", false))\n// >>> reverse_delete((\"abcdef\"), (\"b\"))\n// (std::make_tuple(\"acdef\", false))\n// >>> reverse_delete((\"abcdedcba\"), (\"ab\"))\n// (std::make_tuple(\"cdedc\", true))\nstd::tuple reverse_delete(std::string s, std::string c) {\n std::string result = \"\";\n for (int i = 0; i < s.length(); i++) {\n if (c.find(s[i]) == std::string::npos) {\n result += s[i];\n }\n }\n std::string reversed = result;\n std::reverse(reversed.begin(), reversed.end());\n bool is_palindrome = (result == reversed);\n return std::make_tuple(result, is_palindrome);"], ["#include\n#include\n// Given a vector of strings, where each string consists of only digits, return a vector.\n// Each element i of the output should be \"the number of odd elements in the\n// string i of the input.\" where all the i's should be replaced by the number\n// of odd digits in the i'th string of the input.\n// >>> odd_count((std::vector({(std::string)\"1234567\"})))\n// (std::vector({(std::string)\"the number of odd elements 4n the str4ng 4 of the 4nput.\"}))\n// >>> odd_count((std::vector({(std::string)\"3\", (std::string)\"11111111\"})))\n// (std::vector({(std::string)\"the number of odd elements 1n the str1ng 1 of the 1nput.\", (std::string)\"the number of odd elements 8n the str8ng 8 of the 8nput.\"}))\nstd::vector odd_count(std::vector lst) {\n std::vector result;\n for (auto str : lst) {\n int count = 0;\n for (auto c : str) {\n if (c % 2 != 0) {\n count++;\n }\n }\n result.push_back(\"the number of odd elements \" + std::to_string(count) + \"n the str\" + std::to_string(count) + \"ng \" + std::to_string(count) + \"nput.\");\n }\n return result;"], ["#include\n#include\n// Given a vector of integers nums, find the minimum sum of any non-empty sub-vector\n// of nums.\n// Example\n// >>> minSubArraySum((std::vector({(long)2, (long)3, (long)4, (long)1, (long)2, (long)4})))\n// (1)\n// >>> minSubArraySum((std::vector({(long)-1, (long)-2, (long)-3})))\n// (-6)\nlong minSubArraySum(std::vector nums) {\n long min_sum = nums[0];\n long curr_sum = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n curr_sum = std::min(nums[i], curr_sum + nums[i]);\n min_sum = std::min(min_sum, curr_sum);\n }\n return min_sum;"], ["#include\n#include\n// You are given a rectangular grid of wells. Each row represents a single well,\n// and each 1 in a row represents a single unit of water.\n// Each well has a corresponding bucket that can be used to extract water from it, \n// and all buckets have the same capacity.\n// Your task is to use the buckets to empty the wells.\n// Output the number of times you need to lower the buckets.\n// Example 1:\n// >>> max_fill((std::vector>({(std::vector)std::vector({(long)0, (long)0, (long)1, (long)0}), (std::vector)std::vector({(long)0, (long)1, (long)0, (long)0}), (std::vector)std::vector({(long)1, (long)1, (long)1, (long)1})})), (1))\n// (6)\n// Example 2:\n// >>> max_fill((std::vector>({(std::vector)std::vector({(long)0, (long)0, (long)1, (long)1}), (std::vector)std::vector({(long)0, (long)0, (long)0, (long)0}), (std::vector)std::vector({(long)1, (long)1, (long)1, (long)1}), (std::vector)std::vector({(long)0, (long)1, (long)1, (long)1})})), (2))\n// (5)\n// Example 3:\n// >>> max_fill((std::vector>({(std::vector)std::vector({(long)0, (long)0, (long)0}), (std::vector)std::vector({(long)0, (long)0, (long)0})})), (5))\n// (0)\n// Constraints:\n// * all wells have the same length\n// * 1 <= grid.length <= 10^2\n// * 1 <= grid[:,1].length <= 10^2\n// * grid[i][j] -> 0 | 1\n// * 1 <= capacity <= 10\nlong max_fill(std::vector> grid, long capacity) {\n long n = grid.size();\n long m = grid[0].size();\n long ans = 0;\n for (long i = 0; i < n; i++) {\n long curr = 0;\n for (long j = 0; j < m; j++) {\n curr += grid[i][j];\n if (curr >= capacity) {\n ans += curr / capacity;\n curr %= capacity;\n }\n }\n ans += curr;\n }\n return ans;"], ["#include\n#include\n// In this Kata, you have to sort a vector of non-negative integers according to\n// number of ones in their binary representation in ascending order.\n// For similar number of ones, sort based on decimal value.\n// It must be implemented like this:\n// >>> sort_array((std::vector({(long)1, (long)5, (long)2, (long)3, (long)4})))\n// (std::vector({(long)1, (long)2, (long)3, (long)4, (long)5}))\n// >>> sort_array((std::vector({(long)-2, (long)-3, (long)-4, (long)-5, (long)-6})))\n// (std::vector({(long)-6, (long)-5, (long)-4, (long)-3, (long)-2}))\n// >>> sort_array((std::vector({(long)1, (long)0, (long)2, (long)3, (long)4})))\n// (std::vector({(long)0, (long)1, (long)2, (long)3, (long)4}))\nstd::vector sort_array(std::vector arr) {\n std::sort(arr.begin(), arr.end(), [](long a, long b) {\n int count_a = __builtin_popcount(a);\n int count_b = __builtin_popcount(b);\n if (count_a == count_b) {\n return a < b;\n }\n return count_a < count_b;\n });\n return arr;"], ["#include\n#include\n// Given a string s and a natural number n, you have been tasked to implement \n// a function that returns a vector of all words from string s that contain exactly \n// n consonants, in order these words appear in the string s.\n// If the string s is empty then the function should return an empty vector.\n// Note: you may assume the input string contains only letters and spaces.\n// Examples:\n// >>> select_words((\"Mary had a little lamb\"), (4))\n// (std::vector({(std::string)\"little\"}))\n// >>> select_words((\"Mary had a little lamb\"), (3))\n// (std::vector({(std::string)\"Mary\", (std::string)\"lamb\"}))\n// >>> select_words((\"simple white space\"), (2))\n// (std::vector())\n// >>> select_words((\"Hello world\"), (4))\n// (std::vector({(std::string)\"world\"}))\n// >>> select_words((\"Uncle sam\"), (3))\n// (std::vector({(std::string)\"Uncle\"}))\nstd::vector select_words(std::string s, long n) {\n std::vector result;\n std::stringstream ss(s);\n std::string word;\n while (ss >> word) {\n long consonant_count = 0;\n for (char c : word) {\n if (std::tolower(c) != 'a' && std::tolower(c) != 'e' && std::tolower(c) != 'i' && std::tolower(c) != 'o' && std::tolower(c) != 'u') {\n consonant_count++;\n }\n }\n if (consonant_count == n) {\n result.push_back(word);\n }\n }\n return result;"], ["#include\n#include\n// You are given a word. Your task is to find the closest vowel that stands between \n// two consonants from the right side of the word (case sensitive).\n// Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n// find any vowel met the above condition. \n// You may assume that the given string contains English letter only.\n// Example:\n// >>> get_closest_vowel((\"yogurt\"))\n// (\"u\")\n// >>> get_closest_vowel((\"FULL\"))\n// (\"U\")\n// >>> get_closest_vowel((\"quick\"))\n// (\"\")\n// >>> get_closest_vowel((\"ab\"))\n// (\"\")\nstd::string get_closest_vowel(std::string word) {\n std::string vowels = \"aeiouAEIOU\";\n std::string result = \"\";\n int n = word.length();\n for (int i = n - 1; i >= 0; i--) {\n if (vowels.find(word[i]) != std::string::npos) {\n if (i > 0 && i < n - 1 && vowels.find(word[i - 1]) == std::string::npos && vowels.find(word[i + 1]) == std::string::npos) {\n result = word[i];\n break;\n }\n }\n }\n return result;"], ["#include\n#include\n// You are given a vector of two strings, both strings consist of open\n// parentheses '(' or close parentheses ')' only.\n// Your job is to check if it is possible to concatenate the two strings in\n// some order, that the resulting string will be good.\n// A string S is considered to be good if and only if all parentheses in S\n// are balanced. For example: the string '(())()' is good, while the string\n// '())' is not.\n// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n// Examples:\n// >>> match_parens((std::vector({(std::string)\"()(\", (std::string)\")\"})))\n// (\"Yes\")\n// >>> match_parens((std::vector({(std::string)\")\", (std::string)\")\"})))\n// (\"No\")\nstd::string match_parens(std::vector lst) {\n int count = 0;\n for (auto s : lst) {\n for (auto c : s) {\n if (c == '(') {\n count++;\n } else if (c == ')') {\n count--;\n }\n }\n }\n return count == 0 ? \"Yes\" : \"No\";"], ["#include\n#include\n// Input are two strings a and b consisting only of 1s and 0s.\n// Perform binary XOR on these inputs and return result also as a string.\n// >>> string_xor((\"010\"), (\"110\"))\n// (\"100\")\nstd::string string_xor(std::string a, std::string b) {\n assert(a.size() == b.size());\n std::string result = \"\";\n for (int i = 0; i < a.size(); i++) {\n if (a[i] == b[i]) {\n result += \"0\";\n } else {\n result += \"1\";\n }\n }\n return result;"], ["#include\n#include\n// Given a vector arr of integers and a positive integer k, return a sorted vector \n// of length k with the maximum k numbers in arr.\n// Example 1:\n// >>> maximum((std::vector({(long)-3, (long)-4, (long)5})), (3))\n// (std::vector({(long)-4, (long)-3, (long)5}))\n// Example 2:\n// >>> maximum((std::vector({(long)4, (long)-4, (long)4})), (2))\n// (std::vector({(long)4, (long)4}))\n// Example 3:\n// >>> maximum((std::vector({(long)-3, (long)2, (long)1, (long)2, (long)-1, (long)-2, (long)1})), (1))\n// (std::vector({(long)2}))\n// Note:\n// 1. The length of the vector will be in the range of [1, 1000].\n// 2. The elements in the vector will be in the range of [-1000, 1000].\n// 3. 0 <= k <= len(arr)\nstd::vector maximum(std::vector arr, long k) {\n std::sort(arr.begin(), arr.end(), std::greater());\n arr.resize(k);\n return arr;"], ["#include\n#include\n// Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions.\n// Examples\n// >>> solution((std::vector({(long)5, (long)8, (long)7, (long)1})))\n// (12)\n// >>> solution((std::vector({(long)3, (long)3, (long)3, (long)3, (long)3})))\n// (9)\n// >>> solution((std::vector({(long)30, (long)13, (long)24, (long)321})))\n// (0)\nlong solution(std::vector lst) {\n long sum = 0;\n for (int i = 0; i < lst.size(); i += 2) {\n if (lst[i] % 2 != 0) {\n sum += lst[i];\n }\n }\n return sum;"], ["#include\n#include\n// Given a non-empty vector of integers arr and an integer k, return\n// the sum of the elements with at most two digits from the first k elements of arr.\n// Example:\n// >>> add_elements((std::vector({(long)111, (long)21, (long)3, (long)4000, (long)5, (long)6, (long)7, (long)8, (long)9})), (4))\n// (24)\n// Constraints:\n// 1. 1 <= len(arr) <= 100\n// 2. 1 <= k <= len(arr)\nlong add_elements(std::vector arr, long k) {\n long sum = 0;\n for (int i = 0; i < k; i++) {\n if (arr[i] < 100) {\n sum += arr[i];\n }\n }\n return sum;"], ["#include\n#include\n// Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence.\n// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n// as follows: start with any positive integer n. Then each term is obtained from the \n// previous term as follows: if the previous term is even, the next term is one half of \n// the previous term. If the previous term is odd, the next term is 3 times the previous\n// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n// Note: \n// 1. Collatz(1) is [1].\n// 2. returned vector sorted in increasing order.\n// For example:\n// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n// >>> get_odd_collatz((5))\n// (std::vector({(long)1, (long)5}))\nstd::vector get_odd_collatz(long n) {\n std::vector collatz_seq;\n while (n != 1) {\n collatz_seq.push_back(n);\n if (n % 2 == 0) {\n n = n / 2;\n } else {\n n = 3 * n + 1;\n }\n }\n collatz_seq.push_back(1);\n std::vector odd_collatz_seq;\n for (auto num : collatz_seq) {\n if (num % 2 != 0) {\n odd_collatz_seq.push_back(num);\n }\n }\n std::sort(odd_collatz_seq.begin(), odd_collatz_seq.end());\n return odd_collatz_seq;"], ["#include\n#include\n// You have to write a function which validates a given date string and\n// returns true if the date is valid otherwise false.\n// The date is valid if all of the following rules are satisfied:\n// 1. The date string is not empty.\n// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n// 3. The months should not be less than 1 or higher than 12.\n// 4. The date should be in the format: mm-dd-yyyy\n// >>> valid_date((\"03-11-2000\"))\n// (true)\n// >>> valid_date((\"15-01-2012\"))\n// (false)\n// >>> valid_date((\"04-0-2040\"))\n// (false)\n// >>> valid_date((\"06-04-2020\"))\n// (true)\n// >>> valid_date((\"06/04/2020\"))\n// (false)\nbool valid_date(std::string date) {\n if (date.empty()) {\n return false;\n }\n std::vector date_parts;\n std::stringstream ss(date);\n std::string part;\n while (getline(ss, part, '-')) {\n date_parts.push_back(part);\n }\n if (date_parts.size() != 3) {\n return false;\n }\n int month = std::stoi(date_parts[0]);\n int day = std::stoi(date_parts[1]);\n int year = std::stoi(date_parts[2]);\n if (month < 1 || month > 12) {\n return false;\n }\n if (day < 1 || day > 31) {\n return false;\n }\n if (month == 2) {\n if (day > 29) {\n return false;\n }\n if (day == 29 && !((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) {\n return false;\n }\n }\n if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {\n return false;\n }\n return true;"], ["#include\n#include\nunion Union_std_vector_std_string__long{\n std::vector f0;\n long f1; Union_std_vector_std_string__long(std::vector _f0) : f0(_f0) {}\n Union_std_vector_std_string__long(long _f1) : f1(_f1) {}\n ~Union_std_vector_std_string__long() {}\n bool operator==(std::vector f) {\n return f0 == f ;\n } bool operator==(long f) {\n return f1 == f ;\n }\n};\n// Given a string of words, return a vector of words split on whitespace, if no whitespaces exists in the text you\n// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n// Examples\n// >>> split_words((\"Hello world!\"))\n// std::vector({(std::string)\"Hello\", (std::string)\"world!\"})\n// >>> split_words((\"Hello,world!\"))\n// std::vector({(std::string)\"Hello\", (std::string)\"world!\"})\n// >>> split_words((\"abcdef\"))\n// 3\nUnion_std_vector_std_string__long split_words(std::string txt) {\n std::vector words;\n std::stringstream ss(txt);\n std::string word;\n while (ss >> word) {\n words.push_back(word);\n }\n if (words.size() > 0) {\n return Union_std_vector_std_string__long(words);\n }\n int count = 0;\n for (char c : txt) {\n if (islower(c) && (c - 'a') % 2 == 0) {\n count++;\n }\n }\n return Union_std_vector_std_string__long(count);"], ["#include\n#include\n// Given a vector of numbers, return whether or not they are sorted\n// in ascending order. If vector has more than 1 duplicate of the same\n// number, return false. Assume no negative numbers and only integers.\n// Examples\n// >>> is_sorted((std::vector({(long)5})))\n// (true)\n// >>> is_sorted((std::vector({(long)1, (long)2, (long)3, (long)4, (long)5})))\n// (true)\n// >>> is_sorted((std::vector({(long)1, (long)3, (long)2, (long)4, (long)5})))\n// (false)\n// >>> is_sorted((std::vector({(long)1, (long)2, (long)3, (long)4, (long)5, (long)6})))\n// (true)\n// >>> is_sorted((std::vector({(long)1, (long)2, (long)3, (long)4, (long)5, (long)6, (long)7})))\n// (true)\n// >>> is_sorted((std::vector({(long)1, (long)3, (long)2, (long)4, (long)5, (long)6, (long)7})))\n// (false)\n// >>> is_sorted((std::vector({(long)1, (long)2, (long)2, (long)3, (long)3, (long)4})))\n// (true)\n// >>> is_sorted((std::vector({(long)1, (long)2, (long)2, (long)2, (long)3, (long)4})))\n// (false)\nbool is_sorted(std::vector lst) {\n std::set s(lst.begin(), lst.end());\n return s.size() == lst.size() && std::is_sorted(lst.begin(), lst.end());"], ["#include\n#include\n// You are given two intervals,\n// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n// The given intervals are closed which means that the interval (start, end)\n// includes both start and end.\n// For each given interval, it is assumed that its start is less or equal its end.\n// Your task is to determine whether the length of intersection of these two \n// intervals is a prime number.\n// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n// which its length is 1, which not a prime number.\n// If the length of the intersection is a prime number, return \"YES\",\n// otherwise, return \"NO\".\n// If the two intervals don't intersect, return \"NO\".\n// [input/output] samples:\n// >>> intersection((std::make_tuple(1, 2)), (std::make_tuple(2, 3)))\n// (\"NO\")\n// >>> intersection((std::make_tuple(-1, 1)), (std::make_tuple(0, 4)))\n// (\"NO\")\n// >>> intersection((std::make_tuple(-3, -1)), (std::make_tuple(-5, 5)))\n// (\"YES\")\nstd::string intersection(std::tuple interval1, std::tuple interval2) {\n long start1 = std::get<0>(interval1);\n long end1 = std::get<1>(interval1);\n long start2 = std::get<0>(interval2);\n long end2 = std::get<1>(interval2);\n long start = std::max(start1, start2);\n long end = std::min(end1, end2);\n long length = end - start + 1;\n if (length <= 1) {\n return \"NO\";\n }\n for (long i = 2; i * i <= length; i++) {\n if (length % i == 0) {\n return \"NO\";\n }\n }\n return \"YES\";"], ["#include\n#include\n// You are given a vector arr of integers and you need to return\n// sum of magnitudes of integers multiplied by product of all signs\n// of each number in the vector, represented by 1, -1 or 0.\n// Note: return None for empty arr.\n// Example:\n// >>> prod_signs((std::vector({(long)1, (long)2, (long)2, (long)-4})))\n// 9\n// >>> prod_signs((std::vector({(long)0, (long)1})))\n// 0\n// >>> prod_signs((std::vector()))\n// std::nullopt\nstd::optional prod_signs(std::vector arr) {\n if (arr.empty()) {\n return std::nullopt;\n }\n long sum = 0;\n long product = 1;\n for (auto num : arr) {\n sum += std::abs(num);\n if (num < 0) {\n product *= -1;\n } else if (num == 0) {\n product = 0;\n break;\n }\n }\n return sum * product;"], ["#include\n#include\n// Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n// each cell of the grid contains a value. Every integer in the range [1, N * N]\n// inclusive appears exactly once on the cells of the grid.\n// You have to find the minimum path of length k in the grid. You can start\n// from any cell, and in each step you can move to any of the neighbor cells,\n// in other words, you can go to cells which share an edge with you current\n// cell.\n// Please note that a path of length k means visiting exactly k cells (not\n// necessarily distinct).\n// You CANNOT go off the grid.\n// A path A (of length k) is considered less than a path B (of length k) if\n// after making the ordered vectors of the values on the cells that A and B go\n// through (let's call them lst_A and lst_B), lst_A is lexicographically less\n// than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n// lst_A[j] = lst_B[j].\n// It is guaranteed that the answer is unique.\n// Return an ordered vector of the values on the cells that the minimum path go through.\n// Examples: \n// >>> minPath((std::vector>({(std::vector)std::vector({(long)1, (long)2, (long)3}), (std::vector)std::vector({(long)4, (long)5, (long)6}), (std::vector)std::vector({(long)7, (long)8, (long)9})})), (3))\n// (std::vector({(long)1, (long)2, (long)1}))\n// >>> minPath((std::vector>({(std::vector)std::vector({(long)5, (long)9, (long)3}), (std::vector)std::vector({(long)4, (long)1, (long)6}), (std::vector)std::vector({(long)7, (long)8, (long)2})})), (1))\n// (std::vector({(long)1}))\nstd::vector minPath(std::vector> grid, long k) {\n long n = grid.size();\n std::vector> dp(n, std::vector(n, INT_MAX));\n std::vector>> parent(n, std::vector>(n, {-1, -1}));\n dp[0][0] = grid[0][0];\n for (long i = 0; i < n; i++) {\n for (long j = 0; j < n; j++) {\n if (i > 0 && dp[i - 1][j] < dp[i][j]) {\n dp[i][j] = dp[i - 1][j];\n parent[i][j] = {i - 1, j};\n }\n if (j > 0 && dp[i][j - 1] < dp[i][j]) {\n dp[i][j] = dp[i][j - 1];\n parent[i][j] = {i, j - 1};\n }\n dp[i][j] += grid[i][j];\n }\n }\n std::vector path;\n long i = n - 1, j = n - 1;\n while (i != 0 || j != 0) {\n path.push_back(grid[i][j]);\n std::pair p = parent[i][j];\n i = p.first;\n j = p.second;\n }\n path.push_back(grid[0][0]);\n std::reverse(path.begin(), path.end());\n return path;"], ["#include\n#include\n// Out of vector of strings, return the longest one. Return the first one in case of multiple\n// strings of the same length. Return None in case the input vector is empty.\n// >>> longest((std::vector()))\n// std::nullopt\n// >>> longest((std::vector({(std::string)\"a\", (std::string)\"b\", (std::string)\"c\"})))\n// \"a\"\n// >>> longest((std::vector({(std::string)\"a\", (std::string)\"bb\", (std::string)\"ccc\"})))\n// \"ccc\"\nstd::optional longest(std::vector strings) {\n if (strings.empty()) {\n return std::nullopt;\n }\n std::string longest_string = strings[0];\n for (const auto& string : strings) {\n if (string.size() > longest_string.size()) {\n longest_string = string;\n }\n }\n return longest_string;"], ["#include\n#include\n// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n// the last couple centuries. However, what people don't know is Tribonacci sequence.\n// Tribonacci sequence is defined by the recurrence:\n// tri(1) = 3\n// tri(n) = 1 + n / 2, if n is even.\n// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n// For example:\n// tri(2) = 1 + (2 / 2) = 2\n// tri(4) = 3\n// tri(3) = tri(2) + tri(1) + tri(4)\n// = 2 + 3 + 3 = 8 \n// You are given a non-negative integer number n, you have to a return a vector of the \n// first n + 1 numbers of the Tribonacci sequence.\n// Examples:\n// >>> tri((3))\n// (std::vector({(long)1, (long)3, (long)2, (long)8}))\nstd::vector tri(long n) {\n std::vector res(n+1);\n res[0] = 1;\n res[1] = 3;\n for(int i=2; i<=n; i++){\n if(i%2==0){\n res[i] = 1 + i/2;\n }\n else{\n res[i] = res[i-1] + res[i-2] + res[i+1];\n }\n }\n return res;"], ["#include\n#include\n// Given a positive integer n, return the product of the odd digits.\n// Return 0 if all digits are even.\n// For example:\n// >>> digits((1))\n// (1)\n// >>> digits((4))\n// (0)\n// >>> digits((235))\n// (15)\nlong digits(long n) {\n long product = 1;\n while (n > 0) {\n int digit = n % 10;\n if (digit % 2 != 0) {\n product *= digit;\n }\n n /= 10;\n }\n return product;"], ["#include\n#include\n// Create a function that takes a string as input which contains only square brackets.\n// The function should return true if and only if there is a valid subsequence of brackets \n// where at least one bracket in the subsequence is nested.\n// >>> is_nested((\"[[]]\"))\n// (true)\n// >>> is_nested((\"[]]]]]]][[[[[]\"))\n// (false)\n// >>> is_nested((\"[][]\"))\n// (false)\n// >>> is_nested((\"[]\"))\n// (false)\n// >>> is_nested((\"[[][]]\"))\n// (true)\n// >>> is_nested((\"[[]][[\"))\n// (true)\nbool is_nested(std::string string) {\n std::stack stack;\n for (char c : string) {\n if (c == '[') {\n stack.push(c);\n } else if (c == ']') {\n if (stack.empty()) {\n return false;\n }\n stack.pop();\n } else {\n assert(false);\n }\n }\n return !stack.empty();"], ["#include\n#include\n// You are given a vector of numbers.\n// You need to return the sum of squared numbers in the given vector,\n// round each element in the vector to the upper int(Ceiling) first.\n// Examples:\n// >>> lst((std::vector({(float)1.0f, (float)2.0f, (float)3.0f})))\n// (14)\n// >>> lst((std::vector({(float)1.0f, (float)4.0f, (float)9.0f})))\n// (98)\n// >>> lst((std::vector({(float)1.0f, (float)3.0f, (float)5.0f, (float)7.0f})))\n// (84)\n// >>> lst((std::vector({(float)1.4f, (float)4.2f, (float)0.0f})))\n// (29)\n// >>> lst((std::vector({(float)-2.4f, (float)1.0f, (float)1.0f})))\n// (6)\nlong sum_squares(std::vector lst) {\n long sum = 0;\n for (auto num : lst) {\n sum += pow(ceil(num), 2);\n }\n return sum;"], ["#include\n#include\n// Create a function that returns true if the last character\n// of a given string is an alphabetical character and is not\n// a part of a word, and false otherwise.\n// Note: \"word\" is a group of characters separated by space.\n// Examples:\n// >>> check_if_last_char_is_a_letter((\"apple pie\"))\n// (false)\n// >>> check_if_last_char_is_a_letter((\"apple pi e\"))\n// (true)\n// >>> check_if_last_char_is_a_letter((\"apple pi e \"))\n// (false)\n// >>> check_if_last_char_is_a_letter((\"\"))\n// (false)\nbool check_if_last_char_is_a_letter(std::string txt) {\n int n = txt.length();\n if (n == 0) {\n return false;\n }\n if (isalpha(txt[n-1]) && (n == 1 || txt[n-2] == ' ')) {\n return true;\n }\n return false;"], ["#include\n#include\n// Create a function which returns the largest index of an element which\n// is not greater than or equal to the element immediately preceding it. If\n// no such element exists then return -1. The given vector will not contain\n// duplicate values.\n// Examples:\n// >>> can_arrange((std::vector({(long)1, (long)2, (long)4, (long)3, (long)5})))\n// (3)\n// >>> can_arrange((std::vector({(long)1, (long)2, (long)3})))\n// (-1)\nlong can_arrange(std::vector arr) {\n long n = arr.size();\n long max_index = -1;\n for (long i = 1; i < n; i++) {\n if (arr[i] < arr[i-1]) {\n max_index = i-1;\n }\n }\n return max_index;"], ["#include\n#include\n// Create a function that returns a tuple (a, b), where 'a' is\n// the largest of negative integers, and 'b' is the smallest\n// of positive integers in a vector.\n// If there is no negative or positive integers, return them as None.\n// Examples:\n// >>> largest_smallest_integers((std::vector({(long)2, (long)4, (long)1, (long)3, (long)5, (long)7})))\n// std::make_tuple(std::optional(std::nullopt), std::optional(1))\n// >>> largest_smallest_integers((std::vector()))\n// std::make_tuple(std::optional(std::nullopt), std::optional(std::nullopt))\n// >>> largest_smallest_integers((std::vector({(long)0})))\n// std::make_tuple(std::optional(std::nullopt), std::optional(std::nullopt))\nstd::tuple, std::optional> largest_smallest_integers(std::vector lst) {\n std::optional largest_negative = std::nullopt;\n std::optional smallest_positive = std::nullopt;\n for (auto num : lst) {\n if (num < 0) {\n if (!largest_negative || num > *largest_negative) {\n largest_negative = num;\n }\n } else if (num > 0) {\n if (!smallest_positive || num < *smallest_positive) {\n smallest_positive = num;\n }\n }\n }\n return std::make_tuple(largest_negative, smallest_positive);"], ["#include\n#include\nunion Union_long_float_std_string{\n long f0;\n float f1;\n std::string f2; Union_long_float_std_string(long _f0) : f0(_f0) {}\n Union_long_float_std_string(float _f1) : f1(_f1) {}\n Union_long_float_std_string(std::string _f2) : f2(_f2) {}\n ~Union_long_float_std_string() {}\n bool operator==(long f) {\n return f0 == f ;\n } bool operator==(float f) {\n return f1 == f ;\n } bool operator==(std::string f) {\n return f2 == f ;\n }\n};\nunion Union_long_float_std_string_std_nullopt{\n long f0;\n float f1;\n std::string f2;\n std::nullopt f3; Union_long_float_std_string_std_nullopt(long _f0) : f0(_f0) {}\n Union_long_float_std_string_std_nullopt(float _f1) : f1(_f1) {}\n Union_long_float_std_string_std_nullopt(std::string _f2) : f2(_f2) {}\n Union_long_float_std_string_std_nullopt(std::nullopt _f3) : f3(_f3) {}\n ~Union_long_float_std_string_std_nullopt() {}\n bool operator==(long f) {\n return f0 == f ;\n } bool operator==(float f) {\n return f1 == f ;\n } bool operator==(std::string f) {\n return f2 == f ;\n } bool operator==(std::nullopt f) {\n return f3 == f ;\n }\n};\n// Create a function that takes integers, floats, or strings representing\n// real numbers, and returns the larger variable in its given variable type.\n// Return None if the values are equal.\n// Note: If a real number is represented as a string, the floating point might be . or ,\n// >>> compare_one(1, 2.5f)\n// 2.5f\n// >>> compare_one(1, \"2,3\")\n// \"2,3\"\n// >>> compare_one(\"5,1\", \"6\")\n// \"6\"\n// >>> compare_one(\"1\", 1)\n// std::nullopt\nUnion_long_float_std_string_std_nullopt compare_one(Union_long_float_std_string a, Union_long_float_std_string b) {\n if (a == b) {\n return std::nullopt;\n }\n if (a.f0 > b.f0) {\n return a;\n }\n if (a.f1 > b.f1) {\n return a;\n }\n if (a.f2 > b.f2) {\n return a;\n }\n return b;"], ["#include\n#include\n// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n// Example\n// >>> is_equal_to_sum_even((4))\n// (false)\n// >>> is_equal_to_sum_even((6))\n// (false)\n// >>> is_equal_to_sum_even((8))\n// (true)\nbool is_equal_to_sum_even(long n) {\n if (n % 4 != 0) {\n return false;\n }\n long sum = 0;\n for (int i = 1; i <= 4; i++) {\n sum += i * 2;\n }\n return sum == n;"], ["#include\n#include\n// The Brazilian factorial is defined as:\n// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n// where n > 0\n// For example:\n// >>> special_factorial((4))\n// (288)\n// The function will receive an integer as input and should return the special\n// factorial of this integer.\nlong special_factorial(long n) {\n assert(n > 0);\n long result = 1;\n for (long i = n; i > 0; i -= 2) {\n result *= i;\n }\n return result;"], ["#include\n#include\n// Return a greatest common divisor of two integers a and b\n// >>> greatest_common_divisor((3), (5))\n// (1)\n// >>> greatest_common_divisor((25), (15))\n// (5)\nlong greatest_common_divisor(long a, long b) {\n if (b == 0) {\n return a;\n }\n return greatest_common_divisor(b, a % b);"], ["#include\n#include\n// Given a string text, replace all spaces in it with underscores, \n// and if a string has more than 2 consecutive spaces, \n// then replace all consecutive spaces with - \n// >>> fix_spaces((\" Example\"))\n// (\"Example\")\n// >>> fix_spaces((\" Example 1\"))\n// (\"Example_1\")\n// >>> fix_spaces((\" Example 2\"))\n// (\"_Example_2\")\n// >>> fix_spaces((\" Example 3\"))\n// (\"_Example-3\")\nstd::string fix_spaces(std::string text) {\n std::string result = \"\";\n int count = 0;\n for (int i = 0; i < text.length(); i++) {\n if (text[i] == ' ') {\n count++;\n if (count == 1) {\n result += '_';\n } else if (count == 2) {\n result += '-';\n }\n } else {\n count = 0;\n result += text[i];\n }\n }\n return result;"], ["#include\n#include\n// Create a function which takes a string representing a file's name, and returns\n// 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n// A file's name is considered to be valid if and only if all the following conditions \n// are met:\n// - There should not be more than three digits ('0'-'9') in the file's name.\n// - The file's name contains exactly one dot '.'\n// - The substring before the dot should not be empty, and it starts with a letter from \n// the latin alphapet ('a'-'z' and 'A'-'Z').\n// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n// Examples:\n// >>> file_name_check((\"example.txt\"))\n// (\"Yes\")\n// >>> file_name_check((\"1example.dll\"))\n// (\"No\")\nstd::string file_name_check(std::string file_name) {\n int dot_count = 0;\n int digit_count = 0;\n int len = file_name.length();\n for (int i = 0; i < len; i++) {\n if (file_name[i] == '.') {\n dot_count++;\n } else if (isdigit(file_name[i])) {\n digit_count++;\n }\n }\n if (dot_count != 1 || digit_count > 3) {\n return \"No\";\n }\n std::stringstream ss(file_name);\n std::string before_dot, after_dot;\n std::getline(ss, before_dot, '.');\n std::getline(ss, after_dot);\n if (before_dot.empty() || !isalpha(before_dot[0])) {\n return \"No\";\n }\n if (after_dot != \"txt\" && after_dot != \"exe\" && after_dot != \"dll\") {\n return \"No\";\n }\n return \"Yes\";"], ["#include\n#include\n// \"\n// This function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a \n// multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n// change the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n// Examples:\n// >>> lst\n// (long({(long)1, (long)2, (long)3}))\n// >>> lst\n// (long())\n// >>> lst\n// (long({(long)-1, (long)-5, (long)2, (long)-1, (long)-5}))\nlong sum_squares(std::vector lst) {\n long sum = 0;\n for (int i = 0; i < lst.size(); i++) {\n if (i % 3 == 0) {\n sum += lst[i] * lst[i];\n } else if (i % 4 == 0) {\n sum += lst[i] * lst[i] * lst[i];\n } else {\n sum += lst[i];\n }\n }\n return sum;"], ["#include\n#include\n// You are given a string representing a sentence,\n// the sentence contains some words separated by a space,\n// and you have to return a string that contains the words from the original sentence,\n// whose lengths are prime numbers,\n// the order of the words in the new string should be the same as the original one.\n// Example 1:\n// >>> words_in_sentence((\"This is a test\"))\n// (\"is\")\n// Example 2:\n// >>> words_in_sentence((\"lets go for swimming\"))\n// (\"go for\")\n// Constraints:\n// * 1 <= len(sentence) <= 100\n// * sentence contains only letters\nstd::string words_in_sentence(std::string sentence) {\n std::vector words;\n std::stringstream ss(sentence);\n std::string word;\n while (ss >> word) {\n words.push_back(word);\n }\n std::string result = \"\";\n for (auto word : words) {\n int len = word.length();\n bool is_prime = true;\n for (int i = 2; i <= sqrt(len); i++) {\n if (len % i == 0) {\n is_prime = false;\n break;\n }\n }\n if (is_prime && len > 1) {\n result += word + \" \";\n }\n }\n if (result.length() > 0) {\n result.pop_back();\n }\n return result;"], ["#include\n#include\n// Your task is to implement a function that will simplify the expression\n// x * n. The function returns true if x * n evaluates to a whole number and false\n// otherwise. Both x and n, are string representation of a fraction, and have the following format,\n// / where both numerator and denominator are positive whole numbers.\n// You can assume that x, and n are valid fractions, and do not have zero as denominator.\n// >>> simplify((\"1/5\"), (\"5/1\"))\n// (true)\n// >>> simplify((\"1/6\"), (\"2/1\"))\n// (false)\n// >>> simplify((\"7/10\"), (\"10/2\"))\n// (false)\nbool simplify(std::string x, std::string n) {\n // Parse the input strings into integers\n int x_num, x_den, n_num, n_den;\n sscanf(x.c_str(), \"%d/%d\", &x_num, &x_den);\n sscanf(n.c_str(), \"%d/%d\", &n_num, &n_den);\n\n // Multiply the numerators and denominators\n int num = x_num * n_num;\n int den = x_den * n_den;\n\n // Check if the result is a whole number\n return (num % den == 0);"], ["#include\n#include\n// Write a function which sorts the given vector of integers\n// in ascending order according to the sum of their digits.\n// Note: if there are several items with similar sum of their digits,\n// order them based on their index in original vector.\n// For example:\n// >>> order_by_points((std::vector({(long)1, (long)11, (long)-1, (long)-11, (long)-12})))\n// (std::vector({(long)-1, (long)-11, (long)1, (long)-12, (long)11}))\n// >>> order_by_points((std::vector()))\n// (std::vector())\nstd::vector order_by_points(std::vector nums) {\n std::vector> v;\n for (int i = 0; i < nums.size(); i++) {\n long sum = 0;\n long n = nums[i];\n while (n != 0) {\n sum += n % 10;\n n /= 10;\n }\n v.push_back({sum, i});\n }\n std::sort(v.begin(), v.end());\n std::vector res;\n for (auto p : v) {\n res.push_back(nums[p.second]);\n }\n return res;"], ["#include\n#include\n// Write a function that takes a vector of numbers as input and returns \n// the number of elements in the vector that are greater than 10 and both \n// first and last digits of a number are odd (1, 3, 5, 7, 9).\n// For example:\n// >>> specialFilter((std::vector({(long)15, (long)-73, (long)14, (long)-15})))\n// (1)\n// >>> specialFilter((std::vector({(long)33, (long)-2, (long)-3, (long)45, (long)21, (long)109})))\n// (2)\nlong specialFilter(std::vector nums) {\n long count = 0;\n for (auto num : nums) {\n if (num > 10) {\n std::string num_str = std::to_string(num);\n int first_digit = num_str[0] - '0';\n int last_digit = num_str.back() - '0';\n if (first_digit % 2 != 0 && last_digit % 2 != 0) {\n count++;\n }\n }\n }\n return count;"], ["#include\n#include\n// You are given a positive integer n. You have to create an integer vector a of length n.\n// For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n// and a[i] + a[j] + a[k] is a multiple of 3.\n// Example :\n// >>> get_max_triples((5))\n// (1)\n// Explanation: \n// a = [1, 3, 7, 13, 21]\n// The only valid triple is (1, 7, 13).\nlong get_max_triples(long n) {\n std::vector a(n);\n for (long i = 0; i < n; i++) {\n a[i] = i * i - i + 1;\n }\n long count = 0;\n for (long i = 0; i < n; i++) {\n for (long j = i + 1; j < n; j++) {\n for (long k = j + 1; k < n; k++) {\n if ((a[i] + a[j] + a[k]) % 3 == 0) {\n count++;\n }\n }\n }\n }\n return count;"], ["#include\n#include\n// There are eight planets in our solar system: the closerst to the Sun \n// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n// Uranus, Neptune.\n// Write a function that takes two planet names as strings planet1 and planet2. \n// The function should return a tuple containing all planets whose orbits are \n// located between the orbit of planet1 and the orbit of planet2, sorted by \n// the proximity to the sun. \n// The function should return an empty tuple if planet1 or planet2\n// are not correct planet names. \n// Examples\n// >>> bf((\"Jupiter\"), (\"Neptune\"))\n// (std::vector({(std::string)\"Saturn\", (std::string)\"Uranus\"}))\n// >>> bf((\"Earth\"), (\"Mercury\"))\n// (std::vector(\"Venus\"))\n// >>> bf((\"Mercury\"), (\"Uranus\"))\n// (std::vector({(std::string)\"Venus\", (std::string)\"Earth\", (std::string)\"Mars\", (std::string)\"Jupiter\", (std::string)\"Saturn\"}))\nstd::vector bf(std::string planet1, std::string planet2) {\n std::vector planets = {\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\"};\n std::vector result;\n int start = -1, end = -1;\n for (int i = 0; i < planets.size(); i++) {\n if (planets[i] == planet1) {\n start = i;\n }\n if (planets[i] == planet2) {\n end = i;\n }\n }\n if (start == -1 || end == -1) {\n return result;\n }\n if (start > end) {\n std::swap(start, end);\n }\n for (int i = start + 1; i < end; i++) {\n result.push_back(planets[i]);\n }\n return result;"], ["#include\n#include\n// Write a function that accepts a vector of strings as a parameter,\n// deletes the strings that have odd lengths from it,\n// and returns the resulted vector with a sorted order,\n// The vector is always a vector of strings and never a vector of numbers,\n// and it may contain duplicates.\n// The order of the vector should be ascending by length of each word, and you\n// should return the vector sorted by that rule.\n// If two words have the same length, sort the vector alphabetically.\n// The function should return a vector of strings in sorted order.\n// You may assume that all words will have the same length.\n// For example:\n// >>> list_sort((std::vector({(std::string)\"aa\", (std::string)\"a\", (std::string)\"aaa\"})))\n// (std::vector({(std::string)\"aa\"}))\n// >>> list_sort((std::vector({(std::string)\"ab\", (std::string)\"a\", (std::string)\"aaa\", (std::string)\"cd\"})))\n// (std::vector({(std::string)\"ab\", (std::string)\"cd\"}))\nstd::vector sorted_list_sum(std::vector lst) {\n std::vector result;\n for (auto str : lst) {\n if (str.length() % 2 == 0) {\n result.push_back(str);\n }\n }\n std::sort(result.begin(), result.end(), [](const std::string& a, const std::string& b) {\n if (a.length() == b.length()) {\n return a < b;\n }\n return a.length() < b.length();\n });\n return result;"], ["#include\n#include\n// Return vector of all prefixes from shortest to longest of the input string\n// >>> all_prefixes((\"abc\"))\n// (std::vector({(std::string)\"a\", (std::string)\"ab\", (std::string)\"abc\"}))\nstd::vector all_prefixes(std::string string) {\n std::vector prefixes;\n for (int i = 1; i <= string.length(); i++) {\n prefixes.push_back(string.substr(0, i));\n }\n return prefixes;"], ["#include\n#include\n// A simple program which should return the value of x if n is \n// a prime number and should return the value of y otherwise.\n// Examples:\n// >>> x_or_y((7), (34), (12))\n// (34)\n// >>> x_or_y((15), (8), (5))\n// (5)\nlong x_or_y(long n, long x, long y) {\n bool isPrime = true;\n for(long i = 2; i <= sqrt(n); i++) {\n if(n % i == 0) {\n isPrime = false;\n break;\n }\n }\n if(isPrime) {\n return x;\n } else {\n return y;\n }"], ["#include\n#include\n// Given a vector of numbers, return the sum of squares of the numbers\n// in the vector that are odd. Ignore numbers that are negative or not integers.\n// >>> double_the_difference((std::vector({(long)1, (long)3, (long)2, (long)0})))\n// (10)\n// >>> double_the_difference((std::vector({(long)-1, (long)-2, (long)0})))\n// (0)\n// >>> double_the_difference((std::vector({(long)9, (long)-2})))\n// (81)\n// >>> double_the_difference((std::vector({(long)0})))\n// (0)\n// If the input vector is empty, return 0.\nlong double_the_difference(std::vector lst) {\n long sum = 0;\n for (auto num : lst) {\n if (num < 0 || num != (int)num) {\n continue;\n }\n if ((int)num % 2 != 0) {\n sum += num * num;\n }\n }\n return sum;"], ["#include\n#include\n// I think we all remember that feeling when the result of some long-awaited\n// event is finally known. The feelings and thoughts you have at that moment are\n// definitely worth noting down and comparing.\n// Your task is to determine if a person correctly guessed the results of a number of matches.\n// You are given two vectors of scores and guesses of equal length, where each index shows a match. \n// Return a vector of the same length denoting how far off each guess was. If they have guessed correctly,\n// the value is 0, and if not, the value is the absolute difference between the guess and the score.\n// example:\n// >>> compare((std::vector({(long)1, (long)2, (long)3, (long)4, (long)5, (long)1})), (std::vector({(long)1, (long)2, (long)3, (long)4, (long)2, (long)-2})))\n// (std::vector({(long)0, (long)0, (long)0, (long)0, (long)3, (long)3}))\n// >>> compare((std::vector({(long)0, (long)5, (long)0, (long)0, (long)0, (long)4})), (std::vector({(long)4, (long)1, (long)1, (long)0, (long)0, (long)-2})))\n// (std::vector({(long)4, (long)4, (long)1, (long)0, (long)0, (long)6}))\nstd::vector compare(std::vector game, std::vector guess) {\n assert(game.size() == guess.size());\n std::vector result;\n for (int i = 0; i < game.size(); i++) {\n result.push_back(abs(game[i] - guess[i]));\n }\n return result;"], ["#include\n#include\n// You will be given the name of a class (a string) and a vector of extensions.\n// The extensions are to be used to load additional classes to the class. The\n// strength of the extension is as follows: Let CAP be the number of the uppercase\n// letters in the extension's name, and let SM be the number of lowercase letters \n// in the extension's name, the strength is given by the fraction CAP - SM. \n// You should find the strongest extension and return a string in this \n// format: ClassName.StrongestExtensionName.\n// If there are two or more extensions with the same strength, you should\n// choose the one that comes first in the vector.\n// For example, if you are given \"Slices\" as the class and a vector of the\n// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n// (its strength is -1).\n// Example:\n// >>> Strongest_Extension((\"my_class\"), (std::vector({(std::string)\"AA\", (std::string)\"Be\", (std::string)\"CC\"})))\n// (\"my_class.AA\")\nstd::string Strongest_Extension(std::string class_name, std::vector extensions) {\n std::string strongest_extension = \"\";\n double strongest_strength = -1;\n for (auto extension : extensions) {\n int cap = 0, sm = 0;\n for (auto c : extension) {\n if (isupper(c)) {\n cap++;\n } else if (islower(c)) {\n sm++;\n }\n }\n double strength = cap - sm;\n if (strength > strongest_strength) {\n strongest_extension = extension;\n strongest_strength = strength;\n }\n }\n return class_name + \".\" + strongest_extension;"], ["#include\n#include\n// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n// >>> cycpattern_check((\"abcd\"), (\"abd\"))\n// (false)\n// >>> cycpattern_check((\"hello\"), (\"ell\"))\n// (true)\n// >>> cycpattern_check((\"whassup\"), (\"psus\"))\n// (false)\n// >>> cycpattern_check((\"abab\"), (\"baa\"))\n// (true)\n// >>> cycpattern_check((\"efef\"), (\"eeff\"))\n// (false)\n// >>> cycpattern_check((\"himenss\"), (\"simen\"))\n// (true)\nbool cycpattern_check(std::string a, std::string b) {\n int n = a.length();\n int m = b.length();\n if (m > n) {\n return false;\n }\n std::string temp = a + a;\n for (int i = 0; i < n; i++) {\n if (temp.substr(i, m) == b) {\n return true;\n }\n }\n return false;"], ["#include\n#include\n// Given an integer. return a tuple that has the number of even and odd digits respectively.\n// Example:\n// >>> even_odd_count((-12))\n// (std::make_tuple(1, 1))\n// >>> even_odd_count((123))\n// (std::make_tuple(1, 2))\nstd::tuple even_odd_count(long num) {\n long even_count = 0, odd_count = 0;\n if(num == 0) {\n even_count = 1;\n } else {\n while(num != 0) {\n int digit = num % 10;\n if(digit % 2 == 0) {\n even_count++;\n } else {\n odd_count++;\n }\n num /= 10;\n }\n }\n return std::make_tuple(even_count, odd_count);"], ["#include\n#include\n// Given a positive integer, obtain its roman numeral equivalent as a string,\n// and return it in lowercase.\n// Restrictions: 1 <= num <= 1000\n// Examples:\n// >>> int_to_mini_roman((19))\n// (\"xix\")\n// >>> int_to_mini_roman((152))\n// (\"clii\")\n// >>> int_to_mini_roman((426))\n// (\"cdxxvi\")\nstd::string int_to_mini_roman(long number) {\n assert(number >= 1 && number <= 1000);\n std::string roman = \"\";\n std::vector> roman_map = {\n {1000, \"m\"}, {900, \"cm\"}, {500, \"d\"}, {400, \"cd\"}, {100, \"c\"},\n {90, \"xc\"}, {50, \"l\"}, {40, \"xl\"}, {10, \"x\"}, {9, \"ix\"},\n {5, \"v\"}, {4, \"iv\"}, {1, \"i\"}\n };\n for (auto it = roman_map.begin(); it != roman_map.end(); ++it) {\n while (number >= it->first) {\n roman += it->second;\n number -= it->first;\n }\n }\n return roman;"], ["#include\n#include\n// Given the lengths of the three sides of a triangle. Return true if the three\n// sides form a right-angled triangle, false otherwise.\n// A right-angled triangle is a triangle in which one angle is right angle or \n// 90 degree.\n// Example:\n// >>> right_angle_triangle((3), (4), (5))\n// (true)\n// >>> right_angle_triangle((1), (2), (3))\n// (false)\nbool right_angle_triangle(long a, long b, long c) {\n long hypotenuse = std::max(a, std::max(b, c));\n long leg1 = std::min(a, std::min(b, c));\n long leg2 = a + b + c - hypotenuse - leg1;\n return (hypotenuse * hypotenuse) == (leg1 * leg1) + (leg2 * leg2);"], ["#include\n#include\n// Write a function that accepts a vector of strings.\n// The vector contains different words. Return the word with maximum number\n// of unique characters. If multiple strings have maximum number of unique\n// characters, return the one which comes first in lexicographical order.\n// >>> find_max((std::vector({(std::string)\"name\", (std::string)\"of\", (std::string)\"string\"})))\n// (\"string\")\n// >>> find_max((std::vector({(std::string)\"name\", (std::string)\"enam\", (std::string)\"game\"})))\n// (\"enam\")\n// >>> find_max((std::vector({(std::string)\"aaaaaaa\", (std::string)\"bb\", (std::string)\"cc\"})))\n// (\"aaaaaaa\")\nstd::string find_max(std::vector words) {\n std::string max_word = \"\";\n int max_unique = 0;\n for (auto word : words) {\n std::set unique_chars(word.begin(), word.end());\n int num_unique = unique_chars.size();\n if (num_unique > max_unique || (num_unique == max_unique && word < max_word)) {\n max_word = word;\n max_unique = num_unique;\n }\n }\n return max_word;"], ["#include\n#include\n// You're a hungry rabbit, and you already have eaten a certain number of carrots,\n// but now you need to eat more carrots to complete the day's meals.\n// you should return a vector of [ total number of eaten carrots after your meals,\n// the number of carrots left after your meals ]\n// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n// Example:\n// >>> eat((5), (6), (10))\n// (std::vector({(long)11, (long)4}))\n// >>> eat((4), (8), (9))\n// (std::vector({(long)12, (long)1}))\n// >>> eat((1), (10), (10))\n// (std::vector({(long)11, (long)0}))\n// >>> eat((2), (11), (5))\n// (std::vector({(long)7, (long)0}))\n// Variables:\n// @number : integer\n// the number of carrots that you have eaten.\n// @need : integer\n// the number of carrots that you need to eat.\n// @remaining : integer\n// the number of remaining carrots thet exist in stock\n// Constrain:\n// * 0 <= number <= 1000\n// * 0 <= need <= 1000\n// * 0 <= remaining <= 1000\n// Have fun :)\nstd::vector eat(long number, long need, long remaining) {\n assert(0 <= number && number <= 1000);\n assert(0 <= need && need <= 1000);\n assert(0 <= remaining && remaining <= 1000);\n long total = number + need;\n long left = remaining - need;\n if (left < 0) {\n left = 0;\n }\n return {total, left};"], ["#include\n#include\n// Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n// >>> string_sequence((0))\n// (\"0\")\n// >>> string_sequence((5))\n// (\"0 1 2 3 4 5\")\nstd::string string_sequence(long n) {\n std::stringstream ss;\n for (long i = 0; i <= n; i++) {\n ss << i << \" \";\n }\n return ss.str();"], ["#include\n#include\n// Given two vectors operator, and operand. The first vector has basic algebra operations, and \n// the second vector is a vector of integers. Use the two given vectors to build the algebric \n// expression and return the evaluation of this expression.\n// The basic algebra operations:\n// Addition ( + ) \n// Subtraction ( - ) \n// Multiplication ( * ) \n// Floor division ( // ) \n// Exponentiation ( ** ) \n// Example:\n// operator['+', '*', '-']\n// vector = [2, 3, 4, 5]\n// result = 2 + 3 * 4 - 5\n// => result = 9\n// Note:\n// The length of operator vector is equal to the length of operand vector minus one.\n// Operand is a vector of of non-negative integers.\n// Operator vector has at least one operator, and operand vector has at least two operands.\nlong do_algebra(std::vector op, std::vector operand) {\n assert(op.size() == operand.size() - 1);\n long result = operand[0];\n for (int i = 1; i < operand.size(); i++) {\n if (op[i-1] == \"+\") {\n result += operand[i];\n } else if (op[i-1] == \"-\") {\n result -= operand[i];\n } else if (op[i-1] == \"*\") {\n result *= operand[i];\n } else if (op[i-1] == \"//\") {\n result /= operand[i];\n } else if (op[i-1] == \"**\") {\n result = pow(result, operand[i]);\n }\n }\n return result;"], ["#include\n#include\n// You are given a string s.\n// if s[i] is a letter, reverse its case from lower to upper or vise versa, \n// otherwise keep it as it is.\n// If the string contains no letters, reverse the string.\n// The function should return the resulted string.\n// Examples\n// >>> solve((\"1234\"))\n// (\"4321\")\n// >>> solve((\"ab\"))\n// (\"AB\")\n// >>> solve((\"#a@C\"))\n// (\"#A@c\")\nstd::string solve(std::string s) {\n bool has_letter = false;\n for (int i = 0; i < s.size(); i++) {\n if (isalpha(s[i])) {\n has_letter = true;\n if (islower(s[i])) {\n s[i] = toupper(s[i]);\n } else {\n s[i] = tolower(s[i]);\n }\n }\n }\n if (!has_letter) {\n std::reverse(s.begin(), s.end());\n }\n return s;"], ["#include\n#include\n// Given a string 'text', return its md5 hash equivalent string.\n// If 'text' is an empty string, return None.\n// >>> string_to_md5((\"Hello world\"))\n// \"3e25960a79dbc69b674cd4ec67a72c62\"\nstd::optional string_to_md5(std::string text) {\n if (text.empty()) {\n return std::nullopt;\n }\n unsigned char hash[MD5_DIGEST_LENGTH];\n MD5((unsigned char*)&text[0], text.size(), hash);\n std::stringstream ss;\n for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {\n ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];\n }\n return ss.str();"], ["#include\n#include\n// Given two positive integers a and b, return the even digits between a\n// and b, in ascending order.\n// For example:\n// >>> generate_integers((2), (8))\n// (std::vector({(long)2, (long)4, (long)6, (long)8}))\n// >>> generate_integers((8), (2))\n// (std::vector({(long)2, (long)4, (long)6, (long)8}))\n// >>> generate_integers((10), (14))\n// (std::vector())\nstd::vector generate_integers(long a, long b) {\n std::vector result;\n for (long i = a; i <= b; i++) {\n long temp = i;\n while (temp > 0) {\n long digit = temp % 10;\n if (digit % 2 == 0) {\n result.push_back(digit);\n }\n temp /= 10;\n }\n }\n std::sort(result.begin(), result.end());\n return result;"], ["#include\n#include\n// Given a string, find out how many distinct characters (regardless of case) does it consist of\n// >>> count_distinct_characters((\"xyzXYZ\"))\n// (3)\n// >>> count_distinct_characters((\"Jerry\"))\n// (4)\nlong count_distinct_characters(std::string string) {\n std::set distinct_chars;\n for (char c : string) {\n distinct_chars.insert(std::tolower(c));\n }\n return distinct_chars.size();"], ["#include\n#include\n// Input to this function is a string representing musical notes in a special ASCII format.\n// Your task is to parse this string and return vector of integers corresponding to how many beats does each\n// not last.\n// Here is a legend:\n// 'o' - whole note, lasts four beats\n// 'o|' - half note, lasts two beats\n// '.|' - quater note, lasts one beat\n// >>> parse_music((\"o o| .| o| o| .| .| .| .| o o\"))\n// (std::vector({(long)4, (long)2, (long)1, (long)2, (long)2, (long)1, (long)1, (long)1, (long)1, (long)4, (long)4}))\nstd::vector parse_music(std::string music_string) {\n std::vector beats;\n std::stringstream ss(music_string);\n std::string note;\n while (ss >> note) {\n if (note == \"o\") {\n beats.push_back(4);\n } else if (note == \"o|\") {\n beats.push_back(2);\n } else if (note == \".|\") {\n beats.push_back(1);\n } else {\n assert(false && \"Invalid note format\");\n }\n }\n return beats;"], ["#include\n#include\n// Find how many times a given substring can be found in the original string. Count overlaping cases.\n// >>> how_many_times((\"\"), (\"a\"))\n// (0)\n// >>> how_many_times((\"aaa\"), (\"a\"))\n// (3)\n// >>> how_many_times((\"aaaa\"), (\"aa\"))\n// (3)\nlong how_many_times(std::string string, std::string substring) {\n long count = 0;\n size_t pos = 0;\n while ((pos = string.find(substring, pos)) != std::string::npos) {\n ++count;\n pos += substring.length();\n }\n return count;"], ["#include\n#include\n// Input is a space-delimited string of numberals from 'zero' to 'nine'.\n// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n// Return the string with numbers sorted from smallest to largest\n// >>> sort_numbers((\"three one five\"))\n// (\"one three five\")\nstd::string sort_numbers(std::string numbers) {\n std::vector nums = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"};\n std::vector nums_in_str;\n std::stringstream ss(numbers);\n std::string temp;\n while (ss >> temp) {\n nums_in_str.push_back(temp);\n }\n std::sort(nums_in_str.begin(), nums_in_str.end(), [&](const std::string& a, const std::string& b) {\n return std::find(nums.begin(), nums.end(), a) < std::find(nums.begin(), nums.end(), b);\n });\n std::string result;\n for (auto& num : nums_in_str) {\n result += num + \" \";\n }\n result.pop_back();\n return result;"], ["#include\n#include\n// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n// separate those group into separate strings and return the vector of those.\n// Separate groups are balanced (each open brace is properly closed) and not nested within each other\n// Ignore any spaces in the input string.\n// >>> separate_paren_groups((\"( ) (( )) (( )( ))\"))\n// (std::vector({(std::string)\"()\", (std::string)\"(())\", (std::string)\"(()())\"}))\nstd::vector separate_paren_groups(std::string paren_string) {\n std::vector result;\n std::stack st;\n std::string temp = \"\";\n for (int i = 0; i < paren_string.length(); i++) {\n if (paren_string[i] == ' ') {\n continue;\n }\n if (paren_string[i] == '(') {\n st.push(paren_string[i]);\n temp += paren_string[i];\n } else if (paren_string[i] == ')') {\n if (st.empty()) {\n assert(false);\n }\n st.pop();\n temp += paren_string[i];\n if (st.empty()) {\n result.push_back(temp);\n temp = \"\";\n }\n }\n }\n if (!st.empty()) {\n assert(false);\n }\n return result;"], ["#include\n#include\n// From a supplied vector of numbers (of length at least two) select and return two that are the closest to each\n// other and return them in order (smaller number, larger number).\n// >>> find_closest_elements((std::vector({(float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.2f})))\n// (std::make_tuple(2.0f, 2.2f))\n// >>> find_closest_elements((std::vector({(float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f})))\n// (std::make_tuple(2.0f, 2.0f))\nstd::tuple find_closest_elements(std::vector numbers) {\n assert(numbers.size() >= 2);\n std::sort(numbers.begin(), numbers.end());\n float min_diff = std::numeric_limits::max();\n float closest_num1, closest_num2;\n for (int i = 1; i < numbers.size(); i++) {\n float diff = numbers[i] - numbers[i-1];\n if (diff < min_diff) {\n min_diff = diff;\n closest_num1 = numbers[i-1];\n closest_num2 = numbers[i];\n }\n }\n return std::make_tuple(closest_num1, closest_num2);"], ["#include\n#include\n// Given vector of numbers (of at least two elements), apply a linear transform to that vector,\n// such that the smallest number will become 0 and the largest will become 1\n// >>> rescale_to_unit((std::vector({(float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f})))\n// (std::vector({(float)0.0f, (float)0.25f, (float)0.5f, (float)0.75f, (float)1.0f}))\nstd::vector rescale_to_unit(std::vector numbers) {\n assert(numbers.size() >= 2);\n float min_val = *std::min_element(numbers.begin(), numbers.end());\n float max_val = *std::max_element(numbers.begin(), numbers.end());\n float range = max_val - min_val;\n for (int i = 0; i < numbers.size(); i++) {\n numbers[i] = (numbers[i] - min_val) / range;\n }\n return numbers;"], ["#include\n#include\n// Filter given vector of any cppthon values only for integers\n// >>> filter_integers((std::vector({(std::string)\"a\", (std::string)3.14f, (std::string)5})))\n// (std::vector({(long)5}))\n// >>> filter_integers((std::vector({1, 2, 3, \"abc\", std::map(), std::vector()})))\n// (std::vector({(long)1, (long)2, (long)3}))\nstd::vector filter_integers(std::vector values) {\n std::vector integers;\n for (auto value : values) {\n if (value.type() == typeid(int)) {\n integers.push_back(std::any_cast(value));\n }\n }\n return integers;"], ["#include\n#include\n// Return length of given string\n// >>> string_length((\"\"))\n// (0)\n// >>> string_length((\"abc\"))\n// (3)\nlong string_length(std::string string) {\n return string.length();"], ["#include\n#include\n// For a given number n, find the largest number that divides n evenly, smaller than n\n// >>> largest_divisor((15))\n// (5)\nlong largest_divisor(long n) {\n assert(n > 0);\n long largest = 1;\n for (long i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n largest = i;\n while (n % i == 0) {\n n /= i;\n }\n }\n }\n if (n > 1) {\n largest = n;\n }\n return largest;"], ["#include\n#include\n// Return vector of prime factors of given integer in the order from smallest to largest.\n// Each of the factors should be vectored number of times corresponding to how many times it appeares in factorization.\n// Input number should be equal to the product of all factors\n// >>> factorize((8))\n// (std::vector({(long)2, (long)2, (long)2}))\n// >>> factorize((25))\n// (std::vector({(long)5, (long)5}))\n// >>> factorize((70))\n// (std::vector({(long)2, (long)5, (long)7}))\nstd::vector factorize(long n) {\n std::vector factors;\n for (long i = 2; i * i <= n; i++) {\n while (n % i == 0) {\n factors.push_back(i);\n n /= i;\n }\n }\n if (n > 1) {\n factors.push_back(n);\n }\n return factors;"], ["#include\n#include\n// From a vector of integers, remove all elements that occur more than once.\n// Keep order of elements left the same as in the input.\n// >>> remove_duplicates((std::vector({(long)1, (long)2, (long)3, (long)2, (long)4})))\n// (std::vector({(long)1, (long)3, (long)4}))\nstd::vector remove_duplicates(std::vector numbers) {\n std::unordered_set seen;\n std::vector result;\n for (auto num : numbers) {\n if (seen.find(num) == seen.end()) {\n seen.insert(num);\n result.push_back(num);\n }\n }\n return result;"], ["#include\n#include\n// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n// >>> flip_case((\"Hello\"))\n// (\"hELLO\")\nstd::string flip_case(std::string string) {\n for (int i = 0; i < string.length(); i++) {\n if (isupper(string[i])) {\n string[i] = tolower(string[i]);\n } else if (islower(string[i])) {\n string[i] = toupper(string[i]);\n }\n }\n return string;"], ["#include\n#include\n// Concatenate vector of strings into a single string\n// >>> concatenate((std::vector()))\n// (\"\")\n// >>> concatenate((std::vector({(std::string)\"a\", (std::string)\"b\", (std::string)\"c\"})))\n// (\"abc\")\nstd::string concatenate(std::vector strings) {\n std::string result = \"\";\n for (auto s : strings) {\n result += s;\n }\n return result;"], ["#include\n#include\n// Filter an input vector of strings only for ones that start with a given prefix.\n// >>> filter_by_prefix((std::vector()), (\"a\"))\n// (std::vector())\n// >>> filter_by_prefix((std::vector({(std::string)\"abc\", (std::string)\"bcd\", (std::string)\"cde\", (std::string)\"array\"})), (\"a\"))\n// (std::vector({(std::string)\"abc\", (std::string)\"array\"}))\nstd::vector filter_by_prefix(std::vector strings, std::string prefix) {\n std::vector result;\n for (auto s : strings) {\n if (s.substr(0, prefix.size()) == prefix) {\n result.push_back(s);\n }\n }\n return result;"], ["#include\n#include\n// Given a positive floating point number, it can be decomposed into\n// and integer part (largest integer smaller than given number) and decimals\n// (leftover part always smaller than 1).\n// Return the decimal part of the number.\n// >>> truncate_number((3.5f))\n// (0.5f)\nfloat truncate_number(float number) {\n int integer_part = (int) number;\n float decimal_part = number - integer_part;\n return decimal_part;"], ["#include\n#include\n// Return only positive numbers in the vector.\n// >>> get_positive((std::vector({(long)-1, (long)2, (long)-4, (long)5, (long)6})))\n// (std::vector({(long)2, (long)5, (long)6}))\n// >>> get_positive((std::vector({(long)5, (long)3, (long)-5, (long)2, (long)-3, (long)3, (long)9, (long)0, (long)123, (long)1, (long)-10})))\n// (std::vector({(long)5, (long)3, (long)2, (long)3, (long)9, (long)123, (long)1}))\nstd::vector get_positive(std::vector l) {\n std::vector result;\n for (auto i : l) {\n if (i > 0) {\n result.push_back(i);\n }\n }\n return result;"], ["#include\n#include\n// Return true if a given number is prime, and false otherwise.\n// >>> is_prime((6))\n// (false)\n// >>> is_prime((101))\n// (true)\n// >>> is_prime((11))\n// (true)\n// >>> is_prime((13441))\n// (true)\n// >>> is_prime((61))\n// (true)\n// >>> is_prime((4))\n// (false)\n// >>> is_prime((1))\n// (false)\nbool is_prime(long n) {\n if (n <= 1) {\n return false;\n }\n if (n <= 3) {\n return true;\n }\n if (n % 2 == 0 || n % 3 == 0) {\n return false;\n }\n for (long i = 5; i * i <= n; i += 6) {\n if (n % i == 0 || n % (i + 2) == 0) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// This function takes a vector l and returns a vector l' such that\n// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n// to the values of the corresponding indicies of l, but sorted.\n// >>> sort_third((std::vector({(long)1, (long)2, (long)3})))\n// (std::vector({(long)1, (long)2, (long)3}))\n// >>> sort_third((std::vector({(long)5, (long)6, (long)3, (long)4, (long)8, (long)9, (long)2})))\n// (std::vector({(long)2, (long)6, (long)3, (long)4, (long)8, (long)9, (long)5}))\nstd::vector sort_third(std::vector l) {\n std::vector l_prime;\n std::vector third_elements;\n for (int i = 0; i < l.size(); i++) {\n if ((i+1) % 3 == 0) {\n third_elements.push_back(l[i]);\n } else {\n l_prime.push_back(l[i]);\n }\n }\n std::sort(third_elements.begin(), third_elements.end());\n int j = 0;\n for (int i = 0; i < l.size(); i++) {\n if ((i+1) % 3 == 0) {\n l_prime.push_back(third_elements[j]);\n j++;\n }\n }\n return l_prime;"], ["#include\n#include\n// Return sorted unique elements in a vector\n// >>> unique((std::vector({(long)5, (long)3, (long)5, (long)2, (long)3, (long)3, (long)9, (long)0, (long)123})))\n// (std::vector({(long)0, (long)2, (long)3, (long)5, (long)9, (long)123}))\nstd::vector unique(std::vector l) {\n std::sort(l.begin(), l.end());\n l.erase(std::unique(l.begin(), l.end()), l.end());\n return l;"], ["#include\n#include\n// Return maximum element in the vector.\n// >>> max_element((std::vector({(long)1, (long)2, (long)3})))\n// (3)\n// >>> max_element((std::vector({(long)5, (long)3, (long)-5, (long)2, (long)-3, (long)3, (long)9, (long)0, (long)123, (long)1, (long)-10})))\n// (123)\nlong max_element(std::vector l) {\n assert(l.size() > 0);\n return *std::max_element(l.begin(), l.end());"], ["#include\n#include\n// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n// >>> fizz_buzz((50))\n// (0)\n// >>> fizz_buzz((78))\n// (2)\n// >>> fizz_buzz((79))\n// (3)\nlong fizz_buzz(long n) {\n long count = 0;\n for (long i = 1; i < n; i++) {\n if (i % 11 == 0 || i % 13 == 0) {\n std::string str = std::to_string(i);\n count += std::count(str.begin(), str.end(), '7');\n }\n }\n return count;"], ["#include\n#include\n// This function takes a vector l and returns a vector l' such that\n// l' is identical to l in the odd indicies, while its values at the even indicies are equal\n// to the values of the even indicies of l, but sorted.\n// >>> sort_even((std::vector({(long)1, (long)2, (long)3})))\n// (std::vector({(long)1, (long)2, (long)3}))\n// >>> sort_even((std::vector({(long)5, (long)6, (long)3, (long)4})))\n// (std::vector({(long)3, (long)6, (long)5, (long)4}))\nstd::vector sort_even(std::vector l) {\n std::vector even_values;\n for (int i = 0; i < l.size(); i += 2) {\n even_values.push_back(l[i]);\n }\n std::sort(even_values.begin(), even_values.end());\n for (int i = 0; i < even_values.size(); i++) {\n l[2*i+1] = even_values[i];\n }\n return l;"], ["#include\n#include\n// prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n// >>> prime_fib((1))\n// (2)\n// >>> prime_fib((2))\n// (3)\n// >>> prime_fib((3))\n// (5)\n// >>> prime_fib((4))\n// (13)\n// >>> prime_fib((5))\n// (89)\nlong prime_fib(long n) {\n std::vector fibs = {0, 1};\n long i = 2;\n while (fibs.size() < n) {\n fibs.push_back(fibs[i-1] + fibs[i-2]);\n i++;\n }\n long prime_fib_num = 0;\n for (long j = 0; j < fibs.size(); j++) {\n if (is_prime(fibs[j])) {\n prime_fib_num++;\n if (prime_fib_num == n) {\n return fibs[j];\n }\n }\n }\n return -1;"], ["#include\n#include\n// You're given a vector of deposit and withdrawal operations on a bank account that starts with\n// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n// at that point function should return true. Otherwise it should return false.\n// >>> below_zero((std::vector({(long)1, (long)2, (long)3})))\n// (false)\n// >>> below_zero((std::vector({(long)1, (long)2, (long)-4, (long)5})))\n// (true)\nbool below_zero(std::vector operations) {\n long balance = 0;\n for (auto op : operations) {\n balance += op;\n if (balance < 0) {\n return true;\n }\n }\n return false;"], ["#include\n#include\n// triples_sum_to_zero takes a vector of integers as an input.\n// it returns true if there are three distinct elements in the vector that\n// sum to zero, and false otherwise.\n// >>> triples_sum_to_zero((std::vector({(long)1, (long)3, (long)5, (long)0})))\n// (false)\n// >>> triples_sum_to_zero((std::vector({(long)1, (long)3, (long)-2, (long)1})))\n// (true)\n// >>> triples_sum_to_zero((std::vector({(long)1, (long)2, (long)3, (long)7})))\n// (false)\n// >>> triples_sum_to_zero((std::vector({(long)2, (long)4, (long)-5, (long)3, (long)9, (long)7})))\n// (true)\n// >>> triples_sum_to_zero((std::vector({(long)1})))\n// (false)\nbool triples_sum_to_zero(std::vector l) {\n int n = l.size();\n for (int i = 0; i < n - 2; i++) {\n std::unordered_set s;\n for (int j = i + 1; j < n; j++) {\n int x = -(l[i] + l[j]);\n if (s.find(x) != s.end()) {\n return true;\n } else {\n s.insert(l[j]);\n }\n }\n }\n return false;"], ["#include\n#include\n// Imagine a road that's a perfectly straight infinitely long line.\n// n cars are driving left to right; simultaneously, a different set of n cars\n// are driving right to left. The two sets of cars start out being very far from\n// each other. All cars move in the same speed. Two cars are said to collide\n// when a car that's moving left to right hits a car that's moving right to left.\n// However, the cars are infinitely sturdy and strong; as a result, they continue moving\n// in their trajectory as if they did not collide.\n// This function outputs the number of such collisions.\nlong car_race_collision(long n) {\n assert(n >= 0);\n return n * (n - 1) / 2;"], ["#include\n#include\n// Return vector with elements incremented by 1.\n// >>> incr_list((std::vector({(long)1, (long)2, (long)3})))\n// (std::vector({(long)2, (long)3, (long)4}))\n// >>> incr_list((std::vector({(long)5, (long)3, (long)5, (long)2, (long)3, (long)3, (long)9, (long)0, (long)123})))\n// (std::vector({(long)6, (long)4, (long)6, (long)3, (long)4, (long)4, (long)10, (long)1, (long)124}))\nstd::vector incr_list(std::vector l) {\n for (int i = 0; i < l.size(); i++) {\n l[i]++;\n }\n return l;"], ["#include\n#include\n// pairs_sum_to_zero takes a vector of integers as an input.\n// it returns true if there are two distinct elements in the vector that\n// sum to zero, and false otherwise.\n// >>> pairs_sum_to_zero((std::vector({(long)1, (long)3, (long)5, (long)0})))\n// (false)\n// >>> pairs_sum_to_zero((std::vector({(long)1, (long)3, (long)-2, (long)1})))\n// (false)\n// >>> pairs_sum_to_zero((std::vector({(long)1, (long)2, (long)3, (long)7})))\n// (false)\n// >>> pairs_sum_to_zero((std::vector({(long)2, (long)4, (long)-5, (long)3, (long)5, (long)7})))\n// (true)\n// >>> pairs_sum_to_zero((std::vector({(long)1})))\n// (false)\nbool pairs_sum_to_zero(std::vector l) {\n std::unordered_set s;\n for (auto i : l) {\n if (s.find(-i) != s.end()) {\n return true;\n }\n s.insert(i);\n }\n return false;"], ["#include\n#include\n// Change numerical base of input number x to base.\n// return string representation after the conversion.\n// base numbers are less than 10.\n// >>> change_base((8), (3))\n// (\"22\")\n// >>> change_base((8), (2))\n// (\"1000\")\n// >>> change_base((7), (2))\n// (\"111\")\nstd::string change_base(long x, long base) {\n assert(base < 10);\n std::string result = \"\";\n while (x > 0) {\n result = std::to_string(x % base) + result;\n x /= base;\n }\n return result;"], ["#include\n#include\n// Given length of a side and high return area for a triangle.\n// >>> triangle_area((5), (3))\n// (7.5f)\nfloat triangle_area(long a, long h) {\n assert(a > 0 && h > 0);\n return (a * h) / 2.0f;"], ["#include\n#include\n// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n// fib4(0) -> 0\n// fib4(1) -> 0\n// fib4(2) -> 2\n// fib4(3) -> 0\n// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n// >>> fib4((5))\n// (4)\n// >>> fib4((6))\n// (8)\n// >>> fib4((7))\n// (14)\nlong fib4(long n) {\n if (n == 0) {\n return 0;\n }\n if (n == 1) {\n return 0;\n }\n if (n == 2) {\n return 2;\n }\n if (n == 3) {\n return 0;\n }\n long a = 0;\n long b = 0;\n long c = 2;\n long d = 0;\n for (long i = 4; i <= n; i++) {\n long temp = a + b + c + d;\n a = b;\n b = c;\n c = d;\n d = temp;\n }\n return d;"], ["#include\n#include\n// Return median of elements in the vector l.\n// >>> median((std::vector({(long)3, (long)1, (long)2, (long)4, (long)5})))\n// (float(3))\n// >>> median((std::vector({(long)-10, (long)4, (long)6, (long)1000, (long)10, (long)20})))\n// (15.0f)\nfloat median(std::vector l) {\n assert(l.size() > 0);\n std::sort(l.begin(), l.end());\n int n = l.size();\n if (n % 2 == 0) {\n return (l[n/2 - 1] + l[n/2]) / 2.0f;\n } else {\n return l[n/2];\n }"], ["#include\n#include\n// Checks if given string is a palindrome\n// >>> is_palindrome((\"\"))\n// (true)\n// >>> is_palindrome((\"aba\"))\n// (true)\n// >>> is_palindrome((\"aaaaa\"))\n// (true)\n// >>> is_palindrome((\"zbcd\"))\n// (false)\nbool is_palindrome(std::string text) {\n int n = text.length();\n for (int i = 0; i < n/2; i++) {\n if (text[i] != text[n-i-1]) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// Return 2^n modulo p (be aware of numerics).\n// >>> modp((3), (5))\n// (3)\n// >>> modp((1101), (101))\n// (2)\n// >>> modp((0), (101))\n// (1)\n// >>> modp((3), (11))\n// (8)\n// >>> modp((100), (101))\n// (1)\nlong modp(long n, long p) {\n long res = 1;\n n = n % p;\n while (n > 0) {\n if (n & 1)\n res = (res * 2) % p;\n n = n >> 1;\n n = n % p;\n }\n return res;"], ["#include\n#include\n// For a given vector of input numbers, calculate Mean Absolute Deviation\n// around the mean of this dataset.\n// Mean Absolute Deviation is the average absolute difference between each\n// element and a centerpoint (mean in this case):\n// MAD = average | x - x_mean |\n// >>> mean_absolute_deviation((std::vector({(float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f})))\n// (1.0f)\nfloat mean_absolute_deviation(std::vector numbers) {\n float sum = 0.0f;\n float mean = 0.0f;\n float mad = 0.0f;\n int n = numbers.size();\n assert(n > 0);\n for (int i = 0; i < n; i++) {\n sum += numbers[i];\n }\n mean = sum / n;\n for (int i = 0; i < n; i++) {\n mad += fabs(numbers[i] - mean);\n }\n mad /= n;\n return mad;"], ["#include\n#include\n// remove_vowels is a function that takes string and returns string without vowels.\n// >>> remove_vowels((\"\"))\n// (\"\")\n// >>> remove_vowels((\"abcdef\"))\n// (\"bcdf\")\n// >>> remove_vowels((\"aaaaa\"))\n// (\"\")\n// >>> remove_vowels((\"aaBAA\"))\n// (\"B\")\n// >>> remove_vowels((\"zbcd\"))\n// (\"zbcd\")\nstd::string remove_vowels(std::string text) {\n std::string result = \"\";\n for (int i = 0; i < text.length(); i++) {\n char c = text[i];\n if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != 'A' && c != 'E' && c != 'I' && c != 'O' && c != 'U') {\n result += c;\n }\n }\n return result;"], ["#include\n#include\n// Return true if all numbers in the vector l are below threshold t.\n// >>> below_threshold((std::vector({(long)1, (long)2, (long)4, (long)10})), (100))\n// (true)\n// >>> below_threshold((std::vector({(long)1, (long)20, (long)4, (long)10})), (5))\n// (false)\nbool below_threshold(std::vector l, long t) {\n for (auto num : l) {\n if (num >= t) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// Add two numbers x and y\n// >>> add((2), (3))\n// (5)\n// >>> add((5), (7))\n// (12)\nlong add(long x, long y) {\n return x + y;"], ["#include\n#include\n// Check if two words have the same characters.\n// >>> same_chars((\"eabcdzzzz\"), (\"dddzzzzzzzddeddabc\"))\n// (true)\n// >>> same_chars((\"abcd\"), (\"dddddddabc\"))\n// (true)\n// >>> same_chars((\"dddddddabc\"), (\"abcd\"))\n// (true)\n// >>> same_chars((\"eabcd\"), (\"dddddddabc\"))\n// (false)\n// >>> same_chars((\"abcd\"), (\"dddddddabce\"))\n// (false)\n// >>> same_chars((\"eabcdzzzz\"), (\"dddzzzzzzzddddabc\"))\n// (false)\nbool same_chars(std::string s0, std::string s1) {\n std::sort(s0.begin(), s0.end());\n std::sort(s1.begin(), s1.end());\n return s0 == s1;"], ["#include\n#include\n// Return n-th Fibonacci number.\n// >>> fib((10))\n// (55)\n// >>> fib((1))\n// (1)\n// >>> fib((8))\n// (21)\nlong fib(long n) {\n long a = 0, b = 1, c, i;\n if( n == 0)\n return a;\n for(i = 2; i <= n; i++)\n {\n c = a + b;\n a = b;\n b = c;\n }\n return b;"], ["#include\n#include\n// brackets is a string of \"<\" and \">\".\n// return true if every opening bracket has a corresponding closing bracket.\n// >>> correct_bracketing((\"<\"))\n// (false)\n// >>> correct_bracketing((\"<>\"))\n// (true)\n// >>> correct_bracketing((\"<<><>>\"))\n// (true)\n// >>> correct_bracketing((\"><<>\"))\n// (false)\nbool correct_bracketing(std::string brackets) {\n std::stack st;\n for (char c : brackets) {\n if (c == '<') {\n st.push(c);\n } else if (c == '>') {\n if (st.empty()) {\n return false;\n }\n st.pop();\n }\n }\n return st.empty();"], ["#include\n#include\n// Return true is vector elements are monotonically increasing or decreasing.\n// >>> monotonic((std::vector({(long)1, (long)2, (long)4, (long)20})))\n// (true)\n// >>> monotonic((std::vector({(long)1, (long)20, (long)4, (long)10})))\n// (false)\n// >>> monotonic((std::vector({(long)4, (long)1, (long)0, (long)-10})))\n// (true)\nbool monotonic(std::vector l) {\n bool increasing = true, decreasing = true;\n for (int i = 0; i < l.size() - 1; i++) {\n if (l[i] > l[i + 1])\n increasing = false;\n if (l[i] < l[i + 1])\n decreasing = false;\n }\n return increasing || decreasing;"], ["#include\n#include\n// Return sorted unique common elements for two vectors.\n// >>> common((std::vector({(long)1, (long)4, (long)3, (long)34, (long)653, (long)2, (long)5})), (std::vector({(long)5, (long)7, (long)1, (long)5, (long)9, (long)653, (long)121})))\n// (std::vector({(long)1, (long)5, (long)653}))\n// >>> common((std::vector({(long)5, (long)3, (long)2, (long)8})), (std::vector({(long)3, (long)2})))\n// (std::vector({(long)2, (long)3}))\nstd::vector common(std::vector l1, std::vector l2) {\n std::set s1(l1.begin(), l1.end());\n std::set s2(l2.begin(), l2.end());\n std::vector result;\n std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(result));\n std::sort(result.begin(), result.end());\n result.erase(std::unique(result.begin(), result.end()), result.end());\n return result;"], ["#include\n#include\n// Return the largest prime factor of n. Assume n > 1 and is not a prime.\n// >>> largest_prime_factor((13195))\n// (29)\n// >>> largest_prime_factor((2048))\n// (2)\nlong largest_prime_factor(long n) {\n long largest_factor = 0;\n while (n % 2 == 0) {\n largest_factor = 2;\n n = n / 2;\n }\n for (int i = 3; i <= sqrt(n); i = i + 2) {\n while (n % i == 0) {\n largest_factor = i;\n n = n / i;\n }\n }\n if (n > 2) {\n largest_factor = n;\n }\n return largest_factor;"], ["#include\n#include\n// Insert a number 'delimeter' between every two consecutive elements of input vector `numbers'\n// >>> intersperse((std::vector()), (4))\n// (std::vector())\n// >>> intersperse((std::vector({(long)1, (long)2, (long)3})), (4))\n// (std::vector({(long)1, (long)4, (long)2, (long)4, (long)3}))\nstd::vector intersperse(std::vector numbers, long delimeter) {\n std::vector result;\n for (int i = 0; i < numbers.size(); i++) {\n result.push_back(numbers[i]);\n if (i != numbers.size() - 1) {\n result.push_back(delimeter);\n }\n }\n return result;"], ["#include\n#include\n// sum_to_n is a function that sums numbers from 1 to n.\n// >>> sum_to_n((30))\n// (465)\n// >>> sum_to_n((100))\n// (5050)\n// >>> sum_to_n((5))\n// (15)\n// >>> sum_to_n((10))\n// (55)\n// >>> sum_to_n((1))\n// (1)\nlong sum_to_n(long n) {\n return n*(n+1)/2;"], ["#include\n#include\n// brackets is a string of \"(\" and \")\".\n// return true if every opening bracket has a corresponding closing bracket.\n// >>> correct_bracketing((\"(\"))\n// (false)\n// >>> correct_bracketing((\"()\"))\n// (true)\n// >>> correct_bracketing((\"(()())\"))\n// (true)\n// >>> correct_bracketing((\")(()\"))\n// (false)\nbool correct_bracketing(std::string brackets) {\n std::stack st;\n for (char c : brackets) {\n if (c == '(') {\n st.push(c);\n } else if (c == ')') {\n if (st.empty()) {\n return false;\n }\n st.pop();\n }\n }\n return st.empty();"], ["#include\n#include\n// xs represent coefficients of a polynomial.\n// xs[0] + xs[1] * x + xs[2] * x^2 + ....\n// Return derivative of this polynomial in the same form.\n// >>> derivative((std::vector({(long)3, (long)1, (long)2, (long)4, (long)5})))\n// (std::vector({(long)1, (long)4, (long)12, (long)20}))\n// >>> derivative((std::vector({(long)1, (long)2, (long)3})))\n// (std::vector({(long)2, (long)6}))\nstd::vector derivative(std::vector xs) {\n std::vector result;\n for (int i = 1; i < xs.size(); i++) {\n result.push_back(i * xs[i]);\n }\n return result;"], ["#include\n#include\n// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n// fibfib(0) == 0\n// fibfib(1) == 0\n// fibfib(2) == 1\n// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n// Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n// >>> fibfib((1))\n// (0)\n// >>> fibfib((5))\n// (4)\n// >>> fibfib((8))\n// (24)\nlong fibfib(long n) {\n if (n == 0) {\n return 0;\n }\n if (n == 1) {\n return 0;\n }\n if (n == 2) {\n return 1;\n }\n long a = 0;\n long b = 0;\n long c = 1;\n for (long i = 3; i <= n; i++) {\n long temp = a + b + c;\n a = b;\n b = c;\n c = temp;\n }\n return c;"], ["#include\n#include\n// Write a function vowels_count which takes a string representing\n// a word as input and returns the number of vowels in the string.\n// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n// vowel, but only when it is at the end of the given word.\n// Example:\n// >>> vowels_count((\"abcde\"))\n// (2)\n// >>> vowels_count((\"ACEDY\"))\n// (3)\nlong vowels_count(std::string s) {\n long count = 0;\n for (int i = 0; i < s.length(); i++) {\n char c = tolower(s[i]);\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || (c == 'y' && i == s.length() - 1)) {\n count++;\n }\n }\n return count;"], ["#include\n#include\n// Circular shift the digits of the integer x, shift the digits right by shift\n// and return the result as a string.\n// If shift > number of digits, return digits reversed.\n// >>> circular_shift((12), (1))\n// (\"21\")\n// >>> circular_shift((12), (2))\n// (\"12\")\nstd::string circular_shift(long x, long shift) {\n std::string s = std::to_string(x);\n if (shift > s.size()) {\n std::reverse(s.begin(), s.end());\n return s;\n }\n std::rotate(s.begin(), s.end() - shift, s.end());\n return s;"], ["#include\n#include\n// Task\n// Write a function that takes a string as input and returns the sum of the upper characters only'\n// ASCII codes.\n// Examples:\n// >>> digitSum((\"\"))\n// (0)\n// >>> digitSum((\"abAB\"))\n// (131)\n// >>> digitSum((\"abcCd\"))\n// (67)\n// >>> digitSum((\"helloE\"))\n// (69)\n// >>> digitSum((\"woArBld\"))\n// (131)\n// >>> digitSum((\"aAaaaXa\"))\n// (153)\nlong digitSum(std::string s) {\n long sum = 0;\n for (char c : s) {\n if (isupper(c)) {\n sum += c;\n }\n }\n return sum;"], ["#include\n#include\n// In this task, you will be given a string that represents a number of apples and oranges \n// that are distributed in a basket of fruit this basket contains \n// apples, oranges, and mango fruits. Given the string that represents the total number of \n// the oranges and apples and an integer that represent the total number of the fruits \n// in the basket return the number of the mango fruits in the basket.\n// for examble:\n// >>> fruit_distribution((\"5 apples and 6 oranges\"), (19))\n// (8)\n// >>> fruit_distribution((\"0 apples and 1 oranges\"), (3))\n// (2)\n// >>> fruit_distribution((\"2 apples and 3 oranges\"), (100))\n// (95)\n// >>> fruit_distribution((\"100 apples and 1 oranges\"), (120))\n// (19)\nlong fruit_distribution(std::string s, long n) {\n std::stringstream ss(s);\n long apples, oranges;\n ss >> apples >> std::string() >> oranges;\n long mangoes = n - apples - oranges;\n assert(mangoes >= 0);\n return mangoes;"], ["#include\n#include\n// \"Given a vector representing a branch of a tree that has non-negative integer nodes\n// your task is to pluck one of the nodes and return it.\n// The plucked node should be the node with the smallest even value.\n// If multiple nodes with the same smallest even value are found return the node that has smallest index.\n// The plucked node should be returned in a vector, [ smalest_value, its index ],\n// If there are no even values or the given vector is empty, return [].\n// Example 1:\n// >>> pluck((std::vector({(long)4, (long)2, (long)3})))\n// (std::vector({(long)2, (long)1}))\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 2:\n// >>> pluck((std::vector({(long)1, (long)2, (long)3})))\n// (std::vector({(long)2, (long)1}))\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 3:\n// >>> pluck((std::vector()))\n// (std::vector())\n// Example 4:\n// >>> pluck((std::vector({(long)5, (long)0, (long)3, (long)0, (long)4, (long)2})))\n// (std::vector({(long)0, (long)1}))\n// Explanation: 0 is the smallest value, but there are two zeros,\n// so we will choose the first zero, which has the smallest index.\n// Constraints:\n// * 1 <= nodes.length <= 10000\n// * 0 <= node.value\nstd::vector pluck(std::vector arr) {\n long min_even = LONG_MAX;\n long min_index = -1;\n for(int i=0; i\n#include\n// You are given a non-empty vector of positive integers. Return the greatest integer that is greater than \n// zero, and has a frequency greater than or equal to the value of the integer itself. \n// The frequency of an integer is the number of times it appears in the vector.\n// If no such a value exist, return -1.\n// Examples:\n// >>> search((std::vector({(long)4, (long)1, (long)2, (long)2, (long)3, (long)1})))\n// (2)\n// >>> search((std::vector({(long)1, (long)2, (long)2, (long)3, (long)3, (long)3, (long)4, (long)4, (long)4})))\n// (3)\n// >>> search((std::vector({(long)5, (long)5, (long)4, (long)4, (long)4})))\n// (-1)\nlong search(std::vector lst) {\n std::unordered_map freq;\n for (auto num : lst) {\n freq[num]++;\n }\n for (int i = lst.size(); i > 0; i--) {\n if (freq[i] >= i) {\n return i;\n }\n }\n return -1;"], ["#include\n#include\n// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n// For each of the group, output the deepest level of nesting of parentheses.\n// E.g. (()()) has maximum two levels of nesting while ((())) has three.\n// >>> parse_nested_parens((\"(()()) ((())) () ((())()())\"))\n// (std::vector({(long)2, (long)3, (long)1, (long)3}))\nstd::vector parse_nested_parens(std::string paren_string) {\n std::vector result;\n std::stack st;\n long max_depth = 0;\n long curr_depth = 0;\n for (char c : paren_string) {\n if (c == '(') {\n st.push(c);\n curr_depth++;\n max_depth = std::max(max_depth, curr_depth);\n } else if (c == ')') {\n assert(!st.empty() && st.top() == '(');\n st.pop();\n curr_depth--;\n }\n }\n assert(st.empty());\n result.push_back(max_depth);\n return result;"], ["#include\n#include\n// Given vector of integers, return vector in strange order.\n// Strange sorting, is when you start with the minimum value,\n// then maximum of the remaining integers, then minimum and so on.\n// Examples:\n// >>> strange_sort_list((std::vector({(long)1, (long)2, (long)3, (long)4})))\n// (std::vector({(long)1, (long)4, (long)2, (long)3}))\n// >>> strange_sort_list((std::vector({(long)5, (long)5, (long)5, (long)5})))\n// (std::vector({(long)5, (long)5, (long)5, (long)5}))\n// >>> strange_sort_list((std::vector()))\n// (std::vector())\nstd::vector strange_sort_list(std::vector lst) {\n std::vector result;\n while (!lst.empty()) {\n auto min_it = std::min_element(lst.begin(), lst.end());\n result.push_back(*min_it);\n lst.erase(min_it);\n if (!lst.empty()) {\n auto max_it = std::max_element(lst.begin(), lst.end());\n result.push_back(*max_it);\n lst.erase(max_it);\n }\n }\n return result;"], ["#include\n#include\n// Given the lengths of the three sides of a triangle. Return the area of\n// the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n// Otherwise return -1\n// Three sides make a valid triangle when the sum of any two sides is greater \n// than the third side.\n// Example:\n// >>> triangle_area((3), (4), (5))\n// (6.0f)\n// >>> triangle_area((1), (2), (10))\n// (float(-1))\nfloat triangle_area(long a, long b, long c) {\n if (a + b <= c || a + c <= b || b + c <= a) {\n return -1;\n }\n float s = (a + b + c) / 2.0f;\n float area = sqrt(s * (s - a) * (s - b) * (s - c));\n return round(area * 100) / 100.0f;"], ["#include\n#include\n// Write a function that returns true if the object q will fly, and false otherwise.\n// The object q will fly if it's balanced (it is a palindromic vector) and the sum of its elements is less than or equal the maximum possible weight w.\n// Example:\n// >>> will_it_fly((std::vector({(long)1, (long)2})), (5))\n// (false)\n// # 1+2 is less than the maximum possible weight, but it's unbalanced.\n// >>> will_it_fly((std::vector({(long)3, (long)2, (long)3})), (1))\n// (false)\n// # it's balanced, but 3+2+3 is more than the maximum possible weight.\n// >>> will_it_fly((std::vector({(long)3, (long)2, (long)3})), (9))\n// (true)\n// # 3+2+3 is less than the maximum possible weight, and it's balanced.\n// >>> will_it_fly((std::vector({(long)3})), (5))\n// (true)\n// # 3 is less than the maximum possible weight, and it's balanced.\nbool will_it_fly(std::vector q, long w) {\n long sum = 0;\n for (int i = 0; i < q.size(); i++) {\n sum += q[i];\n }\n if (sum > w) {\n return false;\n }\n for (int i = 0; i < q.size() / 2; i++) {\n if (q[i] != q[q.size() - i - 1]) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// Given a vector arr of integers, find the minimum number of elements that\n// need to be changed to make the vector palindromic. A palindromic vector is a vector that\n// is read the same backwards and forwards. In one change, you can change one element to any other element.\n// For example:\n// >>> smallest_change((std::vector({(long)1, (long)2, (long)3, (long)5, (long)4, (long)7, (long)9, (long)6})))\n// (4)\n// >>> smallest_change((std::vector({(long)1, (long)2, (long)3, (long)4, (long)3, (long)2, (long)2})))\n// (1)\n// >>> smallest_change((std::vector({(long)1, (long)2, (long)3, (long)2, (long)1})))\n// (0)\nlong smallest_change(std::vector arr) {\n long n = arr.size();\n long count = 0;\n for (long i = 0; i < n / 2; i++) {\n if (arr[i] != arr[n - i - 1]) {\n count++;\n }\n }\n return count;"], ["#include\n#include\n// Write a function that accepts two vectors of strings and returns the vector that has \n// total number of chars in the all strings of the vector less than the other vector.\n// if the two vectors have the same number of chars, return the first vector.\n// Examples\n// >>> total_match((std::vector()), (std::vector()))\n// (std::vector())\n// >>> total_match((std::vector({(std::string)\"hi\", (std::string)\"admin\"})), (std::vector({(std::string)\"hI\", (std::string)\"Hi\"})))\n// (std::vector({(std::string)\"hI\", (std::string)\"Hi\"}))\n// >>> total_match((std::vector({(std::string)\"hi\", (std::string)\"admin\"})), (std::vector({(std::string)\"hi\", (std::string)\"hi\", (std::string)\"admin\", (std::string)\"project\"})))\n// (std::vector({(std::string)\"hi\", (std::string)\"admin\"}))\n// >>> total_match((std::vector({(std::string)\"hi\", (std::string)\"admin\"})), (std::vector({(std::string)\"hI\", (std::string)\"hi\", (std::string)\"hi\"})))\n// (std::vector({(std::string)\"hI\", (std::string)\"hi\", (std::string)\"hi\"}))\n// >>> total_match((std::vector({(std::string)\"4\"})), (std::vector({(std::string)\"1\", (std::string)\"2\", (std::string)\"3\", (std::string)\"4\", (std::string)\"5\"})))\n// (std::vector({(std::string)\"4\"}))\nstd::vector total_match(std::vector lst1, std::vector lst2) {\n int sum1 = 0, sum2 = 0;\n for (auto str : lst1) {\n sum1 += str.size();\n }\n for (auto str : lst2) {\n sum2 += str.size();\n }\n if (sum1 < sum2) {\n return lst1;\n } else if (sum1 > sum2) {\n return lst2;\n } else {\n return lst1;\n }"], ["#include\n#include\n// Write a function that returns true if the given number is the multiplication of 3 prime numbers\n// and false otherwise.\n// Knowing that (a) is less then 100. \n// Example:\n// >>> is_multiply_prime((30))\n// (true)\n// 30 = 2 * 3 * 5\nbool is_multiply_prime(long a) {\n if (a < 6) {\n return false;\n }\n std::vector primes;\n for (long i = 2; i <= a; i++) {\n bool is_prime = true;\n for (long j = 2; j * j <= i; j++) {\n if (i % j == 0) {\n is_prime = false;\n break;\n }\n }\n if (is_prime) {\n primes.push_back(i);\n }\n }\n for (long i = 0; i < primes.size(); i++) {\n for (long j = i; j < primes.size(); j++) {\n for (long k = j; k < primes.size(); k++) {\n if (primes[i] * primes[j] * primes[k] == a) {\n return true;\n }\n }\n }\n }\n return false;"], ["#include\n#include\n// Your task is to write a function that returns true if a number x is a simple\n// power of n and false in other cases.\n// x is a simple power of n if n**int=x\n// For example:\n// >>> is_simple_power((1), (4))\n// (true)\n// >>> is_simple_power((2), (2))\n// (true)\n// >>> is_simple_power((8), (2))\n// (true)\n// >>> is_simple_power((3), (2))\n// (false)\n// >>> is_simple_power((3), (1))\n// (false)\n// >>> is_simple_power((5), (3))\n// (false)\nbool is_simple_power(long x, long n) {\n if (x == 1) {\n return true;\n }\n long power = 1;\n while (power < x) {\n power *= n;\n }\n return power == x;"], ["#include\n#include\n// Write a function that takes an integer a and returns true \n// if this ingeger is a cube of some integer number.\n// Note: you may assume the input is always valid.\n// Examples:\n// >>> iscube((1))\n// (true)\n// >>> iscube((2))\n// (false)\n// >>> iscube((-1))\n// (true)\n// >>> iscube((64))\n// (true)\n// >>> iscube((0))\n// (true)\n// >>> iscube((180))\n// (false)\nbool iscube(long a) {\n long cube_root = round(cbrt(a));\n return (cube_root * cube_root * cube_root == a);"], ["#include\n#include\n// You have been tasked to write a function that receives \n// a hexadecimal number as a string and counts the number of hexadecimal \n// digits that are primes (prime number, or a prime, is a natural number \n// greater than 1 that is not a product of two smaller natural numbers).\n// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n// So you have to determine a number of the following digits: 2, 3, 5, 7, \n// B (=decimal 11), D (=decimal 13).\n// Note: you may assume the input is always correct or empty string, \n// and symbols A,B,C,D,E,F are always uppercase.\n// Examples:\n// >>> hex_key((\"AB\"))\n// (1)\n// >>> hex_key((\"1077E\"))\n// (2)\n// >>> hex_key((\"ABED1A33\"))\n// (4)\n// >>> hex_key((\"123456789ABCDEF0\"))\n// (6)\n// >>> hex_key((\"2020\"))\n// (2)\nlong hex_key(std::string num) {\n long count = 0;\n for(int i=0; i\n#include\n// You will be given a number in decimal form and your task is to convert it to\n// binary format. The function should return a string, with each character representing a binary\n// number. Each character in the string will be '0' or '1'.\n// There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n// The extra characters are there to help with the format.\n// Examples:\n// >>> decimal_to_binary((15))\n// (\"db1111db\")\n// >>> decimal_to_binary((32))\n// (\"db100000db\")\nstd::string decimal_to_binary(long decimal) {\n std::string binary = \"\";\n while (decimal > 0) {\n binary = std::to_string(decimal % 2) + binary;\n decimal /= 2;\n }\n return \"db\" + binary + \"db\";"], ["#include\n#include\n// Filter an input vector of strings only for ones that contain given substring\n// >>> filter_by_substring((std::vector()), (\"a\"))\n// (std::vector())\n// >>> filter_by_substring((std::vector({(std::string)\"abc\", (std::string)\"bacd\", (std::string)\"cde\", (std::string)\"array\"})), (\"a\"))\n// (std::vector({(std::string)\"abc\", (std::string)\"bacd\", (std::string)\"array\"}))\nstd::vector filter_by_substring(std::vector strings, std::string substring) {\n std::vector result;\n for (auto s : strings) {\n if (s.find(substring) != std::string::npos) {\n result.push_back(s);\n }\n }\n return result;"], ["#include\n#include\n// You are given a string s.\n// Your task is to check if the string is hapcpp or not.\n// A string is hapcpp if its length is at least 3 and every 3 consecutive letters are distinct\n// For example:\n// >>> is_happy((\"a\"))\n// (false)\n// >>> is_happy((\"aa\"))\n// (false)\n// >>> is_happy((\"abcd\"))\n// (true)\n// >>> is_happy((\"aabb\"))\n// (false)\n// >>> is_happy((\"adb\"))\n// (true)\n// >>> is_happy((\"xyy\"))\n// (false)\nbool is_happy(std::string s) {\n int n = s.length();\n if (n < 3) {\n return false;\n }\n for (int i = 0; i < n - 2; i++) {\n if (s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2]) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// It is the last week of the semester and the teacher has to give the grades\n// to students. The teacher has been making her own algorithm for grading.\n// The only problem is, she has lost the code she used for grading.\n// She has given you a vector of GPAs for some students and you have to write \n// a function that can output a vector of letter grades using the following table:\n// GPA | Letter grade\n// 4.0 A+\n// > 3.7 A \n// > 3.3 A- \n// > 3.0 B+\n// > 2.7 B \n// > 2.3 B-\n// > 2.0 C+\n// > 1.7 C\n// > 1.3 C-\n// > 1.0 D+ \n// > 0.7 D \n// > 0.0 D-\n// 0.0 E\n// Example:\n// >>> grade_equation((std::vector({(float)4.0f, (float)3, (float)1.7f, (float)2, (float)3.5f})))\n// (std::vector({(std::string)\"A+\", (std::string)\"B\", (std::string)\"C-\", (std::string)\"C\", (std::string)\"A-\"}))\nstd::vector numerical_letter_grade(std::vector grades) {\n std::vector letter_grades;\n for (auto grade : grades) {\n if (grade == 4.0) {\n letter_grades.push_back(\"A+\");\n } else if (grade > 3.7) {\n letter_grades.push_back(\"A\");\n } else if (grade > 3.3) {\n letter_grades.push_back(\"A-\");\n } else if (grade > 3.0) {\n letter_grades.push_back(\"B+\");\n } else if (grade > 2.7) {\n letter_grades.push_back(\"B\");\n } else if (grade > 2.3) {\n letter_grades.push_back(\"B-\");\n } else if (grade > 2.0) {\n letter_grades.push_back(\"C+\");\n } else if (grade > 1.7) {\n letter_grades.push_back(\"C\");\n } else if (grade > 1.3) {\n letter_grades.push_back(\"C-\");\n } else if (grade > 1.0) {\n letter_grades.push_back(\"D+\");\n } else if (grade > 0.7) {\n letter_grades.push_back(\"D\");\n } else if (grade > 0.0) {\n letter_grades.push_back(\"D-\");\n } else {\n letter_grades.push_back(\"E\");\n }\n }\n return letter_grades;"], ["#include\n#include\n// Write a function that takes a string and returns true if the string\n// length is a prime number or false otherwise\n// Examples\n// >>> prime_length((\"Hello\"))\n// (true)\n// >>> prime_length((\"abcdcba\"))\n// (true)\n// >>> prime_length((\"kittens\"))\n// (true)\n// >>> prime_length((\"orange\"))\n// (false)\nbool prime_length(std::string string) {\n int length = string.length();\n if (length < 2) {\n return false;\n }\n for (int i = 2; i <= sqrt(length); i++) {\n if (length % i == 0) {\n return false;\n }\n }\n return true;"], ["#include\n#include\n// Given a positive integer n, return the count of the numbers of n-digit\n// positive integers that start or end with 1.\nlong starts_one_ends(long n) {\n if (n == 1) {\n return 1;\n }\n long count = 0;\n for (int i = 1; i < n; i++) {\n count += pow(2, i - 1);\n }\n return count * 2 + 1;"], ["#include\n#include\n// Given a positive integer N, return the total sum of its digits in binary.\n// Example\n// >>> solve((1000))\n// (\"1\")\n// >>> solve((150))\n// (\"110\")\n// >>> solve((147))\n// (\"1100\")\n// Variables:\n// @N integer\n// Constraints: 0 \u2264 N \u2264 10000.\n// Output:\n// a string of binary number\nstd::string solve(long N) {\n assert(0 <= N && N <= 10000);\n std::string binary = \"\";\n while (N > 0) {\n binary = std::to_string(N % 2) + binary;\n N /= 2;\n }\n return binary;"], ["#include\n#include\n// Given a non-empty vector of integers lst. add the even elements that are at odd indices..\n// Examples:\n// >>> add((std::vector({(long)4, (long)2, (long)6, (long)7})))\n// (2)\nlong add(std::vector lst) {\n long sum = 0;\n for (int i = 1; i < lst.size(); i += 2) {\n if (lst[i] % 2 == 0) {\n sum += lst[i];\n }\n }\n return sum;"], ["#include\n#include\n// Write a function that takes a string and returns an ordered version of it.\n// Ordered version of string, is a string where all words (separated by space)\n// are replaced by a new word where all the characters arranged in\n// ascending order based on ascii value.\n// Note: You should keep the order of words and blank spaces in the sentence.\n// For example:\n// >>> anti_shuffle((\"Hi\"))\n// (\"Hi\")\n// >>> anti_shuffle((\"hello\"))\n// (\"ehllo\")\n// >>> anti_shuffle((\"Hello World!!!\"))\n// (\"Hello !!!Wdlor\")\nstd::string anti_shuffle(std::string s) {\n std::stringstream ss(s);\n std::string word;\n std::string result = \"\";\n while (ss >> word) {\n std::sort(word.begin(), word.end());\n result += word + \" \";\n }\n result.pop_back(); // remove the last space\n return result;"], ["#include\n#include\n// You are given a 2 dimensional data, as a nested vectors,\n// which is similar to matrix, however, unlike matrices,\n// each row may contain a different number of columns.\n// Given lst, and integer x, find integers x in the vector,\n// and return vector of tuples, [(x1, y1), (x2, y2) ...] such that\n// each tuple is a coordinate - (row, columns), starting with 0.\n// Sort coordinates initially by rows in ascending order.\n// Also, sort coordinates of the row by columns in descending order.\n// Examples:\n// >>> get_row((std::vector>({(std::vector)std::vector({(long)1, (long)2, (long)3, (long)4, (long)5, (long)6}), (std::vector)std::vector({(long)1, (long)2, (long)3, (long)4, (long)1, (long)6}), (std::vector)std::vector({(long)1, (long)2, (long)3, (long)4, (long)5, (long)1})})), (1))\n// (std::vector>({(std::tuple)std::make_tuple(0, 0), (std::tuple)std::make_tuple(1, 4), (std::tuple)std::make_tuple(1, 0), (std::tuple)std::make_tuple(2, 5), (std::tuple)std::make_tuple(2, 0)}))\n// >>> get_row((std::vector>()), (1))\n// (std::vector>())\n// >>> get_row((std::vector>({(std::vector)std::vector(), (std::vector)std::vector({(long)1}), (std::vector)std::vector({(long)1, (long)2, (long)3})})), (3))\n// (std::vector>({(std::tuple)std::make_tuple(2, 2)}))\nstd::vector> get_row(std::vector> lst, long x) {\n std::vector> result;\n for (long i = 0; i < lst.size(); i++) {\n for (long j = 0; j < lst[i].size(); j++) {\n if (lst[i][j] == x) {\n result.push_back(std::make_tuple(i, j));\n }\n }\n }\n std::sort(result.begin(), result.end(), [](const std::tuple& a, const std::tuple& b) {\n if (std::get<0>(a) != std::get<0>(b)) {\n return std::get<0>(a) < std::get<0>(b);\n } else {\n return std::get<1>(a) > std::get<1>(b);\n }\n });\n return result;"], ["#include\n#include\n// Given a vector of non-negative integers, return a cocpp of the given vector after sorting,\n// you will sort the given vector in ascending order if the sum( first index value, last index value) is odd,\n// or sort it in descending order if the sum( first index value, last index value) is even.\n// Note:\n// * don't change the given vector.\n// Examples:\n// >>> sort_array((std::vector()))\n// (std::vector())\n// >>> sort_array((std::vector({(long)5})))\n// (std::vector({(long)5}))\n// >>> sort_array((std::vector({(long)2, (long)4, (long)3, (long)0, (long)1, (long)5})))\n// (std::vector({(long)0, (long)1, (long)2, (long)3, (long)4, (long)5}))\n// >>> sort_array((std::vector({(long)2, (long)4, (long)3, (long)0, (long)1, (long)5, (long)6})))\n// (std::vector({(long)6, (long)5, (long)4, (long)3, (long)2, (long)1, (long)0}))\nstd::vector sort_array(std::vector array) {\n if (array.size() == 0) {\n return array;\n }\n std::vector sorted_array = array;\n long sum = array[0] + array[array.size() - 1];\n if (sum % 2 == 0) {\n std::sort(sorted_array.begin(), sorted_array.end(), std::greater());\n } else {\n std::sort(sorted_array.begin(), sorted_array.end());\n }\n return sorted_array;"], ["#include\n#include\n// Create a function encrypt that takes a string as an argument and\n// returns a string encrypted with the alphabet being rotated. \n// The alphabet should be rotated in a manner such that the letters \n// shift down by two multiplied to two places.\n// For example:\n// >>> encrypt((\"hi\"))\n// (\"lm\")\n// >>> encrypt((\"asdfghjkl\"))\n// (\"ewhjklnop\")\n// >>> encrypt((\"gf\"))\n// (\"kj\")\n// >>> encrypt((\"et\"))\n// (\"ix\")\nstd::string encrypt(std::string s) {\n std::string result = \"\";\n for (int i = 0; i < s.length(); i++) {\n if (s[i] >= 'a' && s[i] <= 'z') {\n result += (s[i] - 'a' + 2*2) % 26 + 'a';\n } else if (s[i] >= 'A' && s[i] <= 'Z') {\n result += (s[i] - 'A' + 2*2) % 26 + 'A';\n } else {\n result += s[i];\n }\n }\n return result;"], ["#include\n#include\n// For a given vector of integers, return a tuple consisting of a sum and a product of all the integers in a vector.\n// Empty sum should be equal to 0 and empty product should be equal to 1.\n// >>> sum_product((std::vector()))\n// (std::make_tuple(0, 1))\n// >>> sum_product((std::vector({(long)1, (long)2, (long)3, (long)4})))\n// (std::make_tuple(10, 24))\nstd::tuple sum_product(std::vector numbers) {\n long sum = 0;\n long product = 1;\n for (auto number : numbers) {\n sum += number;\n product *= number;\n }\n return std::make_tuple(sum, product);"], ["#include\n#include\n// You are given a vector of integers.\n// Write a function next_smallest() that returns the 2nd smallest element of the vector.\n// Return None if there is no such element.\n// >>> next_smallest((std::vector({(long)1, (long)2, (long)3, (long)4, (long)5})))\n// 2\n// >>> next_smallest((std::vector({(long)5, (long)1, (long)4, (long)3, (long)2})))\n// 2\n// >>> next_smallest((std::vector()))\n// std::nullopt\n// >>> next_smallest((std::vector({(long)1, (long)1})))\n// std::nullopt\nstd::optional next_smallest(std::vector lst) {\n if (lst.size() < 2) {\n return std::nullopt;\n }\n std::sort(lst.begin(), lst.end());\n return lst[1];"], ["#include\n#include\n// You'll be given a string of words, and your task is to count the number\n// of boredoms. A boredom is a sentence that starts with the word \"I\".\n// Sentences are delimited by '.', '?' or '!'.\n// For example:\n// >>> is_bored((\"Hello world\"))\n// (0)\n// >>> is_bored((\"The sky is blue. The sun is shining. I love this weather\"))\n// (1)\nlong is_bored(std::string S) {\n long count = 0;\n std::stringstream ss(S);\n std::string word;\n while (ss >> word) {\n if (word[0] == 'I') {\n count++;\n }\n }\n return count;"], ["#include\n#include\n// Create a function that takes 3 numbers.\n// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n// Returns false in any other cases.\n// Examples\n// >>> any_int((float(5)), (float(2)), (float(7)))\n// (true)\n// >>> any_int((float(3)), (float(2)), (float(2)))\n// (false)\n// >>> any_int((float(3)), (float(-2)), (float(1)))\n// (true)\n// >>> any_int((3.6f), (-2.2f), (float(2)))\n// (false)\nbool any_int(float x, float y, float z) {\n int a = (int) x;\n int b = (int) y;\n int c = (int) z;\n if (a == b + c || b == a + c || c == a + b) {\n return true;\n }\n return false;"], ["#include\n#include\n// Write a function that takes a message, and encodes in such a \n// way that it swaps case of all letters, replaces all vowels in \n// the message with the letter that appears 2 places ahead of that \n// vowel in the english alphabet. \n// Assume only letters. \n// Examples:\n// >>> encode((\"test\"))\n// (\"TGST\")\n// >>> encode((\"This is a message\"))\n// (\"tHKS KS C MGSSCGG\")\nstd::string encode(std::string message) {\n std::string vowels = \"aeiouAEIOU\";\n std::string encoded_message = \"\";\n for (int i = 0; i < message.length(); i++) {\n if (isalpha(message[i])) {\n if (isupper(message[i])) {\n encoded_message += tolower(message[i]);\n } else {\n encoded_message += toupper(message[i]);\n }\n if (vowels.find(message[i]) != std::string::npos) {\n int index = vowels.find(message[i]);\n int new_index = (index + 2) % vowels.length();\n encoded_message[i] = vowels[new_index];\n }\n } else {\n encoded_message += message[i];\n }\n }\n return encoded_message;"], ["#include\n#include\n// You are given a vector of integers.\n// You need to find the largest prime value and return the sum of its digits.\n// Examples:\n// >>> skjkasdkd((std::vector({(long)0, (long)3, (long)2, (long)1, (long)3, (long)5, (long)7, (long)4, (long)5, (long)5, (long)5, (long)2, (long)181, (long)32, (long)4, (long)32, (long)3, (long)2, (long)32, (long)324, (long)4, (long)3})))\n// (10)\n// >>> skjkasdkd((std::vector({(long)1, (long)0, (long)1, (long)8, (long)2, (long)4597, (long)2, (long)1, (long)3, (long)40, (long)1, (long)2, (long)1, (long)2, (long)4, (long)2, (long)5, (long)1})))\n// (25)\n// >>> skjkasdkd((std::vector({(long)1, (long)3, (long)1, (long)32, (long)5107, (long)34, (long)83278, (long)109, (long)163, (long)23, (long)2323, (long)32, (long)30, (long)1, (long)9, (long)3})))\n// (13)\n// >>> skjkasdkd((std::vector({(long)0, (long)724, (long)32, (long)71, (long)99, (long)32, (long)6, (long)0, (long)5, (long)91, (long)83, (long)0, (long)5, (long)6})))\n// (11)\n// >>> skjkasdkd((std::vector({(long)0, (long)81, (long)12, (long)3, (long)1, (long)21})))\n// (3)\n// >>> skjkasdkd((std::vector({(long)0, (long)8, (long)1, (long)2, (long)1, (long)7})))\n// (7)\nlong skjkasdkd(std::vector lst) {\n long max_prime = 0;\n for (long num : lst) {\n if (num <= 1) continue;\n bool is_prime = true;\n for (long i = 2; i * i <= num; i++) {\n if (num % i == 0) {\n is_prime = false;\n break;\n }\n }\n if (is_prime && num > max_prime) {\n max_prime = num;\n }\n }\n long sum_of_digits = 0;\n while (max_prime > 0) {\n sum_of_digits += max_prime % 10;\n max_prime /= 10;\n }\n return sum_of_digits;"], ["#include\n#include\n// Given a map, return true if all keys are strings in lower \n// case or all keys are strings in upper case, else return false.\n// The function should return false is the given map is empty.\n// Examples:\n// >>> check_dict_case((std::map({{\"a\", \"apple\"}, {\"b\", \"banana\"}})))\n// (true)\n// >>> check_dict_case((std::map({{\"a\", \"apple\"}, {\"A\", \"banana\"}, {\"B\", \"banana\"}})))\n// (false)\n// >>> check_dict_case((std::map({{\"a\", \"apple\"}, {8, \"banana\"}, {\"a\", \"apple\"}})))\n// (false)\n// >>> check_dict_case((std::map({{\"Name\", \"John\"}, {\"Age\", \"36\"}, {\"City\", \"Houston\"}})))\n// (false)\n// >>> check_dict_case((std::map({{\"STATE\", \"NC\"}, {\"ZIP\", \"12345\"}})))\n// (true)\nbool check_dict_case(std::map dict) {\n if (dict.empty()) {\n return false;\n }\n bool all_lower = true;\n bool all_upper = true;\n for (auto const& [key, val] : dict) {\n if (!std::all_of(key.begin(), key.end(), islower)) {\n all_lower = false;\n }\n if (!std::all_of(key.begin(), key.end(), isupper)) {\n all_upper = false;\n }\n }\n return all_lower || all_upper;"], ["#include\n#include\n// Implement a function that takes an non-negative integer and returns a vector of the first n\n// integers that are prime numbers and less than n.\n// for example:\n// >>> count_up_to((5))\n// (std::vector({(long)2, (long)3}))\n// >>> count_up_to((11))\n// (std::vector({(long)2, (long)3, (long)5, (long)7}))\n// >>> count_up_to((0))\n// (std::vector())\n// >>> count_up_to((20))\n// (std::vector({(long)2, (long)3, (long)5, (long)7, (long)11, (long)13, (long)17, (long)19}))\n// >>> count_up_to((1))\n// (std::vector())\n// >>> count_up_to((18))\n// (std::vector({(long)2, (long)3, (long)5, (long)7, (long)11, (long)13, (long)17}))\nstd::vector count_up_to(long n) {\n std::vector primes;\n for (long i = 2; i < n; i++) {\n bool is_prime = true;\n for (long j = 2; j * j <= i; j++) {\n if (i % j == 0) {\n is_prime = false;\n break;\n }\n }\n if (is_prime) {\n primes.push_back(i);\n }\n }\n return primes;"], ["#include\n#include\n// Complete the function that takes two integers and returns \n// the product of their unit digits.\n// Assume the input is always valid.\n// Examples:\n// >>> multiply((148), (412))\n// (16)\n// >>> multiply((19), (28))\n// (72)\n// >>> multiply((2020), (1851))\n// (0)\n// >>> multiply((14), (-15))\n// (20)\nlong multiply(long a, long b) {\n int unit_digit_a = a % 10;\n int unit_digit_b = b % 10;\n return (unit_digit_a * unit_digit_b) % 10;"], ["#include\n#include\n// Given a string s, count the number of uppercase vowels in even indices.\n// For example:\n// >>> count_upper((\"aBCdEf\"))\n// (1)\n// >>> count_upper((\"abcdefg\"))\n// (0)\n// >>> count_upper((\"dBBE\"))\n// (0)\nlong count_upper(std::string s) {\n long count = 0;\n for (int i = 0; i < s.length(); i += 2) {\n if (isupper(s[i]) && (s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')) {\n count++;\n }\n }\n return count;"], ["#include\n#include\n// Create a function that takes a value (string) representing a number\n// and returns the closest integer to it. If the number is equidistant\n// from two integers, round it away from zero.\n// Examples\n// >>> closest_integer((\"10\"))\n// (10)\n// >>> closest_integer((\"15.3\"))\n// (15)\n// Note:\n// Rounding away from zero means that if the given number is equidistant\n// from two integers, the one you should return is the one that is the\n// farthest from zero. For example closest_integer(\"14.5\") should\n// return 15 and closest_integer(\"-14.5\") should return -15.\nlong closest_integer(std::string value) {\n double num = std::stod(value);\n long rounded_num = std::lround(num);\n return rounded_num;"], ["#include\n#include\n// From a given vector of integers, generate a vector of rolling maximum element found until given moment\n// in the sequence.\n// >>> rolling_max((std::vector({(long)1, (long)2, (long)3, (long)2, (long)3, (long)4, (long)2})))\n// (std::vector({(long)1, (long)2, (long)3, (long)3, (long)3, (long)4, (long)4}))\nstd::vector rolling_max(std::vector numbers) {\n std::vector result;\n std::deque dq;\n for (int i = 0; i < numbers.size(); i++) {\n while (!dq.empty() && dq.back() < numbers[i]) {\n dq.pop_back();\n }\n dq.push_back(numbers[i]);\n result.push_back(dq.front());\n }\n return result;"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-d_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-d_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..022ab659c4a28dab4c81d88d1a2543f961d3b53a --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-d_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["import std.math;\n/*\n Check if in given array of numbers, are any two numbers closer to each other than\ngiven threshold.\n>>> has_close_elements([1.0, 2.0, 3.0], 0.5)\nfalse\n>>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\ntrue\n*/\nbool has_close_elements(float[] numbers, float threshold)\n{\n for (int i = 0; i < numbers.length; i++) {\n for (int j = i + 1; j < numbers.length; j++) {\n if (abs(numbers[i] - numbers[j]) <= threshold) {\n return true;\n }\n }\n }\n return false;\n}\n"], ["import std.math;\n/*\nGiven a positive integer n, you have to make a pile of n levels of stones.\nThe first level has n stones.\nThe number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\nReturn the number of stones in each level in an array, where element at index\ni represents the number of stones in the level (i+1).\nExamples:\n>>> make_a_pile(3L)\n[3L, 5L, 7L]\n*/\nlong[] make_a_pile(long n)\n{\n long[] pile = new long[n];\n long stones = n;\n for(long i = 0; i < n; i++)\n {\n pile[i] = stones;\n if(stones % 2 == 0)\n {\n stones += 2;\n }\n else\n {\n stones += 2;\n }\n }\n return pile;\n}\n"], ["import std.math;\n/*\nYou will be given a string of words separated by commas or spaces. Your task is\nto split the string into words and return an array of the words.\nFor example:\n>>> words_string(\"Hi, my name is John\")\n[\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n>>> words_string(\"One, two, three, four, five, six\")\n[\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n*/\nstring[] words_string(string s)\n{\n string[] words;\n int i = 0;\n int j = 0;\n int len = s.length;\n while (i < len)\n {\n while (i < len && (s[i] == ' ' || s[i] == ','))\n {\n i++;\n }\n j = i;\n while (j < len && s[j] != ' ' && s[j] != ',')\n {\n j++;\n }\n if (i < len)\n {\n words.push_back(s.substr(i, j - i));\n }\n i = j;\n }\n return words;\n}\n"], ["import std.math;\n/*\nThis function takes two positive numbers x and y and returns the\nbiggest even integer number that is in the range [x, y] inclusive. If \nthere's no such number, then the function should return -1.\nFor example:\n>>> choose_num(12L, 15L)\n14L\n>>> choose_num(13L, 12L)\n-1L\n*/\nlong choose_num(long x, long y)\n{\n long result = -1;\n for(long i = y; i >= x; i--)\n {\n if(i % 2 == 0)\n {\n result = i;\n break;\n }\n }\n return result;\n}\n"], ["import std.math;\n/*\nGiven an array of positive integers x. return a sorted array of all \nelements that hasn't any even digit.\nNote: Returned array should be sorted in increasing order.\nFor example:\n>>> unique_digits([15L, 33L, 1422L, 1L])\n[1L, 15L, 33L]\n>>> unique_digits([152L, 323L, 1422L, 10L])\n[]\n*/\nlong[] unique_digits(long[] x)\n{\n long[] result = new long[x.length];\n int count = 0;\n foreach(long num in x)\n {\n bool hasEvenDigit = false;\n long temp = num;\n while(temp > 0)\n {\n if(temp % 10 % 2 == 0)\n {\n hasEvenDigit = true;\n break;\n }\n temp /= 10;\n }\n if(!hasEvenDigit)\n {\n result[count++] = num;\n }\n }\n long[] finalResult = new long[count];\n for(int i = 0; i < count; i++)\n {\n finalResult[i] = result[i];\n }\n return finalResult.sort();\n}\n"], ["import std.math;\n/*\nGiven an array of integers, sort the integers that are between 1 and 9 inclusive,\nreverse the resulting array, and then replace each digit by its corresponding name from\n\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\nFor example:\n>>> by_length([2L, 1L, 1L, 4L, 5L, 8L, 2L, 3L])\n[\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n If the array is empty, return an empty array:\n>>> by_length([])\n[]\n If the array has any strange number ignore it:\n>>> by_length([1L, -1L, 55L])\n[\"One\"]\n*/\nstring[] by_length(long[] arr)\n{\n string[] names = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"];\n long[] sorted = arr.filter(x => x >= 1 && x <= 9).sort().reverse();\n string[] result = new string[sorted.length];\n for (int i = 0; i < sorted.length; i++) {\n result[i] = names[sorted[i] - 1];\n }\n return result;\n}\n"], ["import std.math;\n/*\n Implement the function f that takes n as a parameter,\nand returns an array of size n, such that the value of the element at index i is the factorial of i if i is even\nor the sum of numbers from 1 to i otherwise.\ni starts from 1.\nthe factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\nExample:\n>>> f(5L)\n[1L, 2L, 6L, 24L, 15L]\n*/\nlong[] f(long n)\n{\n long[] result = new long[n];\n for(long i = 1; i <= n; i++)\n {\n if(i % 2 == 0)\n {\n result[(int)i-1] = factorial(i);\n }\n else\n {\n long sum = 0;\n for(long j = 1; j <= i; j++)\n {\n sum += j;\n }\n result[(int)i-1] = sum;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer n, return a tuple that has the number of even and odd\ninteger palindromes that fall within the range(1, n), inclusive.\nExample 1:\n>>> even_odd_palindrome(3L)\ntuple(1L, 2L)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\nExample 2:\n>>> even_odd_palindrome(12L)\ntuple(4L, 6L)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\nNote:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\n*/\nTuple!(long, long) even_odd_palindrome(long n)\nnot immutable long countEven = 0;\nnot immutable long countOdd = 0;"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function count_nums which takes an array of integers and returns\nthe number of elements which has a sum of digits > 0.\nIf a number is negative, then its first signed digit will be negative:\ne.g. -123 has signed digits -1, 2, and 3.\n>>> count_nums([])\n0L\n>>> count_nums([-1L, 11L, -11L])\n1L\n>>> count_nums([1L, 1L, 2L])\n3L\n*/\nlong count_nums(long[] arr)\n{\n long count = 0L;\n foreach (num; arr)\n {\n long sum = 0L;\n long n = abs(num);\n while (n > 0)\n {\n sum += n % 10;\n n /= 10;\n }\n if (sum > 0)\n {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWe have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\nnumbers in the array will be randomly ordered. Your task is to determine if\nit is possible to get an array sorted in non-decreasing order by performing \nthe following operation on the given array:\n You are allowed to perform right shift operation any number of times.\nOne right shift operation means shifting all elements of the array by one\nposition in the right direction. The last element of the array will be moved to\nthe starting position in the array i.e. 0th index. \nIf it is possible to obtain the sorted array by performing the above operation\nthen return true else return false.\nIf the given array is empty then return true.\nNote: The given array is guaranteed to have unique elements.\nFor Example:\n>>> move_one_ball([3L, 4L, 5L, 1L, 2L])\ntrue\nExplanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given array.\n>>> move_one_ball([3L, 5L, 4L, 1L, 2L])\nfalse\nExplanation:It is not possible to get non-decreasing order for the given\n array by performing any number of right shift operations.\n*/\nbool move_one_ball(long[] arr)\n{\n if (arr.length == 0) {\n return true;\n }\n int count = 0;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] > arr[(i + 1) % arr.length]) {\n count++;\n }\n }\n return count <= 1;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Find the shortest palindrome that begins with a supplied string.\nAlgorithm idea is simple:\n- Find the longest postfix of supplied string that is a palindrome.\n- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n>>> make_palindrome(\"\")\n\"\"\n>>> make_palindrome(\"cat\")\n\"catac\"\n>>> make_palindrome(\"cata\")\n\"catac\"\n*/\nstring make_palindrome(string string)\n{\n int n = string.length;\n int i = 0;\n while (i < n)\n {\n int j = n - 1;\n while (j >= i && string[i] == string[j])\n {\n i++;\n j--;\n }\n if (i >= j)\n {\n break;\n }\n i = 0;\n n--;\n }\n string palindrome = string;\n for (int k = n - 1; k >= 0; k--)\n {\n palindrome ~= string[k];\n }\n return palindrome;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nIn this problem, you will implement a function that takes two arrays of numbers,\nand determines whether it is possible to perform an exchange of elements\nbetween them to make lst1 an array of only even numbers.\nThere is no limit on the number of exchanged elements between lst1 and lst2.\nIf it is possible to exchange elements between the lst1 and lst2 to make\nall the elements of lst1 to be even, return \"YES\".\nOtherwise, return \"NO\".\nFor example:\n>>> exchange([1L, 2L, 3L, 4L], [1L, 2L, 3L, 4L])\n\"YES\"\n>>> exchange([1L, 2L, 3L, 4L], [1L, 5L, 3L, 4L])\n\"NO\"\nIt is assumed that the input arrays will be non-empty.\n*/\nstring exchange(long[] lst1, long[] lst2)\n{\n long evenCount1 = 0;\n long evenCount2 = 0;\n long oddCount1 = 0;\n long oddCount2 = 0;"], ["import std.math;\nimport std.typecons;\n/*\nGiven a string representing a space separated lowercase letters, return an associative array\nof the letter with the most repetition and containing the corresponding count.\nIf several letters have the same occurrence, return all of them.\nExample:\n>>> histogram(\"a b c\")\n[\"a\": 1L, \"b\": 1L, \"c\": 1L].nullable\n>>> histogram(\"a b b a\")\n[\"a\": 2L, \"b\": 2L].nullable\n>>> histogram(\"a b c a b\")\n[\"a\": 2L, \"b\": 2L].nullable\n>>> histogram(\"b b b b a\")\n[\"b\": 4L].nullable\n>>> histogram(\"\")\n___null_dict___\n*/\nNullable!(long[string]) histogram(string test)\nnot null\n{\n long[string] result;\n string[] words = test.split(\" \");\n foreach (word; words)\n {\n foreach (c; word)\n {\n if (result.exists(c))\n {\n result[c]++;\n }\n else\n {\n result[c] = 1L;\n }\n }\n }\n long maxCount = 0L;\n foreach (key; result.keys)\n {\n if (result[key] > maxCount)\n {\n maxCount = result[key];\n }\n }\n long[string] maxResult;\n foreach (key; result.keys)\n {\n if (result[key] == maxCount)\n {\n maxResult[key] = result[key];\n }\n }\n return maxResult.nullable;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nTask\nWe are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\nthen check if the result string is palindrome.\nA string is called palindrome if it reads the same backward as forward.\nYou should return a tuple containing the result string and true/false for the check.\nExample\n>>> reverse_delete(\"abcde\", \"ae\")\ntuple(\"bcd\", false)\n>>> reverse_delete(\"abcdef\", \"b\")\ntuple(\"acdef\", false)\n>>> reverse_delete(\"abcdedcba\", \"ab\")\ntuple(\"cdedc\", true)\n*/\nTuple!(string, bool) reverse_delete(string s, string c)\n{\n string result = \"\";\n foreach (char ch; s)\n {\n if (!c.contains(ch))\n {\n result ~= ch;\n }\n }\n bool isPalindrome = true;\n for (size_t i = 0; i < result.length / 2; i++)\n {\n if (result[i] != result[result.length - i - 1])\n {\n isPalindrome = false;\n break;\n }\n }\n return tuple(result, isPalindrome);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array of strings, where each string consists of only digits, return an array.\nEach element i of the output should be \"the number of odd elements in the\nstring i of the input.\" where all the i's should be replaced by the number\nof odd digits in the i'th string of the input.\n>>> odd_count([\"1234567\"])\n[\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n>>> odd_count([\"3\", \"11111111\"])\n[\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\n*/\nstring[] odd_count(string[] lst)\n{\n string[] result = new string[lst.length];\n for(int i = 0; i < lst.length; i++)\n {\n int count = 0;\n foreach(char c; lst[i])\n {\n if(c.toInt() % 2 != 0)\n {\n count++;\n }\n }\n result[i] = \"the number of odd elements \" ~ count ~ \"n the str\" ~ count ~ \"ng \" ~ count ~ \" of the \" ~ count ~ \"nput.\";\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array of integers nums, find the minimum sum of any non-empty sub-array\nof nums.\nExample\n>>> minSubArraySum([2L, 3L, 4L, 1L, 2L, 4L])\n1L\n>>> minSubArraySum([-1L, -2L, -3L])\n-6L\n*/\nlong minSubArraySum(long[] nums)\n{\n long minSum = nums[0];\n long currSum = nums[0];\n for (long i = 1; i < nums.length; i++)\n {\n currSum = min(nums[i], currSum + nums[i]);\n minSum = min(minSum, currSum);\n }\n return minSum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a rectangular grid of wells. Each row represents a single well,\nand each 1 in a row represents a single unit of water.\nEach well has a corresponding bucket that can be used to extract water from it, \nand all buckets have the same capacity.\nYour task is to use the buckets to empty the wells.\nOutput the number of times you need to lower the buckets.\nExample 1:\n>>> max_fill([[0L, 0L, 1L, 0L], [0L, 1L, 0L, 0L], [1L, 1L, 1L, 1L]], 1L)\n6L\nExample 2:\n>>> max_fill([[0L, 0L, 1L, 1L], [0L, 0L, 0L, 0L], [1L, 1L, 1L, 1L], [0L, 1L, 1L, 1L]], 2L)\n5L\nExample 3:\n>>> max_fill([[0L, 0L, 0L], [0L, 0L, 0L]], 5L)\n0L\nConstraints:\n * all wells have the same length\n * 1 <= grid.length <= 10^2\n * 1 <= grid[:,1].length <= 10^2\n * grid[i][j] -> 0 | 1\n * 1 <= capacity <= 10\n*/\nlong max_fill(long[][] grid, long capacity)\n{\n long max_fill = 0;\n long num_rows = grid.length;\n long num_cols = grid[0].length;\n long[] row_sums = new long[num_rows];\n long[] col_sums = new long[num_cols];"], ["import std.math;\nimport std.typecons;\n/*\nIn this Kata, you have to sort an array of non-negative integers according to\nnumber of ones in their binary representation in ascending order.\nFor similar number of ones, sort based on decimal value.\nIt must be implemented like this:\n>>> sort_array([1L, 5L, 2L, 3L, 4L])\n[1L, 2L, 3L, 4L, 5L]\n>>> sort_array([-2L, -3L, -4L, -5L, -6L])\n[-6L, -5L, -4L, -3L, -2L]\n>>> sort_array([1L, 0L, 2L, 3L, 4L])\n[0L, 1L, 2L, 3L, 4L]\n*/\nlong[] sort_array(long[] arr)\n{\n return arr.sort((a, b) => (a.countOnes().compare(b.countOnes()) == 0) ? a.compare(b) : a.countOnes().compare(b.countOnes()));\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a string s and a natural number n, you have been tasked to implement \na function that returns an array of all words from string s that contain exactly \nn consonants, in order these words appear in the string s.\nIf the string s is empty then the function should return an empty array.\nNote: you may assume the input string contains only letters and spaces.\nExamples:\n>>> select_words(\"Mary had a little lamb\", 4L)\n[\"little\"]\n>>> select_words(\"Mary had a little lamb\", 3L)\n[\"Mary\", \"lamb\"]\n>>> select_words(\"simple white space\", 2L)\n[]\n>>> select_words(\"Hello world\", 4L)\n[\"world\"]\n>>> select_words(\"Uncle sam\", 3L)\n[\"Uncle\"]\n*/\nstring[] select_words(string s, long n)\n{\n string[] words = s.split(\" \");\n string[] result = new string[0];\n foreach (word; words)\n {\n long consonants = 0;\n foreach (c; word)\n {\n if (c.isLetter() && !\"aeiouAEIOU\".contains(c))\n {\n consonants++;\n }\n }\n if (consonants == n)\n {\n result ~= word;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a word. Your task is to find the closest vowel that stands between \ntwo consonants from the right side of the word (case sensitive).\nVowels in the beginning and ending doesn't count. Return empty string if you didn't\nfind any vowel met the above condition. \nYou may assume that the given string contains English letter only.\nExample:\n>>> get_closest_vowel(\"yogurt\")\n\"u\"\n>>> get_closest_vowel(\"FULL\")\n\"U\"\n>>> get_closest_vowel(\"quick\")\n\"\"\n>>> get_closest_vowel(\"ab\")\n\"\"\n*/\nstring get_closest_vowel(string word)\nnot null\n{\n string vowels = \"aeiouAEIOU\";\n string result = \"\";\n int i = word.length - 1;\n while (i >= 0)\n {\n if (vowels.index(word[i]) != -1)\n {\n result = word[i];\n break;\n }\n i--;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given an array of two strings, both strings consist of open\nparentheses '(' or close parentheses ')' only.\nYour job is to check if it is possible to concatenate the two strings in\nsome order, that the resulting string will be good.\nA string S is considered to be good if and only if all parentheses in S\nare balanced. For example: the string '(())()' is good, while the string\n'())' is not.\nReturn 'Yes' if there's a way to make a good string, and return 'No' otherwise.\nExamples:\n>>> match_parens([\"()(\", \")\"])\n\"Yes\"\n>>> match_parens([\")\", \")\"])\n\"No\"\n*/\nstring match_parens(string[] lst)\n{\n int open = 0;\n int close = 0;\n foreach (char c; lst[0])\n {\n if (c == '(')\n {\n open++;\n }\n else\n {\n close++;\n }\n }\n foreach (char c; lst[1])\n {\n if (c == '(')\n {\n open++;\n }\n else\n {\n close++;\n }\n }\n if (open == close)\n {\n return \"Yes\";\n }\n else\n {\n return \"No\";\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Input are two strings a and b consisting only of 1s and 0s.\nPerform binary XOR on these inputs and return result also as a string.\n>>> string_xor(\"010\", \"110\")\n\"100\"\n*/\nstring string_xor(string a, string b)\n{\n string result = \"\";\n for (int i = 0; i < a.length; i++)\n {\n int x = a[i] - '0';\n int y = b[i] - '0';\n int z = x ^ y;\n result += z.toChar;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array arr of integers and a positive integer k, return a sorted array \nof length k with the maximum k numbers in arr.\nExample 1:\n>>> maximum([-3L, -4L, 5L], 3L)\n[-4L, -3L, 5L]\nExample 2:\n>>> maximum([4L, -4L, 4L], 2L)\n[4L, 4L]\nExample 3:\n>>> maximum([-3L, 2L, 1L, 2L, -1L, -2L, 1L], 1L)\n[2L]\nNote:\n 1. The length of the array will be in the range of [1, 1000].\n 2. The elements in the array will be in the range of [-1000, 1000].\n 3. 0 <= k <= len(arr)\n*/\nlong[] maximum(long[] arr, long k)\n{\n long[] result = new long[k];\n long[] temp = new long[arr.length];\n for(long i = 0; i < arr.length; i++)\n {\n temp[i] = arr[i];\n }\n for(long i = 0; i < k; i++)\n {\n long max = temp[0];\n long index = 0;\n for(long j = 1; j < temp.length; j++)\n {\n if(temp[j] > max)\n {\n max = temp[j];\n index = j;\n }\n }\n result[i] = max;\n temp[index] = long.MinValue;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a non-empty array of integers, return the sum of all of the odd elements that are in even positions.\nExamples\n>>> solution([5L, 8L, 7L, 1L])\n12L\n>>> solution([3L, 3L, 3L, 3L, 3L])\n9L\n>>> solution([30L, 13L, 24L, 321L])\n0L\n*/\nlong solution(long[] lst)\n{\n long sum = 0L;\n for (int i = 0; i < lst.length; i += 2) {\n if (lst[i] % 2 != 0) {\n sum += lst[i];\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a non-empty array of integers arr and an integer k, return\nthe sum of the elements with at most two digits from the first k elements of arr.\nExample:\n>>> add_elements([111L, 21L, 3L, 4000L, 5L, 6L, 7L, 8L, 9L], 4L)\n24L\nConstraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\n*/\nlong add_elements(long[] arr, long k)\n{\n long sum = 0;\n foreach (i; 0 .. k)\n {\n if (arr[i] < 100)\n {\n sum += arr[i];\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer n, return a sorted array that has the odd numbers in collatz sequence.\nThe Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\nas follows: start with any positive integer n. Then each term is obtained from the \nprevious term as follows: if the previous term is even, the next term is one half of \nthe previous term. If the previous term is odd, the next term is 3 times the previous\nterm plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\nNote: \n 1. Collatz(1) is [1].\n 2. returned array sorted in increasing order.\nFor example:\nget_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n>>> get_odd_collatz(5L)\n[1L, 5L]\n*/\nlong[] get_odd_collatz(long n)\nnot null\n{\n long[] result = new long[0];\n while (n != 1)\n {\n if (n % 2 == 1)\n {\n result ~= n;\n }\n if (n % 2 == 0)\n {\n n = n / 2;\n }\n else\n {\n n = 3 * n + 1;\n }\n }\n result ~= 1;\n return result.sort();\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou have to write a function which validates a given date string and\nreturns true if the date is valid otherwise false.\nThe date is valid if all of the following rules are satisfied:\n1. The date string is not empty.\n2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n3. The months should not be less than 1 or higher than 12.\n4. The date should be in the format: mm-dd-yyyy\n>>> valid_date(\"03-11-2000\")\ntrue\n>>> valid_date(\"15-01-2012\")\nfalse\n>>> valid_date(\"04-0-2040\")\nfalse\n>>> valid_date(\"06-04-2020\")\ntrue\n>>> valid_date(\"06/04/2020\")\nfalse\n*/\nbool valid_date(string date)\n{\n if (date.empty())\n return false;"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array of numbers, return whether or not they are sorted\nin ascending order. If array has more than 1 duplicate of the same\nnumber, return false. Assume no negative numbers and only integers.\nExamples\n>>> is_sorted([5L])\ntrue\n>>> is_sorted([1L, 2L, 3L, 4L, 5L])\ntrue\n>>> is_sorted([1L, 3L, 2L, 4L, 5L])\nfalse\n>>> is_sorted([1L, 2L, 3L, 4L, 5L, 6L])\ntrue\n>>> is_sorted([1L, 2L, 3L, 4L, 5L, 6L, 7L])\ntrue\n>>> is_sorted([1L, 3L, 2L, 4L, 5L, 6L, 7L])\nfalse\n>>> is_sorted([1L, 2L, 2L, 3L, 3L, 4L])\ntrue\n>>> is_sorted([1L, 2L, 2L, 2L, 3L, 4L])\nfalse\n*/\nbool is_sorted(long[] lst)\n{\n foreach (i, e; lst)\n {\n if (i > 0 && e <= lst[i-1])\n {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given two intervals,\nwhere each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\nThe given intervals are closed which means that the interval (start, end)\nincludes both start and end.\nFor each given interval, it is assumed that its start is less or equal its end.\nYour task is to determine whether the length of intersection of these two \nintervals is a prime number.\nExample, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\nwhich its length is 1, which not a prime number.\nIf the length of the intersection is a prime number, return \"YES\",\notherwise, return \"NO\".\nIf the two intervals don't intersect, return \"NO\".\n[input/output] samples:\n>>> intersection(tuple(1L, 2L), tuple(2L, 3L))\n\"NO\"\n>>> intersection(tuple(-1L, 1L), tuple(0L, 4L))\n\"NO\"\n>>> intersection(tuple(-3L, -1L), tuple(-5L, 5L))\n\"YES\"\n*/\nstring intersection(Tuple!(long, long) interval1, Tuple!(long, long) interval2)\n{\n long start1 = interval1[0];\n long end1 = interval1[1];\n long start2 = interval2[0];\n long end2 = interval2[1];"], ["import std.math;\nimport std.typecons;\n/*\nYou are given an array arr of integers and you need to return\nsum of magnitudes of integers multiplied by product of all signs\nof each number in the array, represented by 1, -1 or 0.\nNote: return null for empty arr.\nExample:\n>>> prod_signs([1L, 2L, 2L, -4L])\n9L\n>>> prod_signs([0L, 1L])\n0L\n>>> prod_signs([])\nNone\n*/\nNullable!(long) prod_signs(long[] arr)\n{\n if (arr.length == 0)\n {\n return null;\n }\n long sum = 0;\n long product = 1;\n foreach (long num; arr)\n {\n sum += abs(num);\n product *= num.sign;\n }\n return sum * product;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a grid with N rows and N columns (N >= 2) and a positive integer k, \neach cell of the grid contains a value. Every integer in the range [1, N * N]\ninclusive appears exactly once on the cells of the grid.\nYou have to find the minimum path of length k in the grid. You can start\nfrom any cell, and in each step you can move to any of the neighbor cells,\nin other words, you can go to cells which share an edge with you current\ncell.\nPlease note that a path of length k means visiting exactly k cells (not\nnecessarily distinct).\nYou CANNOT go off the grid.\nA path A (of length k) is considered less than a path B (of length k) if\nafter making the ordered arrays of the values on the cells that A and B go\nthrough (let's call them lst_A and lst_B), lst_A is lexicographically less\nthan lst_B, in other words, there exist an integer index i (1 <= i <= k)\nsuch that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\nlst_A[j] = lst_B[j].\nIt is guaranteed that the answer is unique.\nReturn an ordered array of the values on the cells that the minimum path go through.\nExamples: \n>>> minPath([[1L, 2L, 3L], [4L, 5L, 6L], [7L, 8L, 9L]], 3L)\n[1L, 2L, 1L]\n>>> minPath([[5L, 9L, 3L], [4L, 1L, 6L], [7L, 8L, 2L]], 1L)\n[1L]\n*/\nlong[] minPath(long[][] grid, long k)\n{\n long n = grid.length;\n long[][] dp = new long[n][n];\n long[][] prev = new long[n][n];\n long[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};"], ["import std.math;\nimport std.typecons;\n/*\n Out of array of strings, return the longest one. Return the first one in case of multiple\nstrings of the same length. Return null in case the input array is empty.\n>>> longest([])\nNone\n>>> longest([\"a\", \"b\", \"c\"])\n\"a\"\n>>> longest([\"a\", \"bb\", \"ccc\"])\n\"ccc\"\n*/\nNullable!(string) longest(string[] strings)\n{\n if (strings.length == 0)\n {\n return null;\n }\n else\n {\n int maxLength = 0;\n string longestString = \"\";\n foreach (string s; strings)\n {\n if (s.length > maxLength)\n {\n maxLength = s.length;\n longestString = s;\n }\n }\n return longestString;\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nEveryone knows Fibonacci sequence, it was studied deeply by mathematicians in \nthe last couple centuries. However, what people don't know is Tribonacci sequence.\nTribonacci sequence is defined by the recurrence:\ntri(1) = 3\ntri(n) = 1 + n / 2, if n is even.\ntri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\nFor example:\ntri(2) = 1 + (2 / 2) = 2\ntri(4) = 3\ntri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \nYou are given a non-negative integer number n, you have to a return an array of the \nfirst n + 1 numbers of the Tribonacci sequence.\nExamples:\n>>> tri(3L)\n[1L, 3L, 2L, 8L]\n*/\nlong[] tri(long n)\n{\n long[] result = new long[n+1];\n result[0] = 1;\n result[1] = 3;\n for(long i = 2; i <= n; i++)\n {\n if(i % 2 == 0)\n {\n result[i] = 1 + i / 2;\n }\n else\n {\n result[i] = result[i-1] + result[i-2] + result[i+1];\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer n, return the product of the odd digits.\nReturn 0 if all digits are even.\nFor example:\n>>> digits(1L)\n1L\n>>> digits(4L)\n0L\n>>> digits(235L)\n15L\n*/\nlong digits(long n)\n{\n long product = 1L;\n while (n > 0) {\n long digit = n % 10;\n if (digit % 2 != 0) {\n product *= digit;\n }\n n /= 10;\n }\n return product;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function that takes a string as input which contains only square brackets.\nThe function should return true if and only if there is a valid subsequence of brackets \nwhere at least one bracket in the subsequence is nested.\n>>> is_nested(\"[[]]\")\ntrue\n>>> is_nested(\"[]]]]]]][[[[[]\")\nfalse\n>>> is_nested(\"[][]\")\nfalse\n>>> is_nested(\"[]\")\nfalse\n>>> is_nested(\"[[][]]\")\ntrue\n>>> is_nested(\"[[]][[\")\ntrue\n*/\nbool is_nested(string string)\n{\n int count = 0;\n foreach (char c; string)\n {\n if (c == '[')\n {\n count++;\n }\n else if (c == ']')\n {\n count--;\n }\n if (count < 0)\n {\n return true;\n }\n }\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given an array of numbers.\nYou need to return the sum of squared numbers in the given array,\nround each element in the array to the upper int(Ceiling) first.\nExamples:\n>>> lst([1.0, 2.0, 3.0])\n14L\n>>> lst([1.0, 4.0, 9.0])\n98L\n>>> lst([1.0, 3.0, 5.0, 7.0])\n84L\n>>> lst([1.4, 4.2, 0.0])\n29L\n>>> lst([-2.4, 1.0, 1.0])\n6L\n*/\nlong sum_squares(float[] lst)\n{\n long sum = 0;\n foreach (x; lst) {\n sum += pow(ceil(x), 2);\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function that returns true if the last character\nof a given string is an alphabetical character and is not\na part of a word, and false otherwise.\nNote: \"word\" is a group of characters separated by space.\nExamples:\n>>> check_if_last_char_is_a_letter(\"apple pie\")\nfalse\n>>> check_if_last_char_is_a_letter(\"apple pi e\")\ntrue\n>>> check_if_last_char_is_a_letter(\"apple pi e \")\nfalse\n>>> check_if_last_char_is_a_letter(\"\")\nfalse\n*/\nbool check_if_last_char_is_a_letter(string txt)\n{\n if(txt.length == 0)\n return false;\n else if(txt[$-1] != ' ' && txt[$-1].isAlpha)\n return true;\n else\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function which returns the largest index of an element which\nis not greater than or equal to the element immediately preceding it. If\nno such element exists then return -1. The given array will not contain\nduplicate values.\nExamples:\n>>> can_arrange([1L, 2L, 4L, 3L, 5L])\n3L\n>>> can_arrange([1L, 2L, 3L])\n-1L\n*/\nlong can_arrange(long[] arr)\n{\n long maxIndex = -1;\n for(long i = 1; i < arr.length; i++)\n {\n if(arr[i] < arr[i-1])\n {\n maxIndex = i;\n }\n }\n return maxIndex;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function that returns a tuple (a, b), where 'a' is\nthe largest of negative integers, and 'b' is the smallest\nof positive integers in an array.\nIf there is no negative or positive integers, return them as null.\nExamples:\n>>> largest_smallest_integers([2L, 4L, 1L, 3L, 5L, 7L])\ntuple(None, 1L)\n>>> largest_smallest_integers([])\ntuple(None, None)\n>>> largest_smallest_integers([0L])\ntuple(None, None)\n*/\nTuple!(Nullable!(long), Nullable!(long)) largest_smallest_integers(long[] lst)\n{\n Nullable!(long) largestNegative = null;\n Nullable!(long) smallestPositive = null;"], ["import std.math;\nimport std.typecons;\n/*\nEvaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\nExample\n>>> is_equal_to_sum_even(4L)\nfalse\n>>> is_equal_to_sum_even(6L)\nfalse\n>>> is_equal_to_sum_even(8L)\ntrue\n*/\nbool is_equal_to_sum_even(long n)\n{\n if (n % 4 != 0) {\n return false;\n }\n long x = n / 4;\n return x % 2 == 0;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nThe Brazilian factorial is defined as:\nbrazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\nwhere n > 0\nFor example:\n>>> special_factorial(4L)\n288L\nThe function will receive an integer as input and should return the special\nfactorial of this integer.\n*/\nlong special_factorial(long n)\n{\n long result = 1L;\n for (long i = n; i > 0; i--) {\n result *= factorial(i);\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Return a greatest common divisor of two integers a and b\n>>> greatest_common_divisor(3L, 5L)\n1L\n>>> greatest_common_divisor(25L, 15L)\n5L\n*/\nlong greatest_common_divisor(long a, long b)\n{\n return a.gcd(b);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a string text, replace all spaces in it with underscores, \nand if a string has more than 2 consecutive spaces, \nthen replace all consecutive spaces with - \n>>> fix_spaces(\" Example\")\n\"Example\"\n>>> fix_spaces(\" Example 1\")\n\"Example_1\"\n>>> fix_spaces(\" Example 2\")\n\"_Example_2\"\n>>> fix_spaces(\" Example 3\")\n\"_Example-3\"\n*/\nstring fix_spaces(string text)\n{\n string result = \"\";\n int count = 0;\n foreach (char c; text)\n {\n if (c == ' ')\n {\n count++;\n if (count == 2)\n {\n result ~= '-';\n }\n else\n {\n result ~= '_';\n }\n }\n else\n {\n count = 0;\n result ~= c;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function which takes a string representing a file's name, and returns\n'Yes' if the the file's name is valid, and returns 'No' otherwise.\nA file's name is considered to be valid if and only if all the following conditions \nare met:\n- There should not be more than three digits ('0'-'9') in the file's name.\n- The file's name contains exactly one dot '.'\n- The substring before the dot should not be empty, and it starts with a letter from \nthe latin alphapet ('a'-'z' and 'A'-'Z').\n- The substring after the dot should be one of these: ['txt', 'exe', 'dll']\nExamples:\n>>> file_name_check(\"example.txt\")\n\"Yes\"\n>>> file_name_check(\"1example.dll\")\n\"No\"\n*/\nstring file_name_check(string file_name)\n{\n int digit_count = 0;\n int dot_count = 0;\n int substring_count = 0;\n bool valid_substring = false;"], ["import std.math;\nimport std.typecons;\n/*\n\"\nThis function will take an array of integers. For all entries in the array, the function shall square the integer entry if its index is a \nmultiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \nchange the entries in the array whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \nExamples:\n>>> lst\n[1L, 2L, 3L]\n>>> lst\n[]\n>>> lst\n[-1L, -5L, 2L, -1L, -5L]\n*/\nlong sum_squares(long[] lst)\n{\n long sum = 0;\n foreach (i, e; lst)\n {\n if (i % 3 == 0)\n {\n sum += e * e;\n }\n else if (i % 4 == 0)\n {\n sum += e * e * e;\n }\n else\n {\n sum += e;\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a string representing a sentence,\nthe sentence contains some words separated by a space,\nand you have to return a string that contains the words from the original sentence,\nwhose lengths are prime numbers,\nthe order of the words in the new string should be the same as the original one.\nExample 1:\n>>> words_in_sentence(\"This is a test\")\n\"is\"\nExample 2:\n>>> words_in_sentence(\"lets go for swimming\")\n\"go for\"\nConstraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n*/\nstring words_in_sentence(string sentence)\n{\n string[] words = sentence.split(\" \");\n string result = \"\";\n foreach (word; words)\n {\n if (isPrime(word.length))\n {\n result ~= word;\n }\n }\n return result;\n}"], ["import std.math;\nimport std.typecons;\n/*\nYour task is to implement a function that will simplify the expression\nx * n. The function returns true if x * n evaluates to a whole number and false\notherwise. Both x and n, are string representation of a fraction, and have the following format,\n/ where both numerator and denominator are positive whole numbers.\nYou can assume that x, and n are valid fractions, and do not have zero as denominator.\n>>> simplify(\"1/5\", \"5/1\")\ntrue\n>>> simplify(\"1/6\", \"2/1\")\nfalse\n>>> simplify(\"7/10\", \"10/2\")\nfalse\n*/\nbool simplify(string x, string n)\n{\n int x_num, x_den, n_num, n_den;\n sscanf(x.toString(), \"%d/%d\", &x_num, &x_den);\n sscanf(n.toString(), \"%d/%d\", &n_num, &n_den);\n int result_num = x_num * n_num;\n int result_den = x_den * n_den;\n int gcd_num = gcd(result_num, result_den);\n result_num /= gcd_num;\n result_den /= gcd_num;\n return result_den == 1 && result_num % result_den == 0;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function which sorts the given array of integers\nin ascending order according to the sum of their digits.\nNote: if there are several items with similar sum of their digits,\norder them based on their index in original array.\nFor example:\n>>> order_by_points([1L, 11L, -1L, -11L, -12L])\n[-1L, -11L, 1L, -12L, 11L]\n>>> order_by_points([])\n[]\n*/\nlong[] order_by_points(long[] nums)\n{\n long[][] nums_with_sums = new long[nums.length][2];\n for (int i = 0; i < nums.length; i++)\n {\n long sum = 0;\n long num = nums[i];\n while (num != 0)\n {\n sum += num % 10;\n num /= 10;\n }\n nums_with_sums[i][0] = sum;\n nums_with_sums[i][1] = i;\n }\n nums_with_sums.sort();\n long[] result = new long[nums.length];\n for (int i = 0; i < nums.length; i++)\n {\n result[i] = nums[nums_with_sums[i][1]];\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that takes an array of numbers as input and returns \nthe number of elements in the array that are greater than 10 and both \nfirst and last digits of a number are odd (1, 3, 5, 7, 9).\nFor example:\n>>> specialFilter([15L, -73L, 14L, -15L])\n1L\n>>> specialFilter([33L, -2L, -3L, 45L, 21L, 109L])\n2L\n*/\nlong specialFilter(long[] nums)\n{\n long count = 0;\n foreach (num; nums) {\n if (num > 10 && abs(num) % 2 == 1 && abs(num % 10) % 2 == 1) {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n You are given a positive integer n. You have to create an integer array a of length n.\nFor each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\nReturn the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n Example :\n >>> get_max_triples(5L)\n 1L\nExplanation: \na = [1, 3, 7, 13, 21]\nThe only valid triple is (1, 7, 13).\n*/\nlong get_max_triples(long n)\n{\n long[] a = new long[n];\n long count = 0;\n for(long i = 1; i <= n; i++)\n {\n a[i-1] = i * i - i + 1;\n }\n for(long i = 0; i < n-2; i++)\n {\n for(long j = i+1; j < n-1; j++)\n {\n for(long k = j+1; k < n; k++)\n {\n if((a[i] + a[j] + a[k]) % 3 == 0)\n {\n count++;\n }\n }\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that accepts an array of strings as a parameter,\ndeletes the strings that have odd lengths from it,\nand returns the resulted array with a sorted order,\nThe array is always an array of strings and never an array of numbers,\nand it may contain duplicates.\nThe order of the array should be ascending by length of each word, and you\nshould return the array sorted by that rule.\nIf two words have the same length, sort the array alphabetically.\nThe function should return an array of strings in sorted order.\nYou may assume that all words will have the same length.\nFor example:\n>>> list_sort([\"aa\", \"a\", \"aaa\"])\n[\"aa\"]\n>>> list_sort([\"ab\", \"a\", \"aaa\", \"cd\"])\n[\"ab\", \"cd\"]\n*/\nstring[] sorted_list_sum(string[] lst)\n{\n string[] result;\n int i, j, len;\n len = lst.length;\n result = new string[len];\n j = 0;\n for(i = 0; i < len; i++)\n {\n if(lst[i].length % 2 == 0)\n {\n result[j] = lst[i];\n j++;\n }\n }\n result = result[0..j-1];\n result.sort();\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Return array of all prefixes from shortest to longest of the input string\n>>> all_prefixes(\"abc\")\n[\"a\", \"ab\", \"abc\"]\n*/\nstring[] all_prefixes(string string)\n{\n string[] prefixes;\n for (int i = 1; i <= string.length; i++)\n {\n prefixes ~= string[0..i];\n }\n return prefixes;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nA simple program which should return the value of x if n is \na prime number and should return the value of y otherwise.\nExamples:\n>>> x_or_y(7L, 34L, 12L)\n34L\n>>> x_or_y(15L, 8L, 5L)\n5L\n*/\nlong x_or_y(long n, long x, long y)\n{\n if (isPrime(n)) {\n return x;\n } else {\n return y;\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array of numbers, return the sum of squares of the numbers\nin the array that are odd. Ignore numbers that are negative or not integers.\n>>> double_the_difference([1L, 3L, 2L, 0L])\n10L\n>>> double_the_difference([-1L, -2L, 0L])\n0L\n>>> double_the_difference([9L, -2L])\n81L\n>>> double_the_difference([0L])\n0L\nIf the input array is empty, return 0.\n*/\nlong double_the_difference(float[] lst)\nnot null\n{\n long sum = 0L;\n foreach (num; lst)\n {\n if (num.isInteger() && num.toInt() % 2 != 0)\n {\n sum += pow(num.toInt(), 2);\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nI think we all remember that feeling when the result of some long-awaited\nevent is finally known. The feelings and thoughts you have at that moment are\ndefinitely worth noting down and comparing.\nYour task is to determine if a person correctly guessed the results of a number of matches.\nYou are given two arrays of scores and guesses of equal length, where each index shows a match. \nReturn an array of the same length denoting how far off each guess was. If they have guessed correctly,\nthe value is 0, and if not, the value is the absolute difference between the guess and the score.\nexample:\n>>> compare([1L, 2L, 3L, 4L, 5L, 1L], [1L, 2L, 3L, 4L, 2L, -2L])\n[0L, 0L, 0L, 0L, 3L, 3L]\n>>> compare([0L, 5L, 0L, 0L, 0L, 4L], [4L, 1L, 1L, 0L, 0L, -2L])\n[4L, 4L, 1L, 0L, 0L, 6L]\n*/\nlong[] compare(long[] game, long[] guess)\n{\n long[] diff = new long[game.length];\n for(int i = 0; i < game.length; i++)\n {\n diff[i] = abs(game[i] - guess[i]);\n }\n return diff;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou will be given the name of a class (a string) and an array of extensions.\nThe extensions are to be used to load additional classes to the class. The\nstrength of the extension is as follows: Let CAP be the number of the uppercase\nletters in the extension's name, and let SM be the number of lowercase letters \nin the extension's name, the strength is given by the fraction CAP - SM. \nYou should find the strongest extension and return a string in this \nformat: ClassName.StrongestExtensionName.\nIf there are two or more extensions with the same strength, you should\nchoose the one that comes first in the array.\nFor example, if you are given \"Slices\" as the class and an array of the\nextensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\nreturn 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n(its strength is -1).\nExample:\n>>> Strongest_Extension(\"my_class\", [\"AA\", \"Be\", \"CC\"])\n\"my_class.AA\"\n*/\nstring Strongest_Extension(string class_name, string[] extensions)\n{\n string strongest_extension = \"\";\n double strongest_strength = -1.0;"], ["import std.math;\nimport std.typecons;\n/*\nYou are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n>>> cycpattern_check(\"abcd\", \"abd\")\nfalse\n>>> cycpattern_check(\"hello\", \"ell\")\ntrue\n>>> cycpattern_check(\"whassup\", \"psus\")\nfalse\n>>> cycpattern_check(\"abab\", \"baa\")\ntrue\n>>> cycpattern_check(\"efef\", \"eeff\")\nfalse\n>>> cycpattern_check(\"himenss\", \"simen\")\ntrue\n*/\nbool cycpattern_check(string a, string b)\n{\n int n = a.length();\n int m = b.length();\n if (m > n)\n return false;\n string temp = b + b;\n for (int i = 0; i < n; i++)\n {\n if (temp.substr(i, m) == b)\n return true;\n }\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an integer. return a tuple that has the number of even and odd digits respectively.\nExample:\n >>> even_odd_count(-12L)\n tuple(1L, 1L)\n >>> even_odd_count(123L)\n tuple(1L, 2L)\n*/\nTuple!(long, long) even_odd_count(long num)\n{\n long evenCount = 0L;\n long oddCount = 0L;"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer, obtain its roman numeral equivalent as a string,\nand return it in lowercase.\nRestrictions: 1 <= num <= 1000\nExamples:\n>>> int_to_mini_roman(19L)\n\"xix\"\n>>> int_to_mini_roman(152L)\n\"clii\"\n>>> int_to_mini_roman(426L)\n\"cdxxvi\"\n*/\nstring int_to_mini_roman(long number)\n{\n string roman = \"\";\n while (number > 0)\n {\n if (number >= 100)\n {\n roman ~= \"c\";\n number -= 100;\n }\n else if (number >= 90)\n {\n roman ~= \"xc\";\n number -= 90;\n }\n else if (number >= 50)\n {\n roman ~= \"l\";\n number -= 50;\n }\n else if (number >= 40)\n {\n roman ~= \"xl\";\n number -= 40;\n }\n else if (number >= 10)\n {\n roman ~= \"x\";\n number -= 10;\n }\n else if (number >= 9)\n {\n roman ~= \"ix\";\n number -= 9;\n }\n else if (number >= 5)\n {\n roman ~= \"v\";\n number -= 5;\n }\n else if (number >= 4)\n {\n roman ~= \"iv\";\n number -= 4;\n }\n else\n {\n roman ~= \"i\";\n number -= 1;\n }\n }\n return roman.toLower();\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven the lengths of the three sides of a triangle. Return true if the three\nsides form a right-angled triangle, false otherwise.\nA right-angled triangle is a triangle in which one angle is right angle or \n90 degree.\nExample:\n>>> right_angle_triangle(3L, 4L, 5L)\ntrue\n>>> right_angle_triangle(1L, 2L, 3L)\nfalse\n*/\nbool right_angle_triangle(long a, long b, long c)\n{\n long[] sides = [a, b, c].sort();\n return pow(sides[0], 2) + pow(sides[1], 2) == pow(sides[2], 2);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that accepts an array of strings.\nThe array contains different words. Return the word with maximum number\nof unique characters. If multiple strings have maximum number of unique\ncharacters, return the one which comes first in lexicographical order.\n>>> find_max([\"name\", \"of\", \"string\"])\n\"string\"\n>>> find_max([\"name\", \"enam\", \"game\"])\n\"enam\"\n>>> find_max([\"aaaaaaa\", \"bb\", \"cc\"])\n\"aaaaaaa\"\n*/\nstring find_max(string[] words)\n{\n string max_word = \"\";\n int max_unique = 0;\n foreach (word; words)\n {\n int unique_chars = word.toSet().length;\n if (unique_chars > max_unique || (unique_chars == max_unique && word < max_word))\n {\n max_word = word;\n max_unique = unique_chars;\n }\n }\n return max_word;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou're a hungry rabbit, and you already have eaten a certain number of carrots,\nbut now you need to eat more carrots to complete the day's meals.\nyou should return an array of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\nif there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\nExample:\n>>> eat(5L, 6L, 10L)\n[11L, 4L]\n>>> eat(4L, 8L, 9L)\n[12L, 1L]\n>>> eat(1L, 10L, 10L)\n[11L, 0L]\n>>> eat(2L, 11L, 5L)\n[7L, 0L]\nVariables:\n@number : integer\n the number of carrots that you have eaten.\n@need : integer\n the number of carrots that you need to eat.\n@remaining : integer\n the number of remaining carrots thet exist in stock\nConstrain:\n* 0 <= number <= 1000\n* 0 <= need <= 1000\n* 0 <= remaining <= 1000\nHave fun :)\n*/\nlong[] eat(long number, long need, long remaining)\n{\n long[] result = new long[2];\n long total = number + need;\n result[0] = total;\n result[1] = remaining - need;\n if (result[1] < 0)\n {\n result[1] = 0;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n>>> string_sequence(0L)\n\"0\"\n>>> string_sequence(5L)\n\"0 1 2 3 4 5\"\n*/\nstring string_sequence(long n)\n{\n string result = \"\";\n foreach (i; 0L..=n)\n {\n result ~= i.string;\n if (i != n)\n {\n result ~= \" \";\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven two arrays operator, and operand. The first array has basic algebra operations, and \nthe second array is an array of integers. Use the two given arrays to build the algebric \nexpression and return the evaluation of this expression.\nThe basic algebra operations:\nAddition ( + ) \nSubtraction ( - ) \nMultiplication ( * ) \nFloor division ( // ) \nExponentiation ( ** ) \nExample:\noperator['+', '*', '-']\narray = [2, 3, 4, 5]\nresult = 2 + 3 * 4 - 5\n=> result = 9\nNote:\n The length of operator array is equal to the length of operand array minus one.\n Operand is an array of of non-negative integers.\n Operator array has at least one operator, and operand array has at least two operands.\n*/\nlong do_algebra(string[] operator, long[] operand)\nnotnull operand\n{\n long result = operand[0];\n for (int i = 1; i < operand.length; i++)\n {\n switch (operator[i-1])\n {\n case \"+\":\n result += operand[i];\n break;\n case \"-\":\n result -= operand[i];\n break;\n case \"*\":\n result *= operand[i];\n break;\n case \"//\":\n result = result / operand[i];\n break;\n case \"**\":\n result = pow(result, operand[i]);\n break;\n default:\n break;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a string s.\nif s[i] is a letter, reverse its case from lower to upper or vise versa, \notherwise keep it as it is.\nIf the string contains no letters, reverse the string.\nThe function should return the resulted string.\nExamples\n>>> solve(\"1234\")\n\"4321\"\n>>> solve(\"ab\")\n\"AB\"\n>>> solve(\"#a@C\")\n\"#A@c\"\n*/\nstring solve(string s)\n{\n string result = \"\";\n bool hasLetters = false;\n for (int i = 0; i < s.length(); i++)\n {\n if (isalpha(s[i]))\n {\n hasLetters = true;\n if (isupper(s[i]))\n {\n result += tolower(s[i]);\n }\n else\n {\n result += toupper(s[i]);\n }\n }\n else\n {\n result += s[i];\n }\n }\n if (!hasLetters)\n {\n result = s.reverse();\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a string 'text', return its md5 hash equivalent string.\nIf 'text' is an empty string, return null.\n>>> string_to_md5(\"Hello world\")\n\"3e25960a79dbc69b674cd4ec67a72c62\"\n*/\nNullable!(string) string_to_md5(string text)\n{\n if (text.empty)\n {\n return null;\n }\n else\n {\n return toHex(md5(text.dup));\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven two positive integers a and b, return the even digits between a\nand b, in ascending order.\nFor example:\n>>> generate_integers(2L, 8L)\n[2L, 4L, 6L, 8L]\n>>> generate_integers(8L, 2L)\n[2L, 4L, 6L, 8L]\n>>> generate_integers(10L, 14L)\n[]\n*/\nlong[] generate_integers(long a, long b)\n{\n long[] result;\n long start, end;\n if (a < b) {\n start = a;\n end = b;\n } else {\n start = b;\n end = a;\n }\n long[] temp = new long[end - start + 1];\n long count = 0;\n for (long i = start; i <= end; i++) {\n if (i % 2 == 0) {\n temp[count] = i;\n count++;\n }\n }\n result = new long[count];\n for (long i = 0; i < count; i++) {\n result[i] = temp[i];\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Given a string, find out how many distinct characters (regardless of case) does it consist of\n>>> count_distinct_characters(\"xyzXYZ\")\n3L\n>>> count_distinct_characters(\"Jerry\")\n4L\n*/\nlong count_distinct_characters(string string)\n{\n return string.toLower().distinct.length;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Input to this function is a string representing musical notes in a special ASCII format.\nYour task is to parse this string and return array of integers corresponding to how many beats does each\nnot last.\nHere is a legend:\n'o' - whole note, lasts four beats\n'o|' - half note, lasts two beats\n'.|' - quater note, lasts one beat\n>>> parse_music(\"o o| .| o| o| .| .| .| .| o o\")\n[4L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 4L, 4L]\n*/\nlong[] parse_music(string music_string)\n{\n long[] beats;\n int i = 0;\n foreach (char c; music_string)\n {\n if (c == 'o')\n {\n beats[i++] = 4;\n }\n else if (c == '|')\n {\n if (music_string[$-1] == 'o')\n {\n beats[i++] = 2;\n }\n else if (music_string[$-1] == '.')\n {\n beats[i++] = 1;\n }\n }\n }\n return beats;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Find how many times a given substring can be found in the original string. Count overlaping cases.\n>>> how_many_times(\"\", \"a\")\n0L\n>>> how_many_times(\"aaa\", \"a\")\n3L\n>>> how_many_times(\"aaaa\", \"aa\")\n3L\n*/\nlong how_many_times(string string, string substring)\n{\n long count = 0;\n int index = 0;\n while ((index = string.find(substring, index)) != -1)\n {\n count++;\n index += substring.length();\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Input is a space-delimited string of numberals from 'zero' to 'nine'.\nValid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\nReturn the string with numbers sorted from smallest to largest\n>>> sort_numbers(\"three one five\")\n\"one three five\"\n*/\nstring sort_numbers(string numbers)\n{\n string[] nums = numbers.split(\" \");\n int[] numValues = new int[nums.length];\n string[] numStrings = new string[] { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" };\n for (int i = 0; i < nums.length; i++)\n {\n numValues[i] = numStrings.indexOf(nums[i]);\n }\n numValues.sort();\n string[] sortedNums = new string[nums.length];\n for (int i = 0; i < nums.length; i++)\n {\n sortedNums[i] = numStrings[numValues[i]];\n }\n return sortedNums.join(\" \");\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\nseparate those group into separate strings and return the array of those.\nSeparate groups are balanced (each open brace is properly closed) and not nested within each other\nIgnore any spaces in the input string.\n>>> separate_paren_groups(\"( ) (( )) (( )( ))\")\n[\"()\", \"(())\", \"(()())\"]\n*/\nstring[] separate_paren_groups(string paren_string)\n{\n string[] result;\n int start = 0;\n int end = 0;\n int count = 0;\n int index = 0;"], ["import std.math;\nimport std.typecons;\n/*\n From a supplied array of numbers (of length at least two) select and return two that are the closest to each\nother and return them in order (smaller number, larger number).\n>>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\ntuple(2.0, 2.2)\n>>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\ntuple(2.0, 2.0)\n*/\nTuple!(float, float) find_closest_elements(float[] numbers)\n{\n float min_diff = abs(numbers[0] - numbers[1]);\n float closest1 = numbers[0];\n float closest2 = numbers[1];"], ["import std.math;\nimport std.typecons;\n/*\n Given array of numbers (of at least two elements), apply a linear transform to that array,\nsuch that the smallest number will become 0 and the largest will become 1\n>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n[0.0, 0.25, 0.5, 0.75, 1.0]\n*/\nfloat[] rescale_to_unit(float[] numbers)\n{\n float min = numbers[0];\n float max = numbers[0];\n foreach (num; numbers)\n {\n if (num < min)\n {\n min = num;\n }\n if (num > max)\n {\n max = num;\n }\n }\n float[] rescaled = new float[numbers.length];\n foreach (i, num; numbers)\n {\n rescaled[i] = (num - min) / (max - min);\n }\n return rescaled;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Return length of given string\n>>> strlen(\"\")\n0L\n>>> strlen(\"abc\")\n3L\n*/\nlong strlen(string string)\n{\n return string.length;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n For a given number n, find the largest number that divides n evenly, smaller than n\n>>> largest_divisor(15L)\n5L\n*/\nlong largest_divisor(long n)\n{\n long largest = 1L;\n for (long i = 2L; i <= sqrt(n); i++) {\n if (n % i == 0) {\n largest = i;\n }\n }\n return largest;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Return array of prime factors of given integer in the order from smallest to largest.\nEach of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.\nInput number should be equal to the product of all factors\n>>> factorize(8L)\n[2L, 2L, 2L]\n>>> factorize(25L)\n[5L, 5L]\n>>> factorize(70L)\n[2L, 5L, 7L]\n*/\nlong[] factorize(long n)\n{\n long[] factors = [];\n long i = 2;\n while (i <= n)\n {\n if (n % i == 0)\n {\n factors ~= i;\n n /= i;\n }\n else\n {\n i++;\n }\n }\n return factors;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n From an array of integers, remove all elements that occur more than once.\nKeep order of elements left the same as in the input.\n>>> remove_duplicates([1L, 2L, 3L, 2L, 4L])\n[1L, 3L, 4L]\n*/\nlong[] remove_duplicates(long[] numbers)\n{\n long[] result = new long[0];\n foreach (long num in numbers)\n {\n if (!result.any(n => n == num))\n {\n result ~= num;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n>>> flip_case(\"Hello\")\n\"hELLO\"\n*/\nstring flip_case(string string)\n{\n string result = \"\";\n foreach (char c; string)\n {\n if (islower(c))\n {\n result ~= toUpper(c);\n }\n else if (isupper(c))\n {\n result ~= toLower(c);\n }\n else\n {\n result ~= c;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Concatenate array of strings into a single string\n>>> concatenate([])\n\"\"\n>>> concatenate([\"a\", \"b\", \"c\"])\n\"abc\"\n*/\nstring concatenate(string[] strings)\n{\n string result = \"\";\n foreach (string s; strings)\n {\n result ~= s;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Filter an input array of strings only for ones that start with a given prefix.\n>>> filter_by_prefix([], \"a\")\n[]\n>>> filter_by_prefix([\"abc\", \"bcd\", \"cde\", \"array\"], \"a\")\n[\"abc\", \"array\"]\n*/\nstring[] filter_by_prefix(string[] strings, string prefix)\n{\n string[] filtered = [];\n foreach (str; strings)\n {\n if (str.startsWith(prefix))\n {\n filtered ~= str;\n }\n }\n return filtered;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Given a positive floating point number, it can be decomposed into\nand integer part (largest integer smaller than given number) and decimals\n(leftover part always smaller than 1).\nReturn the decimal part of the number.\n>>> truncate_number(3.5)\n0.5\n*/\nfloat truncate_number(float number)\n{\n return number - floor(number);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn only positive numbers in the array.\n>>> get_positive([-1L, 2L, -4L, 5L, 6L])\n[2L, 5L, 6L]\n>>> get_positive([5L, 3L, -5L, 2L, -3L, 3L, 9L, 0L, 123L, 1L, -10L])\n[5L, 3L, 2L, 3L, 9L, 123L, 1L]\n*/\nlong[] get_positive(long[] l)\n{\n long[] result = new long[l.length];\n int count = 0;\n foreach (num; l)\n {\n if (num > 0)\n {\n result[count] = num;\n count++;\n }\n }\n return result[0..count];\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn true if a given number is prime, and false otherwise.\n>>> is_prime(6L)\nfalse\n>>> is_prime(101L)\ntrue\n>>> is_prime(11L)\ntrue\n>>> is_prime(13441L)\ntrue\n>>> is_prime(61L)\ntrue\n>>> is_prime(4L)\nfalse\n>>> is_prime(1L)\nfalse\n*/\nbool is_prime(long n)\n{\n if (n <= 1)\n return false;\n if (n <= 3)\n return true;\n if (n % 2 == 0 || n % 3 == 0)\n return false;\n for (long i = 5; i * i <= n; i += 6)\n {\n if (n % i == 0 || n % (i + 2) == 0)\n return false;\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nThis function takes an array l and returns an array l' such that\nl' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\nto the values of the corresponding indicies of l, but sorted.\n>>> sort_third([1L, 2L, 3L])\n[1L, 2L, 3L]\n>>> sort_third([5L, 6L, 3L, 4L, 8L, 9L, 2L])\n[2L, 6L, 3L, 4L, 8L, 9L, 5L]\n*/\nlong[] sort_third(long[] l)\n{\n long[] l_prime = new long[l.length];\n long[] third_values = new long[l.length / 3];\n int third_index = 0;"], ["import std.math;\nimport std.typecons;\n/*\nReturn sorted unique elements in an array\n>>> unique([5L, 3L, 5L, 2L, 3L, 3L, 9L, 0L, 123L])\n[0L, 2L, 3L, 5L, 9L, 123L]\n*/\nlong[] unique(long[] l)\n{\n auto sorted = l.sort();\n auto unique = sorted.filter(i => sorted.count(j => j == i) == 1);\n return unique.array;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn maximum element in the array.\n>>> max_element([1L, 2L, 3L])\n3L\n>>> max_element([5L, 3L, -5L, 2L, -3L, 3L, 9L, 0L, 123L, 1L, -10L])\n123L\n*/\nlong max_element(long[] l)\n{\n return l.max;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n>>> fizz_buzz(50L)\n0L\n>>> fizz_buzz(78L)\n2L\n>>> fizz_buzz(79L)\n3L\n*/\nlong fizz_buzz(long n)\n{\n long count = 0;\n for (long i = 1; i < n; i++) {\n if (i % 11 == 0 || i % 13 == 0) {\n string s = i.toString();\n foreach (char c; s) {\n if (c == '7') {\n count++;\n }\n }\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nThis function takes an array l and returns an array l' such that\nl' is identical to l in the odd indicies, while its values at the even indicies are equal\nto the values of the even indicies of l, but sorted.\n>>> sort_even([1L, 2L, 3L])\n[1L, 2L, 3L]\n>>> sort_even([5L, 6L, 3L, 4L])\n[3L, 6L, 5L, 4L]\n*/\nlong[] sort_even(long[] l)\n{\n long[] even_values = l[1::2];\n even_values.sort();\n long[] result = new long[l.length];\n for (int i = 0; i < l.length; i++)\n {\n if (i % 2 == 0)\n {\n result[i] = l[i];\n }\n else\n {\n result[i] = even_values[i / 2];\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nprime_fib returns n-th number that is a Fibonacci number and it's also prime.\n>>> prime_fib(1L)\n2L\n>>> prime_fib(2L)\n3L\n>>> prime_fib(3L)\n5L\n>>> prime_fib(4L)\n13L\n>>> prime_fib(5L)\n89L\n*/\nlong prime_fib(long n)\n{\n long count = 0;\n long fib = 0;\n long i = 0;\n while (count < n) {\n fib = fibonacci(i);\n if (isPrime(fib)) {\n count++;\n }\n i++;\n }\n return fib;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n You're given an array of deposit and withdrawal operations on a bank account that starts with\nzero balance. Your task is to detect if at any point the balance of account fallls below zero, and\nat that point function should return true. Otherwise it should return false.\n>>> below_zero([1L, 2L, 3L])\nfalse\n>>> below_zero([1L, 2L, -4L, 5L])\ntrue\n*/\nbool below_zero(long[] operations)\n{\n long balance = 0;\n foreach (op; operations) {\n balance += op;\n if (balance < 0) {\n return true;\n }\n }\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\ntriples_sum_to_zero takes an array of integers as an input.\nit returns true if there are three distinct elements in the array that\nsum to zero, and false otherwise.\n>>> triples_sum_to_zero([1L, 3L, 5L, 0L])\nfalse\n>>> triples_sum_to_zero([1L, 3L, -2L, 1L])\ntrue\n>>> triples_sum_to_zero([1L, 2L, 3L, 7L])\nfalse\n>>> triples_sum_to_zero([2L, 4L, -5L, 3L, 9L, 7L])\ntrue\n>>> triples_sum_to_zero([1L])\nfalse\n*/\nbool triples_sum_to_zero(long[] l)\nnot null\n{\n if (l.length < 3)\n return false;"], ["import std.math;\nimport std.typecons;\n/*\nImagine a road that's a perfectly straight infinitely long line.\nn cars are driving left to right; simultaneously, a different set of n cars\nare driving right to left. The two sets of cars start out being very far from\neach other. All cars move in the same speed. Two cars are said to collide\nwhen a car that's moving left to right hits a car that's moving right to left.\nHowever, the cars are infinitely sturdy and strong; as a result, they continue moving\nin their trajectory as if they did not collide.\nThis function outputs the number of such collisions.\n*/\nlong car_race_collision(long n)\n{\n return n * (n - 1) / 2;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn array with elements incremented by 1.\n>>> incr_list([1L, 2L, 3L])\n[2L, 3L, 4L]\n>>> incr_list([5L, 3L, 5L, 2L, 3L, 3L, 9L, 0L, 123L])\n[6L, 4L, 6L, 3L, 4L, 4L, 10L, 1L, 124L]\n*/\nlong[] incr_list(long[] l)\n{\n long[] result = new long[l.length];\n foreach (i, e; l)\n {\n result[i] = e + 1;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\npairs_sum_to_zero takes an array of integers as an input.\nit returns true if there are two distinct elements in the array that\nsum to zero, and false otherwise.\n>>> pairs_sum_to_zero([1L, 3L, 5L, 0L])\nfalse\n>>> pairs_sum_to_zero([1L, 3L, -2L, 1L])\nfalse\n>>> pairs_sum_to_zero([1L, 2L, 3L, 7L])\nfalse\n>>> pairs_sum_to_zero([2L, 4L, -5L, 3L, 5L, 7L])\ntrue\n>>> pairs_sum_to_zero([1L])\nfalse\n*/\nbool pairs_sum_to_zero(long[] l)\n{\n foreach (i, e; l) {\n foreach (j, f; l[i+1..$]) {\n if (e + f == 0) {\n return true;\n }\n }\n }\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nChange numerical base of input number x to base.\nreturn string representation after the conversion.\nbase numbers are less than 10.\n>>> change_base(8L, 3L)\n\"22\"\n>>> change_base(8L, 2L)\n\"1000\"\n>>> change_base(7L, 2L)\n\"111\"\n*/\nstring change_base(long x, long base)\n{\n string result = \"\";\n while (x > 0)\n {\n result = to_string(x % base) + result;\n x /= base;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven length of a side and high return area for a triangle.\n>>> triangle_area(5L, 3L)\n7.5\n*/\nfloat triangle_area(long a, long h)\n{\n return (a * h) / 2.0;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nThe Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\nfib4(0) -> 0\nfib4(1) -> 0\nfib4(2) -> 2\nfib4(3) -> 0\nfib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\nPlease write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n>>> fib4(5L)\n4L\n>>> fib4(6L)\n8L\n>>> fib4(7L)\n14L\n*/\nlong fib4(long n)\nnothrow @safe @nogc {\n if (n < 4) return n == 2 ? 2 : 0;\n long a = 0, b = 0, c = 2, d = 0;\n for (long i = 4; i <= n; ++i) {\n long tmp = a + b + c + d;\n a = b;\n b = c;\n c = d;\n d = tmp;\n }\n return d;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn median of elements in the array l.\n>>> median([3L, 1L, 2L, 4L, 5L])\n3L\n>>> median([-10L, 4L, 6L, 1000L, 10L, 20L])\n15.0\n*/\nfloat median(long[] l)\n{\n l.sort();\n int n = l.length;\n if (n % 2 == 0)\n {\n return (l[n/2 - 1] + l[n/2]) / 2.0;\n }\n else\n {\n return l[n/2];\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nChecks if given string is a palindrome\n>>> is_palindrome(\"\")\ntrue\n>>> is_palindrome(\"aba\")\ntrue\n>>> is_palindrome(\"aaaaa\")\ntrue\n>>> is_palindrome(\"zbcd\")\nfalse\n*/\nbool is_palindrome(string text)\n{\n int length = text.length;\n for (int i = 0; i < length / 2; i++)\n {\n if (text[i] != text[length - i - 1])\n {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn 2^n modulo p (be aware of numerics).\n>>> modp(3L, 5L)\n3L\n>>> modp(1101L, 101L)\n2L\n>>> modp(0L, 101L)\n1L\n>>> modp(3L, 11L)\n8L\n>>> modp(100L, 101L)\n1L\n*/\nlong modp(long n, long p)\n{\n return pow(2, n, p);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n For a given array of input numbers, calculate Mean Absolute Deviation\naround the mean of this dataset.\nMean Absolute Deviation is the average absolute difference between each\nelement and a centerpoint (mean in this case):\nMAD = average | x - x_mean |\n>>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n1.0\n*/\nfloat mean_absolute_deviation(float[] numbers)\n{\n float sum = 0.0;\n float mean;\n float mad;\n int n = numbers.length;"], ["import std.math;\nimport std.typecons;\n/*\nremove_vowels is a function that takes string and returns string without vowels.\n>>> remove_vowels(\"\")\n\"\"\n>>> remove_vowels(\"abcdef\")\n\"bcdf\"\n>>> remove_vowels(\"aaaaa\")\n\"\"\n>>> remove_vowels(\"aaBAA\")\n\"B\"\n>>> remove_vowels(\"zbcd\")\n\"zbcd\"\n*/\nstring remove_vowels(string text)\n{\n string result = \"\";\n foreach (char c; text)\n {\n if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' &&\n c != 'A' && c != 'E' && c != 'I' && c != 'O' && c != 'U')\n {\n result ~= c;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn true if all numbers in the array l are below threshold t.\n>>> below_threshold([1L, 2L, 4L, 10L], 100L)\ntrue\n>>> below_threshold([1L, 20L, 4L, 10L], 5L)\nfalse\n*/\nbool below_threshold(long[] l, long t)\n{\n foreach (x; l)\n {\n if (x >= t)\n {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nAdd two numbers x and y\n>>> add(2L, 3L)\n5L\n>>> add(5L, 7L)\n12L\n*/\nlong add(long x, long y)\n{\n return x + y;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCheck if two words have the same characters.\n>>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddeddabc\")\ntrue\n>>> same_chars(\"abcd\", \"dddddddabc\")\ntrue\n>>> same_chars(\"dddddddabc\", \"abcd\")\ntrue\n>>> same_chars(\"eabcd\", \"dddddddabc\")\nfalse\n>>> same_chars(\"abcd\", \"dddddddabce\")\nfalse\n>>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddddabc\")\nfalse\n*/\nbool same_chars(string s0, string s1)\n{\n int[] count0 = new int[26];\n int[] count1 = new int[26];"], ["import std.math;\nimport std.typecons;\n/*\nReturn n-th Fibonacci number.\n>>> fib(10L)\n55L\n>>> fib(1L)\n1L\n>>> fib(8L)\n21L\n*/\nlong fib(long n)\n{\n return ((pow(1 + sqrt(5), n) - pow(1 - sqrt(5), n)) / (pow(2, n) * sqrt(5)));\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n brackets is a string of \"<\" and \">\".\nreturn true if every opening bracket has a corresponding closing bracket.\n>>> correct_bracketing(\"<\")\nfalse\n>>> correct_bracketing(\"<>\")\ntrue\n>>> correct_bracketing(\"<<><>>\")\ntrue\n>>> correct_bracketing(\"><<>\")\nfalse\n*/\nbool correct_bracketing(string brackets)\n{\n int count = 0;\n foreach (char c; brackets)\n {\n if (c == '<')\n {\n count++;\n }\n else if (c == '>')\n {\n count--;\n }\n if (count < 0)\n {\n return false;\n }\n }\n return count == 0;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn true is array elements are monotonically increasing or decreasing.\n>>> monotonic([1L, 2L, 4L, 20L])\ntrue\n>>> monotonic([1L, 20L, 4L, 10L])\nfalse\n>>> monotonic([4L, 1L, 0L, -10L])\ntrue\n*/\nbool monotonic(long[] l)\n{\n bool increasing = true;\n bool decreasing = true;"], ["import std.math;\nimport std.typecons;\n/*\nReturn sorted unique common elements for two arrays.\n>>> common([1L, 4L, 3L, 34L, 653L, 2L, 5L], [5L, 7L, 1L, 5L, 9L, 653L, 121L])\n[1L, 5L, 653L]\n>>> common([5L, 3L, 2L, 8L], [3L, 2L])\n[2L, 3L]\n*/\nlong[] common(long[] l1, long[] l2)\n{\n auto s1 = l1.toSet();\n auto s2 = l2.toSet();\n auto commonSet = s1.intersect(s2);\n auto commonArray = commonSet.array;\n commonArray.sort();\n return commonArray;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nReturn the largest prime factor of n. Assume n > 1 and is not a prime.\n>>> largest_prime_factor(13195L)\n29L\n>>> largest_prime_factor(2048L)\n2L\n*/\nlong largest_prime_factor(long n)\n{\n long largest_factor = 0;\n long i = 2;\n while (i <= n)\n {\n if (n % i == 0)\n {\n largest_factor = i;\n n /= i;\n }\n else\n {\n i++;\n }\n }\n return largest_factor;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Insert a number 'delimeter' between every two consecutive elements of input array `numbers'\n>>> intersperse([], 4L)\n[]\n>>> intersperse([1L, 2L, 3L], 4L)\n[1L, 4L, 2L, 4L, 3L]\n*/\nlong[] intersperse(long[] numbers, long delimeter)\n{\n long[] result = new long[numbers.length * 2 - 1];\n for (int i = 0; i < numbers.length; i++) {\n result[i * 2] = numbers[i];\n if (i != numbers.length - 1) {\n result[i * 2 + 1] = delimeter;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nsum_to_n is a function that sums numbers from 1 to n.\n>>> sum_to_n(30L)\n465L\n>>> sum_to_n(100L)\n5050L\n>>> sum_to_n(5L)\n15L\n>>> sum_to_n(10L)\n55L\n>>> sum_to_n(1L)\n1L\n*/\nlong sum_to_n(long n)\n{\n return n * (n + 1) / 2;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n brackets is a string of \"(\" and \")\".\nreturn true if every opening bracket has a corresponding closing bracket.\n>>> correct_bracketing(\"(\")\nfalse\n>>> correct_bracketing(\"()\")\ntrue\n>>> correct_bracketing(\"(()())\")\ntrue\n>>> correct_bracketing(\")(()\")\nfalse\n*/\nbool correct_bracketing(string brackets)\n{\n int count = 0;\n foreach (char c; brackets)\n {\n if (c == '(')\n {\n count++;\n }\n else if (c == ')')\n {\n count--;\n }\n if (count < 0)\n {\n return false;\n }\n }\n return count == 0;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n xs represent coefficients of a polynomial.\nxs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n>>> derivative([3L, 1L, 2L, 4L, 5L])\n[1L, 4L, 12L, 20L]\n>>> derivative([1L, 2L, 3L])\n[2L, 6L]\n*/\nlong[] derivative(long[] xs)\n{\n long[] result = new long[xs.length - 1];\n for (int i = 1; i < xs.length; i++) {\n result[i - 1] = xs[i] * i;\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nThe FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\nfibfib(0) == 0\nfibfib(1) == 0\nfibfib(2) == 1\nfibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\nPlease write a function to efficiently compute the n-th element of the fibfib number sequence.\n>>> fibfib(1L)\n0L\n>>> fibfib(5L)\n4L\n>>> fibfib(8L)\n24L\n*/\nlong fibfib(long n)\nnothrow @safe @nogc {\n if (n < 3) return n == 2 ? 1 : 0;\n long a = 0, b = 0, c = 1;\n for (long i = 3; i <= n; ++i) {\n long d = a + b + c;\n a = b;\n b = c;\n c = d;\n }\n return c;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function vowels_count which takes a string representing\na word as input and returns the number of vowels in the string.\nVowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\nvowel, but only when it is at the end of the given word.\nExample:\n>>> vowels_count(\"abcde\")\n2L\n>>> vowels_count(\"ACEDY\")\n3L\n*/\nlong vowels_count(string s)\n{\n long count = 0;\n foreach (char c; s)\n {\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || (c == 'y' && s[$-1] != ' '))\n {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCircular shift the digits of the integer x, shift the digits right by shift\nand return the result as a string.\nIf shift > number of digits, return digits reversed.\n>>> circular_shift(12L, 1L)\n\"21\"\n>>> circular_shift(12L, 2L)\n\"12\"\n*/\nstring circular_shift(long x, long shift)\n{\n string s = toString(x);\n long n = s.length;\n if (shift > n)\n {\n s.reverse();\n return s;\n }\n string shifted = s[n-shift..$] ~ s[0..n-shift];\n return shifted;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nTask\nWrite a function that takes a string as input and returns the sum of the upper characters only'\nASCII codes.\nExamples:\n>>> digitSum(\"\")\n0L\n>>> digitSum(\"abAB\")\n131L\n>>> digitSum(\"abcCd\")\n67L\n>>> digitSum(\"helloE\")\n69L\n>>> digitSum(\"woArBld\")\n131L\n>>> digitSum(\"aAaaaXa\")\n153L\n*/\nlong digitSum(string s)\n{\n long sum = 0;\n foreach (char c; s)\n {\n if (isupper(c))\n {\n sum += (long)c;\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nIn this task, you will be given a string that represents a number of apples and oranges \nthat are distributed in a basket of fruit this basket contains \napples, oranges, and mango fruits. Given the string that represents the total number of \nthe oranges and apples and an integer that represent the total number of the fruits \nin the basket return the number of the mango fruits in the basket.\nfor examble:\n>>> fruit_distribution(\"5 apples and 6 oranges\", 19L)\n8L\n>>> fruit_distribution(\"0 apples and 1 oranges\", 3L)\n2L\n>>> fruit_distribution(\"2 apples and 3 oranges\", 100L)\n95L\n>>> fruit_distribution(\"100 apples and 1 oranges\", 120L)\n19L\n*/\nlong fruit_distribution(string s, long n)\n{\n long apples = s.split(\" \")[0].toLong();\n long oranges = s.split(\" \")[4].toLong();\n long mangoes = n - (apples + oranges);\n return mangoes;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n\"Given an array representing a branch of a tree that has non-negative integer nodes\nyour task is to pluck one of the nodes and return it.\nThe plucked node should be the node with the smallest even value.\nIf multiple nodes with the same smallest even value are found return the node that has smallest index.\nThe plucked node should be returned in an array, [ smalest_value, its index ],\nIf there are no even values or the given array is empty, return [].\nExample 1:\n>>> pluck([4L, 2L, 3L])\n[2L, 1L]\nExplanation: 2 has the smallest even value, and 2 has the smallest index.\nExample 2:\n>>> pluck([1L, 2L, 3L])\n[2L, 1L]\nExplanation: 2 has the smallest even value, and 2 has the smallest index.\nExample 3:\n>>> pluck([])\n[]\nExample 4:\n>>> pluck([5L, 0L, 3L, 0L, 4L, 2L])\n[0L, 1L]\nExplanation: 0 is the smallest value, but there are two zeros,\n so we will choose the first zero, which has the smallest index.\nConstraints:\n * 1 <= nodes.length <= 10000\n * 0 <= node.value\n*/\nlong[] pluck(long[] arr)\n{\n long[] result = new long[2];\n long minEven = long.MaxValue;\n long minIndex = -1;"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a non-empty array of positive integers. Return the greatest integer that is greater than \nzero, and has a frequency greater than or equal to the value of the integer itself. \nThe frequency of an integer is the number of times it appears in the array.\nIf no such a value exist, return -1.\nExamples:\n>>> search([4L, 1L, 2L, 2L, 3L, 1L])\n2L\n>>> search([1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L])\n3L\n>>> search([5L, 5L, 4L, 4L, 4L])\n-1L\n*/\nlong search(long[] lst)\n{\n long[] freq = new long[lst.length+1];\n foreach(long num; lst)\n {\n freq[num]++;\n }\n for(long i = lst.length; i > 0; i--)\n {\n if(freq[i] >= i)\n {\n return i;\n }\n }\n return -1L;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\nFor each of the group, output the deepest level of nesting of parentheses.\nE.g. (()()) has maximum two levels of nesting while ((())) has three.\n>>> parse_nested_parens(\"(()()) ((())) () ((())()())\")\n[2L, 3L, 1L, 3L]\n*/\nlong[] parse_nested_parens(string paren_string)\nnotnull\n{\n long[] result;\n long max_depth = 0;\n long current_depth = 0;\n foreach (char c; paren_string)\n {\n if (c == '(')\n {\n current_depth++;\n max_depth = max(max_depth, current_depth);\n }\n else if (c == ')')\n {\n current_depth--;\n }\n }\n result = new long[max_depth];\n current_depth = 0;\n foreach (char c; paren_string)\n {\n if (c == '(')\n {\n current_depth++;\n result[current_depth-1]++;\n }\n else if (c == ')')\n {\n current_depth--;\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven array of integers, return array in strange order.\nStrange sorting, is when you start with the minimum value,\nthen maximum of the remaining integers, then minimum and so on.\nExamples:\n>>> strange_sort_list([1L, 2L, 3L, 4L])\n[1L, 4L, 2L, 3L]\n>>> strange_sort_list([5L, 5L, 5L, 5L])\n[5L, 5L, 5L, 5L]\n>>> strange_sort_list([])\n[]\n*/\nlong[] strange_sort_list(long[] lst)\n{\n long[] result = new long[lst.length];\n int i = 0;\n int j = lst.length - 1;\n int k = 0;\n while (i <= j)\n {\n result[k++] = lst[i++];\n if (i <= j)\n {\n result[k++] = lst[j--];\n }\n }\n return result;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven the lengths of the three sides of a triangle. Return the area of\nthe triangle rounded to 2 decimal points if the three sides form a valid triangle. \nOtherwise return -1\nThree sides make a valid triangle when the sum of any two sides is greater \nthan the third side.\nExample:\n>>> triangle_area(3L, 4L, 5L)\n6.0\n>>> triangle_area(1L, 2L, 10L)\n-1L\n*/\nfloat triangle_area(long a, long b, long c)\nnot pure nothrow @safe @nogc {\n if (a + b <= c || a + c <= b || b + c <= a) {\n return -1.0;\n }\n float s = (a + b + c) / 2.0;\n float area = sqrt(s * (s - a) * (s - b) * (s - c));\n return area.round(2);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that returns true if the object q will fly, and false otherwise.\nThe object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.\nExample:\n>>> will_it_fly([1L, 2L], 5L)\nfalse\n# 1+2 is less than the maximum possible weight, but it's unbalanced.\n>>> will_it_fly([3L, 2L, 3L], 1L)\nfalse\n# it's balanced, but 3+2+3 is more than the maximum possible weight.\n>>> will_it_fly([3L, 2L, 3L], 9L)\ntrue\n# 3+2+3 is less than the maximum possible weight, and it's balanced.\n>>> will_it_fly([3L], 5L)\ntrue\n# 3 is less than the maximum possible weight, and it's balanced.\n*/\nbool will_it_fly(long[] q, long w)\n{\n long sum = 0;\n long n = q.length;\n for (long i = 0; i < n; i++) {\n sum += q[i];\n }\n if (sum > w) {\n return false;\n }\n for (long i = 0; i < n / 2; i++) {\n if (q[i] != q[n - i - 1]) {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array arr of integers, find the minimum number of elements that\nneed to be changed to make the array palindromic. A palindromic array is an array that\nis read the same backwards and forwards. In one change, you can change one element to any other element.\nFor example:\n>>> smallest_change([1L, 2L, 3L, 5L, 4L, 7L, 9L, 6L])\n4L\n>>> smallest_change([1L, 2L, 3L, 4L, 3L, 2L, 2L])\n1L\n>>> smallest_change([1L, 2L, 3L, 2L, 1L])\n0L\n*/\nlong smallest_change(long[] arr)\n{\n long n = arr.length;\n long count = 0;\n for (long i = 0; i < n / 2; i++) {\n if (arr[i] != arr[n - i - 1]) {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that accepts two arrays of strings and returns the array that has \ntotal number of chars in the all strings of the array less than the other array.\nif the two arrays have the same number of chars, return the first array.\nExamples\n>>> total_match([], [])\n[]\n>>> total_match([\"hi\", \"admin\"], [\"hI\", \"Hi\"])\n[\"hI\", \"Hi\"]\n>>> total_match([\"hi\", \"admin\"], [\"hi\", \"hi\", \"admin\", \"project\"])\n[\"hi\", \"admin\"]\n>>> total_match([\"hi\", \"admin\"], [\"hI\", \"hi\", \"hi\"])\n[\"hI\", \"hi\", \"hi\"]\n>>> total_match([\"4\"], [\"1\", \"2\", \"3\", \"4\", \"5\"])\n[\"4\"]\n*/\nstring[] total_match(string[] lst1, string[] lst2)\n{\n int total1 = 0;\n int total2 = 0;\n foreach (str; lst1)\n {\n total1 += str.length;\n }\n foreach (str; lst2)\n {\n total2 += str.length;\n }\n if (total1 < total2)\n {\n return lst1;\n }\n else if (total1 > total2)\n {\n return lst2;\n }\n else\n {\n return lst1;\n }\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that returns true if the given number is the multiplication of 3 prime numbers\nand false otherwise.\nKnowing that (a) is less then 100. \nExample:\n>>> is_multiply_prime(30L)\ntrue\n30 = 2 * 3 * 5\n*/\nbool is_multiply_prime(long a)\n{\n int count = 0;\n long[] 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];\n foreach (long prime; primes)\n {\n if (a % prime == 0)\n {\n count++;\n a /= prime;\n }\n }\n return count == 3 && a == 1;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYour task is to write a function that returns true if a number x is a simple\npower of n and false in other cases.\nx is a simple power of n if n**int=x\nFor example:\n>>> is_simple_power(1L, 4L)\ntrue\n>>> is_simple_power(2L, 2L)\ntrue\n>>> is_simple_power(8L, 2L)\ntrue\n>>> is_simple_power(3L, 2L)\nfalse\n>>> is_simple_power(3L, 1L)\nfalse\n>>> is_simple_power(5L, 3L)\nfalse\n*/\nbool is_simple_power(long x, long n)\n{\n if(x == 1L && n == 1L)\n return true;\n if(n == 1L)\n return false;\n long int_part = x.log(n).round;\n return pow(n, int_part) == x;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that takes an integer a and returns true \nif this ingeger is a cube of some integer number.\nNote: you may assume the input is always valid.\nExamples:\n>>> iscube(1L)\ntrue\n>>> iscube(2L)\nfalse\n>>> iscube(-1L)\ntrue\n>>> iscube(64L)\ntrue\n>>> iscube(0L)\ntrue\n>>> iscube(180L)\nfalse\n*/\nbool iscube(long a)\n{\n if(a == 0)\n return true;\n long cubeRoot = a.cubeRoot().round;\n return cubeRoot * cubeRoot * cubeRoot == a;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou have been tasked to write a function that receives \na hexadecimal number as a string and counts the number of hexadecimal \ndigits that are primes (prime number, or a prime, is a natural number \ngreater than 1 that is not a product of two smaller natural numbers).\nHexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\nPrime numbers are 2, 3, 5, 7, 11, 13, 17,...\nSo you have to determine a number of the following digits: 2, 3, 5, 7, \nB (=decimal 11), D (=decimal 13).\nNote: you may assume the input is always correct or empty string, \nand symbols A,B,C,D,E,F are always uppercase.\nExamples:\n>>> hex_key(\"AB\")\n1L\n>>> hex_key(\"1077E\")\n2L\n>>> hex_key(\"ABED1A33\")\n4L\n>>> hex_key(\"123456789ABCDEF0\")\n6L\n>>> hex_key(\"2020\")\n2L\n*/\nlong hex_key(string num)\nnot null\n{\n long count = 0;\n foreach (char c; num) {\n int digit = c.toDigit();\n if (digit == 2 || digit == 3 || digit == 5 || digit == 7 || digit == 11 || digit == 13) {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou will be given a number in decimal form and your task is to convert it to\nbinary format. The function should return a string, with each character representing a binary\nnumber. Each character in the string will be '0' or '1'.\nThere will be an extra couple of characters 'db' at the beginning and at the end of the string.\nThe extra characters are there to help with the format.\nExamples:\n>>> decimal_to_binary(15L)\n\"db1111db\"\n>>> decimal_to_binary(32L)\n\"db100000db\"\n*/\nstring decimal_to_binary(long decimal)\n{\n string binary = \"\";\n while (decimal > 0)\n {\n binary = (decimal % 2 == 0) ? \"0\" + binary : \"1\" + binary;\n decimal /= 2;\n }\n return \"db\" + binary + \"db\";\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n Filter an input array of strings only for ones that contain given substring\n>>> filter_by_substring([], \"a\")\n[]\n>>> filter_by_substring([\"abc\", \"bacd\", \"cde\", \"array\"], \"a\")\n[\"abc\", \"bacd\", \"array\"]\n*/\nstring[] filter_by_substring(string[] strings, string substring)\n{\n string[] filtered = new string[0];\n foreach (string s; strings)\n {\n if (s.canFind(substring))\n {\n filtered ~= s;\n }\n }\n return filtered;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a string s.\nYour task is to check if the string is hapd or not.\nA string is hapd if its length is at least 3 and every 3 consecutive letters are distinct\nFor example:\n>>> is_happy(\"a\")\nfalse\n>>> is_happy(\"aa\")\nfalse\n>>> is_happy(\"abcd\")\ntrue\n>>> is_happy(\"aabb\")\nfalse\n>>> is_happy(\"adb\")\ntrue\n>>> is_happy(\"xyy\")\nfalse\n*/\nbool is_happy(string s)\n{\n if (s.length < 3) return false;\n for (int i = 0; i < s.length - 2; i++)\n {\n if (s[i] == s[i+1] || s[i] == s[i+2] || s[i+1] == s[i+2])\n {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nIt is the last week of the semester and the teacher has to give the grades\nto students. The teacher has been making her own algorithm for grading.\nThe only problem is, she has lost the code she used for grading.\nShe has given you an array of GPAs for some students and you have to write \na function that can output an array of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\nExample:\n>>> grade_equation([4.0, 3L, 1.7, 2L, 3.5])\n[\"A+\", \"B\", \"C-\", \"C\", \"A-\"]\n*/\nstring[] numerical_letter_grade(float[] grades)\n{\n string[] letter_grades = new string[grades.length];\n for(int i = 0; i < grades.length; i++)\n {\n if(grades[i] == 4.0)\n {\n letter_grades[i] = \"A+\";\n }\n else if(grades[i] > 3.7)\n {\n letter_grades[i] = \"A\";\n }\n else if(grades[i] > 3.3)\n {\n letter_grades[i] = \"A-\";\n }\n else if(grades[i] > 3.0)\n {\n letter_grades[i] = \"B+\";\n }\n else if(grades[i] > 2.7)\n {\n letter_grades[i] = \"B\";\n }\n else if(grades[i] > 2.3)\n {\n letter_grades[i] = \"B-\";\n }\n else if(grades[i] > 2.0)\n {\n letter_grades[i] = \"C+\";\n }\n else if(grades[i] > 1.7)\n {\n letter_grades[i] = \"C\";\n }\n else if(grades[i] > 1.3)\n {\n letter_grades[i] = \"C-\";\n }\n else if(grades[i] > 1.0)\n {\n letter_grades[i] = \"D+\";\n }\n else if(grades[i] > 0.7)\n {\n letter_grades[i] = \"D\";\n }\n else if(grades[i] > 0.0)\n {\n letter_grades[i] = \"D-\";\n }\n else\n {\n letter_grades[i] = \"E\";\n }\n }\n return letter_grades;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that takes a string and returns true if the string\nlength is a prime number or false otherwise\nExamples\n>>> prime_length(\"Hello\")\ntrue\n>>> prime_length(\"abcdcba\")\ntrue\n>>> prime_length(\"kittens\")\ntrue\n>>> prime_length(\"orange\")\nfalse\n*/\nbool prime_length(string string)\n{\n int length = string.length;\n if (length < 2)\n {\n return false;\n }\n for (int i = 2; i <= sqrt(length); i++)\n {\n if (length % i == 0)\n {\n return false;\n }\n }\n return true;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer n, return the count of the numbers of n-digit\npositive integers that start or end with 1.\n*/\nlong starts_one_ends(long n)\n{\n if (n == 1) {\n return 1;\n }\n long count = 0;\n for (long i = 1; i <= n; i++) {\n if (i == 1 || i == n) {\n count += pow(2, n - 2);\n } else {\n count += pow(2, n - i - 1);\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a positive integer N, return the total sum of its digits in binary.\nExample\n>>> solve(1000L)\n\"1\"\n>>> solve(150L)\n\"110\"\n>>> solve(147L)\n\"1100\"\nVariables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\nOutput:\n a string of binary number\n*/\nstring solve(long N)\n{\n long binarySum = 0;\n while (N > 0)\n {\n binarySum += N % 2;\n N /= 2;\n }\n return binarySum.toBinaryString();\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a non-empty array of integers lst. add the even elements that are at odd indices..\nExamples:\n>>> add([4L, 2L, 6L, 7L])\n2L\n*/\nlong add(long[] lst)\n{\n long sum = 0;\n for (int i = 1; i < lst.length; i += 2) {\n if (lst[i] % 2 == 0) {\n sum += lst[i];\n }\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that takes a string and returns an ordered version of it.\nOrdered version of string, is a string where all words (separated by space)\nare replaced by a new word where all the characters arranged in\nascending order based on ascii value.\nNote: You should keep the order of words and blank spaces in the sentence.\nFor example:\n>>> anti_shuffle(\"Hi\")\n\"Hi\"\n>>> anti_shuffle(\"hello\")\n\"ehllo\"\n>>> anti_shuffle(\"Hello World!!!\")\n\"Hello !!!Wdlor\"\n*/\nstring anti_shuffle(string s)\n{\n string[] words = s.split(\" \");\n string result = \"\";\n foreach (word; words)\n {\n char[] chars = word.toCharArray();\n chars.sort();\n result ~= chars.data;\n result ~= \" \";\n }\n return result.strip();\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given a 2 dimensional data, as a nested arrays,\nwhich is similar to matrix, however, unlike matrices,\neach row may contain a different number of columns.\nGiven lst, and integer x, find integers x in the array,\nand return array of tuples, [(x1, y1), (x2, y2) ...] such that\neach tuple is a coordinate - (row, columns), starting with 0.\nSort coordinates initially by rows in ascending order.\nAlso, sort coordinates of the row by columns in descending order.\nExamples:\n>>> get_row([[1L, 2L, 3L, 4L, 5L, 6L], [1L, 2L, 3L, 4L, 1L, 6L], [1L, 2L, 3L, 4L, 5L, 1L]], 1L)\n[tuple(0L, 0L), tuple(1L, 4L), tuple(1L, 0L), tuple(2L, 5L), tuple(2L, 0L)]\n>>> get_row([], 1L)\n[]\n>>> get_row([[], [1L], [1L, 2L, 3L]], 3L)\n[tuple(2L, 2L)]\n*/\nTuple!(long, long)[] get_row(long[][] lst, long x)\nnotnull lst && lst.length > 0 && lst[0].length > 0:\n Tuple!(long, long)[] result = new Tuple!(long, long)[];\n foreach (i, row; lst)\n {\n foreach (j, col; row)\n {\n if (col == x)\n {\n result ~= Tuple(i, j);\n }\n }\n }\n result.sort().reverse();\n return result;\nelse:\n return [];\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an array of non-negative integers, return a cod of the given array after sorting,\nyou will sort the given array in ascending order if the sum( first index value, last index value) is odd,\nor sort it in descending order if the sum( first index value, last index value) is even.\nNote:\n* don't change the given array.\nExamples:\n>>> sort_array([])\n[]\n>>> sort_array([5L])\n[5L]\n>>> sort_array([2L, 4L, 3L, 0L, 1L, 5L])\n[0L, 1L, 2L, 3L, 4L, 5L]\n>>> sort_array([2L, 4L, 3L, 0L, 1L, 5L, 6L])\n[6L, 5L, 4L, 3L, 2L, 1L, 0L]\n*/\nlong[] sort_array(long[] array)\n{\n long[] sortedArray = array.dup;\n long sum = array[0] + array[$-1];\n if (sum % 2 == 0) {\n sortedArray.sort();\n sortedArray.reverse();\n } else {\n sortedArray.sort();\n }\n return sortedArray;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function encrypt that takes a string as an argument and\nreturns a string encrypted with the alphabet being rotated. \nThe alphabet should be rotated in a manner such that the letters \nshift down by two multiplied to two places.\nFor example:\n>>> encrypt(\"hi\")\n\"lm\"\n>>> encrypt(\"asdfghjkl\")\n\"ewhjklnop\"\n>>> encrypt(\"gf\")\n\"kj\"\n>>> encrypt(\"et\")\n\"ix\"\n*/\nstring encrypt(string s)\n{\n string encrypted = \"\";\n int shift = 2 * 2; // Shift the alphabet by 2 * 2 places\n for (int i = 0; i < s.length; i++)\n {\n char c = s[i];\n if (c >= 'a' && c <= 'z')\n {\n c = (c - 'a' + shift) % 26 + 'a';\n }\n else if (c >= 'A' && c <= 'Z')\n {\n c = (c - 'A' + shift) % 26 + 'A';\n }\n encrypted += c;\n }\n return encrypted;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.\nEmpty sum should be equal to 0 and empty product should be equal to 1.\n>>> sum_product([])\ntuple(0L, 1L)\n>>> sum_product([1L, 2L, 3L, 4L])\ntuple(10L, 24L)\n*/\nTuple!(long, long) sum_product(long[] numbers)\n{\n long sum = 0L;\n long product = 1L;\n foreach (num; numbers)\n {\n sum += num;\n product *= num;\n }\n return tuple(sum, product);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given an array of integers.\nWrite a function next_smallest() that returns the 2nd smallest element of the array.\nReturn null if there is no such element.\n>>> next_smallest([1L, 2L, 3L, 4L, 5L])\n2L\n>>> next_smallest([5L, 1L, 4L, 3L, 2L])\n2L\n>>> next_smallest([])\nNone\n>>> next_smallest([1L, 1L])\nNone\n*/\nNullable!(long) next_smallest(long[] lst)\n{\n if (lst.length < 2) return null;\n long smallest = lst[0];\n long nextSmallest = lst[1];\n foreach (long num; lst)\n {\n if (num < smallest)\n {\n nextSmallest = smallest;\n smallest = num;\n }\n else if (num < nextSmallest && num != smallest)\n {\n nextSmallest = num;\n }\n }\n return nextSmallest == smallest ? null : nextSmallest;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou'll be given a string of words, and your task is to count the number\nof boredoms. A boredom is a sentence that starts with the word \"I\".\nSentences are delimited by '.', '?' or '!'.\nFor example:\n>>> is_bored(\"Hello world\")\n0L\n>>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n1L\n*/\nlong is_bored(string S)\n{\n long boredoms = 0;\n string[] sentences = S.splitBy(\".\", \"?\", \"!\");\n foreach (sentence; sentences)\n {\n if (sentence.startsWith(\"I \"))\n {\n boredoms++;\n }\n }\n return boredoms;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function that takes 3 numbers.\nReturns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\nReturns false in any other cases.\nExamples\n>>> any_int(5L, 2L, 7L)\ntrue\n>>> any_int(3L, 2L, 2L)\nfalse\n>>> any_int(3L, -2L, 1L)\ntrue\n>>> any_int(3.6, -2.2, 2L)\nfalse\n*/\nbool any_int(float x, float y, float z)\n{\n if (x.isWhole && y.isWhole && z.isWhole)\n {\n if (x == y + z || y == x + z || z == x + y)\n {\n return true;\n }\n }\n return false;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nWrite a function that takes a message, and encodes in such a \nway that it swaps case of all letters, replaces all vowels in \nthe message with the letter that appears 2 places ahead of that \nvowel in the english alphabet. \nAssume only letters. \nExamples:\n>>> encode(\"test\")\n\"TGST\"\n>>> encode(\"This is a message\")\n\"tHKS KS C MGSSCGG\"\n*/\nstring encode(string message)\n{\n string vowels = \"aeiouAEIOU\";\n string encodedMessage = \"\";\n for (int i = 0; i < message.length; i++)\n {\n char c = message[i];\n if (isalpha(c))\n {\n if (vowels.find(c) != -1)\n {\n int index = vowels.find(c);\n int newIndex = (index + 2) % vowels.length;\n c = vowels[newIndex];\n }\n c = c ^ 32; // Swap case\n }\n encodedMessage ~= c;\n }\n return encodedMessage;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nYou are given an array of integers.\nYou need to find the largest prime value and return the sum of its digits.\nExamples:\n>>> skjkasdkd([0L, 3L, 2L, 1L, 3L, 5L, 7L, 4L, 5L, 5L, 5L, 2L, 181L, 32L, 4L, 32L, 3L, 2L, 32L, 324L, 4L, 3L])\n10L\n>>> skjkasdkd([1L, 0L, 1L, 8L, 2L, 4597L, 2L, 1L, 3L, 40L, 1L, 2L, 1L, 2L, 4L, 2L, 5L, 1L])\n25L\n>>> skjkasdkd([1L, 3L, 1L, 32L, 5107L, 34L, 83278L, 109L, 163L, 23L, 2323L, 32L, 30L, 1L, 9L, 3L])\n13L\n>>> skjkasdkd([0L, 724L, 32L, 71L, 99L, 32L, 6L, 0L, 5L, 91L, 83L, 0L, 5L, 6L])\n11L\n>>> skjkasdkd([0L, 81L, 12L, 3L, 1L, 21L])\n3L\n>>> skjkasdkd([0L, 8L, 1L, 2L, 1L, 7L])\n7L\n*/\nlong skjkasdkd(long[] lst)\nnotnull notempty(lst)\n{\n long maxPrime = 0;\n foreach (num; lst)\n {\n if (isPrime(num) && num > maxPrime)\n {\n maxPrime = num;\n }\n }\n long sum = 0;\n while (maxPrime > 0)\n {\n sum += maxPrime % 10;\n maxPrime /= 10;\n }\n return sum;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven an associative array, return true if all keys are strings in lower \ncase or all keys are strings in upper case, else return false.\nThe function should return false is the given associative array is empty.\nExamples:\n>>> check_dict_case([\"a\": \"apple\", \"b\": \"banana\"].nullable)\ntrue\n>>> check_dict_case([\"a\": \"apple\", \"A\": \"banana\", \"B\": \"banana\"].nullable)\nfalse\n>>> check_dict_case([\"a\": \"apple\", 8L: \"banana\", \"a\": \"apple\"].nullable)\nfalse\n>>> check_dict_case([\"Name\": \"John\", \"Age\": \"36\", \"City\": \"Houston\"].nullable)\nfalse\n>>> check_dict_case([\"STATE\": \"NC\", \"ZIP\": \"12345\"].nullable)\ntrue\n*/\nbool check_dict_case(Nullable!(string[string]) dict)\nnot null and (dict.keys.all(islower) or dict.keys.all(isupper));\n"], ["import std.math;\nimport std.typecons;\n/*\nImplement a function that takes an non-negative integer and returns an array of the first n\nintegers that are prime numbers and less than n.\nfor example:\n>>> count_up_to(5L)\n[2L, 3L]\n>>> count_up_to(11L)\n[2L, 3L, 5L, 7L]\n>>> count_up_to(0L)\n[]\n>>> count_up_to(20L)\n[2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L]\n>>> count_up_to(1L)\n[]\n>>> count_up_to(18L)\n[2L, 3L, 5L, 7L, 11L, 13L, 17L]\n*/\nlong[] count_up_to(long n)\n{\n long[] primes;\n long count = 0;\n long i = 2;\n while (i < n)\n {\n if (isPrime(i))\n {\n primes ~= i;\n count++;\n }\n i++;\n }\n return primes;\n}"], ["import std.math;\nimport std.typecons;\n/*\nComplete the function that takes two integers and returns \nthe product of their unit digits.\nAssume the input is always valid.\nExamples:\n>>> multiply(148L, 412L)\n16L\n>>> multiply(19L, 28L)\n72L\n>>> multiply(2020L, 1851L)\n0L\n>>> multiply(14L, -15L)\n20L\n*/\nlong multiply(long a, long b)\n{\n return (a % 10) * (b % 10);\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nGiven a string s, count the number of uppercase vowels in even indices.\nFor example:\n>>> count_upper(\"aBCdEf\")\n1L\n>>> count_upper(\"abcdefg\")\n0L\n>>> count_upper(\"dBBE\")\n0L\n*/\nlong count_upper(string s)\n{\n long count = 0;\n foreach (i, c; s)\n {\n if (i % 2 == 0 && c.isUpper && \"AEIOU\".index(c) != -1)\n {\n count++;\n }\n }\n return count;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\nCreate a function that takes a value (string) representing a number\nand returns the closest integer to it. If the number is equidistant\nfrom two integers, round it away from zero.\nExamples\n>>> closest_integer(\"10\")\n10L\n>>> closest_integer(\"15.3\")\n15L\nNote:\nRounding away from zero means that if the given number is equidistant\nfrom two integers, the one you should return is the one that is the\nfarthest from zero. For example closest_integer(\"14.5\") should\nreturn 15 and closest_integer(\"-14.5\") should return -15.\n*/\nlong closest_integer(string value)\n{\n immutable double num = value.toDouble();\n immutable long rounded = num.round.toLong;\n immutable long diff = num - rounded;\n return diff == 0.5 ? (num > 0 ? rounded + 1 : rounded - 1) : rounded;\n}\n"], ["import std.math;\nimport std.typecons;\n/*\n From a given array of integers, generate an array of rolling maximum element found until given moment\nin the sequence.\n>>> rolling_max([1L, 2L, 3L, 2L, 3L, 4L, 2L])\n[1L, 2L, 3L, 3L, 3L, 4L, 4L]\n*/\nlong[] rolling_max(long[] numbers)\n{\n long[] result = new long[numbers.length];\n long max = long.min;\n for (int i = 0; i < numbers.length; i++)\n {\n max = max(max, numbers[i]);\n result[i] = max;\n }\n return result;\n}\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-java_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-java_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..6756e82683da739492a240ea62c5f9b56011dce3 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-java_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Check if in given array list of numbers, are any two numbers closer to each other than\n // given threshold.\n // >>> hasCloseElements((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f))), (0.5f))\n // (false)\n // >>> hasCloseElements((new ArrayList(Arrays.asList((float)1.0f, (float)2.8f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.3f))\n // (true)\n public static boolean hasCloseElements(ArrayList numbers, float threshold) {\n for (int i = 0; i < numbers.size(); i++) {\n for (int j = i + 1; j < numbers.size(); j++) {\n if (Math.abs(numbers.get(i) - numbers.get(j)) <= threshold) {\n return true;\n }\n }\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer n, you have to make a pile of n levels of stones.\n // The first level has n stones.\n // The number of stones in the next level is:\n // - the next odd number if n is odd.\n // - the next even number if n is even.\n // Return the number of stones in each level in an array array list, where element at index\n // i represents the number of stones in the level (i+1).\n // Examples:\n // >>> makeAPile((3l))\n // (new ArrayList(Arrays.asList((long)3l, (long)5l, (long)7l)))\n public static ArrayList makeAPile(long n) {\n ArrayList result = new ArrayList();\n result.add(n);\n long next = n % 2 == 0 ? n + 2 : n + 1;\n while (next <= n * 2) {\n result.add(next);\n next = next % 2 == 0 ? next + 2 : next + 1;\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You will be given a string of words separated by commas or spaces. Your task is\n // to split the string into words and return an array array list of the words.\n // For example:\n // >>> wordsString((\"Hi, my name is John\"))\n // (new ArrayList(Arrays.asList((String)\"Hi\", (String)\"my\", (String)\"name\", (String)\"is\", (String)\"John\")))\n // >>> wordsString((\"One, two, three, four, five, six\"))\n // (new ArrayList(Arrays.asList((String)\"One\", (String)\"two\", (String)\"three\", (String)\"four\", (String)\"five\", (String)\"six\")))\n public static ArrayList wordsString(String s) {\n String[] words = s.split(\"[\\\\s,]+\");\n ArrayList result = new ArrayList();\n for (String word : words) {\n result.add(word);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // This function takes two positive numbers x and y and returns the\n // biggest even integer number that is in the range [x, y] inclusive. If \n // there's no such number, then the function should return -1.\n // For example:\n // >>> chooseNum((12l), (15l))\n // (14l)\n // >>> chooseNum((13l), (12l))\n // (-1l)\n public static long chooseNum(long x, long y) {\n if (x % 2 != 0) {\n x++; // make x even\n }\n if (x > y) {\n return -1; // no even number in range\n }\n return y - y % 2; // return biggest even number in range"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of positive integers x. return a sorted array list of all \n // elements that hasn't any even digit.\n // Note: Returned array list should be sorted in increasing order.\n // For example:\n // >>> uniqueDigits((new ArrayList(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)15l, (long)33l)))\n // >>> uniqueDigits((new ArrayList(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l))))\n // (new ArrayList(Arrays.asList()))\n public static ArrayList uniqueDigits(ArrayList x) {\n ArrayList result = new ArrayList();\n for (Long num : x) {\n boolean hasEvenDigit = false;\n while (num > 0) {\n if (num % 2 == 0) {\n hasEvenDigit = true;\n break;\n }\n num /= 10;\n }\n if (!hasEvenDigit) {\n result.add(num);\n }\n }\n Collections.sort(result);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of integers, sort the integers that are between 1 and 9 inclusive,\n // reverse the resulting array array list, and then replace each digit by its corresponding name from\n // \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n // For example:\n // >>> byLength((new ArrayList(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((String)\"Eight\", (String)\"Five\", (String)\"Four\", (String)\"Three\", (String)\"Two\", (String)\"Two\", (String)\"One\", (String)\"One\")))\n // If the array array list is empty, return an empty array array list:\n // >>> byLength((new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n // If the array array list has any strange number ignore it:\n // >>> byLength((new ArrayList(Arrays.asList((long)1l, (long)-1l, (long)55l))))\n // (new ArrayList(Arrays.asList((String)\"One\")))\n public static ArrayList byLength(ArrayList arr) {\n ArrayList result = new ArrayList();\n ArrayList filtered = new ArrayList();\n for (Long num : arr) {\n if (num >= 1 && num <= 9) {\n filtered.add(num);\n }\n }\n Collections.sort(filtered);\n Collections.reverse(filtered);\n for (Long num : filtered) {\n switch (num.intValue()) {\n case 1:\n result.add(\"One\");\n break;\n case 2:\n result.add(\"Two\");\n break;\n case 3:\n result.add(\"Three\");\n break;\n case 4:\n result.add(\"Four\");\n break;\n case 5:\n result.add(\"Five\");\n break;\n case 6:\n result.add(\"Six\");\n break;\n case 7:\n result.add(\"Seven\");\n break;\n case 8:\n result.add(\"Eight\");\n break;\n case 9:\n result.add(\"Nine\");\n break;\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Implement the function f that takes n as a parameter,\n // and returns an array array list of size n, such that the value of the element at index i is the factorial of i if i is even\n // or the sum of numbers from 1 to i otherwise.\n // i starts from 1.\n // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n // Example:\n // >>> f((5l))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l)))\n public static ArrayList f(long n) {\n ArrayList result = new ArrayList();\n for (long i = 1; i <= n; i++) {\n if (i % 2 == 0) {\n long factorial = 1;\n for (long j = 2; j <= i; j++) {\n factorial *= j;\n }\n result.add(factorial);\n } else {\n long sum = 0;\n for (long j = 1; j <= i; j++) {\n sum += j;\n }\n result.add(sum);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer n, return a pair that has the number of even and odd\n // integer palindromes that fall within the range(1, n), inclusive.\n // Example 1:\n // >>> evenOddPalindrome((3l))\n // (Pair.with(1l, 2l))\n // Explanation:\n // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n // Example 2:\n // >>> evenOddPalindrome((12l))\n // (Pair.with(4l, 6l))\n // Explanation:\n // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n // Note:\n // 1. 1 <= n <= 10^3\n // 2. returned pair has the number of even and odd integer palindromes respectively.\n public static Pair evenOddPalindrome(long n) {\n long evenCount = 0;\n long oddCount = 0;\n for (long i = 1; i <= n; i++) {\n if (isPalindrome(i)) {\n if (i % 2 == 0) {\n evenCount++;\n } else {\n oddCount++;\n }\n }\n }\n return Pair.with(evenCount, oddCount);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function count_nums which takes an array array list of integers and returns\n // the number of elements which has a sum of digits > 0.\n // If a number is negative, then its first signed digit will be negative:\n // e.g. -123 has signed digits -1, 2, and 3.\n // >>> countNums((new ArrayList(Arrays.asList())))\n // (0l)\n // >>> countNums((new ArrayList(Arrays.asList((long)-1l, (long)11l, (long)-11l))))\n // (1l)\n // >>> countNums((new ArrayList(Arrays.asList((long)1l, (long)1l, (long)2l))))\n // (3l)\n public static long countNums(ArrayList arr) {\n long count = 0;\n for (long num : arr) {\n long sum = 0;\n long n = Math.abs(num);\n while (n > 0) {\n sum += n % 10;\n n /= 10;\n }\n if (sum > 0) {\n count++;\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // We have an array array list 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n // numbers in the array array list will be randomly ordered. Your task is to determine if\n // it is possible to get an array array list sorted in non-decreasing order by performing \n // the following operation on the given array array list:\n // You are allowed to perform right shift operation any number of times.\n // One right shift operation means shifting all elements of the array array list by one\n // position in the right direction. The last element of the array array list will be moved to\n // the starting position in the array array list i.e. 0th index. \n // If it is possible to obtain the sorted array array list by performing the above operation\n // then return true else return false.\n // If the given array array list is empty then return true.\n // Note: The given array list is guaranteed to have unique elements.\n // For Example:\n // >>> moveOneBall((new ArrayList(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l))))\n // (true)\n // Explanation: By performin 2 right shift operations, non-decreasing order can\n // be achieved for the given array array list.\n // >>> moveOneBall((new ArrayList(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l))))\n // (false)\n // Explanation:It is not possible to get non-decreasing order for the given\n // array array list by performing any number of right shift operations.\n public static boolean moveOneBall(ArrayList arr) {\n if (arr.size() == 0) {\n return true;\n }\n int n = arr.size();\n int count = 0;\n for (int i = 0; i < n; i++) {\n if (arr.get(i) > arr.get((i + 1) % n)) {\n count++;\n }\n }\n return count <= 1;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Find the shortest palindrome that begins with a supplied string.\n // Algorithm idea is simple:\n // - Find the longest postfix of supplied string that is a palindrome.\n // - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n // >>> makePalindrome((\"\"))\n // (\"\")\n // >>> makePalindrome((\"cat\"))\n // (\"catac\")\n // >>> makePalindrome((\"cata\"))\n // (\"catac\")\n public static String makePalindrome(String string) {\n int n = string.length();\n int i = 0;\n int j = n - 1;\n while (j >= 0 && string.charAt(i) == string.charAt(j)) {\n i++;\n j--;\n }\n if (i == n) {\n return string;\n }\n String suffix = string.substring(i);\n String prefix = new StringBuilder(suffix).reverse().toString();\n return prefix + makePalindrome(string.substring(0, i)) + suffix;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // In this problem, you will implement a function that takes two array lists of numbers,\n // and determines whether it is possible to perform an exchange of elements\n // between them to make lst1 an array array list of only even numbers.\n // There is no limit on the number of exchanged elements between lst1 and lst2.\n // If it is possible to exchange elements between the lst1 and lst2 to make\n // all the elements of lst1 to be even, return \"YES\".\n // Otherwise, return \"NO\".\n // For example:\n // >>> exchange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))\n // (\"YES\")\n // >>> exchange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l))))\n // (\"NO\")\n // It is assumed that the input array lists will be non-empty.\n public static String exchange(ArrayList lst1, ArrayList lst2) {\n // Count the number of odd numbers in lst1\n long oddCount = lst1.stream().filter(n -> n % 2 != 0).count();\n // Count the number of even numbers in lst2\n long evenCount = lst2.stream().filter(n -> n % 2 == 0).count();\n // If the number of odd numbers in lst1 is greater than the number of even numbers in lst2,\n // it is not possible to exchange elements to make all elements in lst1 even\n if (oddCount > evenCount) {\n return \"NO\";\n }\n return \"YES\";"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string representing a space separated lowercase letters, return a hash map\n // of the letter with the most repetition and containing the corresponding count.\n // If several letters have the same occurrence, return all of them.\n // Example:\n // >>> histogram((\"a b c\"))\n // (new HashMap(Map.of(\"a\", 1l, \"b\", 1l, \"c\", 1l)))\n // >>> histogram((\"a b b a\"))\n // (new HashMap(Map.of(\"a\", 2l, \"b\", 2l)))\n // >>> histogram((\"a b c a b\"))\n // (new HashMap(Map.of(\"a\", 2l, \"b\", 2l)))\n // >>> histogram((\"b b b b a\"))\n // (new HashMap(Map.of(\"b\", 4l)))\n // >>> histogram((\"\"))\n // (new HashMap())\n public static HashMap histogram(String test) {\n HashMap map = new HashMap<>();\n String[] words = test.split(\" \");\n for (String word : words) {\n map.put(word, map.getOrDefault(word, 0L) + 1);\n }\n long maxCount = map.values().stream().mapToLong(Long::longValue).max().orElse(0);\n HashMap result = new HashMap<>();\n for (Map.Entry entry : map.entrySet()) {\n if (entry.getValue() == maxCount) {\n result.put(entry.getKey(), entry.getValue());\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Task\n // We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n // then check if the result string is palindrome.\n // A string is called palindrome if it reads the same backward as forward.\n // You should return a pair containing the result string and true/false for the check.\n // Example\n // >>> reverseDelete((\"abcde\"), (\"ae\"))\n // (Pair.with(\"bcd\", false))\n // >>> reverseDelete((\"abcdef\"), (\"b\"))\n // (Pair.with(\"acdef\", false))\n // >>> reverseDelete((\"abcdedcba\"), (\"ab\"))\n // (Pair.with(\"cdedc\", true))\n public static Pair reverseDelete(String s, String c) {\n StringBuilder sb = new StringBuilder();\n for (char ch : s.toCharArray()) {\n if (c.indexOf(ch) == -1) {\n sb.append(ch);\n }\n }\n String result = sb.toString();\n boolean isPalindrome = result.equals(new StringBuilder(result).reverse().toString());\n return Pair.with(result, isPalindrome);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of strings, where each string consists of only digits, return an array array list.\n // Each element i of the output should be \"the number of odd elements in the\n // string i of the input.\" where all the i's should be replaced by the number\n // of odd digits in the i'th string of the input.\n // >>> oddCount((new ArrayList(Arrays.asList((String)\"1234567\"))))\n // (new ArrayList(Arrays.asList((String)\"the number of odd elements 4n the str4ng 4 of the 4nput.\")))\n // >>> oddCount((new ArrayList(Arrays.asList((String)\"3\", (String)\"11111111\"))))\n // (new ArrayList(Arrays.asList((String)\"the number of odd elements 1n the str1ng 1 of the 1nput.\", (String)\"the number of odd elements 8n the str8ng 8 of the 8nput.\")))\n public static ArrayList oddCount(ArrayList lst) {\n ArrayList result = new ArrayList();\n for (String str : lst) {\n int count = 0;\n for (char c : str.toCharArray()) {\n if (Character.getNumericValue(c) % 2 != 0) {\n count++;\n }\n }\n result.add(\"the number of odd elements \" + count + \"n the str\" + count + \"ng \" + count + \" of the \" + count + \"nput.\");\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of integers nums, find the minimum sum of any non-empty sub-array array list\n // of nums.\n // Example\n // >>> minSubArraySum((new ArrayList(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l))))\n // (1l)\n // >>> minSubArraySum((new ArrayList(Arrays.asList((long)-1l, (long)-2l, (long)-3l))))\n // (-6l)\n public static long minSubArraySum(ArrayList nums) {\n long minSum = nums.get(0);\n long currSum = nums.get(0);\n for (int i = 1; i < nums.size(); i++) {\n currSum = Math.min(nums.get(i), currSum + nums.get(i));\n minSum = Math.min(minSum, currSum);\n }\n return minSum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a rectangular grid of wells. Each row represents a single well,\n // and each 1 in a row represents a single unit of water.\n // Each well has a corresponding bucket that can be used to extract water from it, \n // and all buckets have the same capacity.\n // Your task is to use the buckets to empty the wells.\n // Output the number of times you need to lower the buckets.\n // Example 1:\n // >>> maxFill((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList)new ArrayList(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList)new ArrayList(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l))\n // (6l)\n // Example 2:\n // >>> maxFill((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList)new ArrayList(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList)new ArrayList(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList)new ArrayList(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l))\n // (5l)\n // Example 3:\n // >>> maxFill((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList)new ArrayList(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l))\n // (0l)\n // Constraints:\n // * all wells have the same length\n // * 1 <= grid.length <= 10^2\n // * 1 <= grid[:,1].length <= 10^2\n // * grid[i][j] -> 0 | 1\n // * 1 <= capacity <= 10\n public static long maxFill(ArrayList> grid, long capacity) {\n long count = 0;\n for (ArrayList row : grid) {\n long sum = 0;\n for (long val : row) {\n sum += val;\n }\n count += (sum + capacity - 1) / capacity;\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // In this Kata, you have to sort an array array list of non-negative integers according to\n // number of ones in their binary representation in ascending order.\n // For similar number of ones, sort based on decimal value.\n // It must be implemented like this:\n // >>> sortArray((new ArrayList(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))\n // >>> sortArray((new ArrayList(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l))))\n // (new ArrayList(Arrays.asList((long)-6l, (long)-5l, (long)-4l, (long)-3l, (long)-2l)))\n // >>> sortArray((new ArrayList(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l))))\n // (new ArrayList(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l)))\n public static ArrayList sortArray(ArrayList arr) {\n ArrayList> pairs = new ArrayList<>();\n for (Long num : arr) {\n int count = Long.bitCount(num);\n pairs.add(new Pair<>(num, count));\n }\n Collections.sort(pairs, (a, b) -> {\n int cmp = a.getValue1().compareTo(b.getValue1());\n if (cmp == 0) {\n return a.getValue0().compareTo(b.getValue0());\n }\n return cmp;\n });\n ArrayList result = new ArrayList<>();\n for (Pair pair : pairs) {\n result.add(pair.getValue0());\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string s and a natural number n, you have been tasked to implement \n // a function that returns an array array list of all words from string s that contain exactly \n // n consonants, in order these words appear in the string s.\n // If the string s is empty then the function should return an empty array list.\n // Note: you may assume the input string contains only letters and spaces.\n // Examples:\n // >>> selectWords((\"Mary had a little lamb\"), (4l))\n // (new ArrayList(Arrays.asList((String)\"little\")))\n // >>> selectWords((\"Mary had a little lamb\"), (3l))\n // (new ArrayList(Arrays.asList((String)\"Mary\", (String)\"lamb\")))\n // >>> selectWords((\"simple white space\"), (2l))\n // (new ArrayList(Arrays.asList()))\n // >>> selectWords((\"Hello world\"), (4l))\n // (new ArrayList(Arrays.asList((String)\"world\")))\n // >>> selectWords((\"Uncle sam\"), (3l))\n // (new ArrayList(Arrays.asList((String)\"Uncle\")))\n public static ArrayList selectWords(String s, long n) {\n ArrayList result = new ArrayList();\n String[] words = s.split(\" \");\n for (String word : words) {\n long consonantCount = word.chars().filter(c -> !\"aeiouAEIOU\".contains(String.valueOf((char)c))).count();\n if (consonantCount == n) {\n result.add(word);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a word. Your task is to find the closest vowel that stands between \n // two consonants from the right side of the word (case sensitive).\n // Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n // find any vowel met the above condition. \n // You may assume that the given string contains English letter only.\n // Example:\n // >>> getClosestVowel((\"yogurt\"))\n // (\"u\")\n // >>> getClosestVowel((\"FULL\"))\n // (\"U\")\n // >>> getClosestVowel((\"quick\"))\n // (\"\")\n // >>> getClosestVowel((\"ab\"))\n // (\"\")\n public static String getClosestVowel(String word) {\n String vowels = \"aeiouAEIOU\";\n int n = word.length();\n int i = n - 1;\n while (i >= 0) {\n if (vowels.indexOf(word.charAt(i)) != -1) {\n int j = i - 1;\n while (j >= 0) {\n if (vowels.indexOf(word.charAt(j)) == -1) {\n j--;\n } else {\n return Character.toString(word.charAt(j));\n }\n }\n }\n i--;\n }\n return \"\";"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given an array array list of two strings, both strings consist of open\n // parentheses '(' or close parentheses ')' only.\n // Your job is to check if it is possible to concatenate the two strings in\n // some order, that the resulting string will be good.\n // A string S is considered to be good if and only if all parentheses in S\n // are balanced. For example: the string '(())()' is good, while the string\n // '())' is not.\n // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n // Examples:\n // >>> matchParens((new ArrayList(Arrays.asList((String)\"()(\", (String)\")\"))))\n // (\"Yes\")\n // >>> matchParens((new ArrayList(Arrays.asList((String)\")\", (String)\")\"))))\n // (\"No\")\n public static String matchParens(ArrayList lst) {\n String s1 = lst.get(0);\n String s2 = lst.get(1);\n int count = 0;\n for (int i = 0; i < s1.length(); i++) {\n if (s1.charAt(i) == '(') {\n count++;\n } else {\n count--;\n }\n }\n for (int i = 0; i < s2.length(); i++) {\n if (s2.charAt(i) == '(') {\n count++;\n } else {\n count--;\n }\n }\n if (count == 0) {\n return \"Yes\";\n } else {\n return \"No\";\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Input are two strings a and b consisting only of 1s and 0s.\n // Perform binary XOR on these inputs and return result also as a string.\n // >>> stringXor((\"010\"), (\"110\"))\n // (\"100\")\n public static String stringXor(String a, String b) {\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < a.length(); i++) {\n if (a.charAt(i) == b.charAt(i)) {\n result.append(\"0\");\n } else {\n result.append(\"1\");\n }\n }\n return result.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list arr of integers and a positive integer k, return a sorted array list \n // of length k with the maximum k numbers in arr.\n // Example 1:\n // >>> maximum((new ArrayList(Arrays.asList((long)-3l, (long)-4l, (long)5l))), (3l))\n // (new ArrayList(Arrays.asList((long)-4l, (long)-3l, (long)5l)))\n // Example 2:\n // >>> maximum((new ArrayList(Arrays.asList((long)4l, (long)-4l, (long)4l))), (2l))\n // (new ArrayList(Arrays.asList((long)4l, (long)4l)))\n // Example 3:\n // >>> maximum((new ArrayList(Arrays.asList((long)-3l, (long)2l, (long)1l, (long)2l, (long)-1l, (long)-2l, (long)1l))), (1l))\n // (new ArrayList(Arrays.asList((long)2l)))\n // Note:\n // 1. The length of the array array list will be in the range of [1, 1000].\n // 2. The elements in the array array list will be in the range of [-1000, 1000].\n // 3. 0 <= k <= len(arr)\n public static ArrayList maximum(ArrayList arr, long k) {\n // Sort the array in descending order\n Collections.sort(arr, Collections.reverseOrder());\n // Create a new array list to store the maximum k numbers\n ArrayList result = new ArrayList<>();\n // Add the first k numbers to the result array list\n for (int i = 0; i < k; i++) {\n result.add(arr.get(i));\n }\n // Sort the result array list in ascending order\n Collections.sort(result);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a non-empty array list of integers, return the sum of all of the odd elements that are in even positions.\n // Examples\n // >>> solution((new ArrayList(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l))))\n // (12l)\n // >>> solution((new ArrayList(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l))))\n // (9l)\n // >>> solution((new ArrayList(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l))))\n // (0l)\n public static long solution(ArrayList lst) {\n long sum = 0;\n for (int i = 0; i < lst.size(); i += 2) {\n if (lst.get(i) % 2 != 0) {\n sum += lst.get(i);\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a non-empty array array list of integers arr and an integer k, return\n // the sum of the elements with at most two digits from the first k elements of arr.\n // Example:\n // >>> addElements((new ArrayList(Arrays.asList((long)111l, (long)21l, (long)3l, (long)4000l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l))), (4l))\n // (24l)\n // Constraints:\n // 1. 1 <= len(arr) <= 100\n // 2. 1 <= k <= len(arr)\n public static long addElements(ArrayList arr, long k) {\n long sum = 0;\n for (int i = 0; i < k; i++) {\n long num = arr.get(i);\n if (num < 100) {\n sum += num;\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence.\n // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n // as follows: start with any positive integer n. Then each term is obtained from the \n // previous term as follows: if the previous term is even, the next term is one half of \n // the previous term. If the previous term is odd, the next term is 3 times the previous\n // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n // Note: \n // 1. Collatz(1) is [1].\n // 2. returned array list sorted in increasing order.\n // For example:\n // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n // >>> getOddCollatz((5l))\n // (new ArrayList(Arrays.asList((long)1l, (long)5l)))\n public static ArrayList getOddCollatz(long n) {\n ArrayList result = new ArrayList();\n while (n != 1) {\n if (n % 2 == 1) {\n result.add(n);\n }\n if (n % 2 == 0) {\n n = n / 2;\n } else {\n n = 3 * n + 1;\n }\n }\n result.add(1L);\n Collections.sort(result);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You have to write a function which validates a given date string and\n // returns true if the date is valid otherwise false.\n // The date is valid if all of the following rules are satisfied:\n // 1. The date string is not empty.\n // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n // 3. The months should not be less than 1 or higher than 12.\n // 4. The date should be in the format: mm-dd-yyyy\n // >>> validDate((\"03-11-2000\"))\n // (true)\n // >>> validDate((\"15-01-2012\"))\n // (false)\n // >>> validDate((\"04-0-2040\"))\n // (false)\n // >>> validDate((\"06-04-2020\"))\n // (true)\n // >>> validDate((\"06/04/2020\"))\n // (false)\n public static boolean validDate(String date) {\n if (date.isEmpty()) {\n return false;\n }\n String[] parts = date.split(\"-\");\n if (parts.length != 3) {\n return false;\n }\n int month = Integer.parseInt(parts[0]);\n int day = Integer.parseInt(parts[1]);\n int year = Integer.parseInt(parts[2]);\n if (month < 1 || month > 12) {\n return false;\n }\n if (day < 1 || day > 31) {\n return false;\n }\n if (month == 2) {\n if (day > 29) {\n return false;\n }\n if (day == 29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) {\n return false;\n }\n } else if (month == 4 || month == 6 || month == 9 || month == 11) {\n if (day > 30) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of numbers, return whether or not they are sorted\n // in ascending order. If array list has more than 1 duplicate of the same\n // number, return false. Assume no negative numbers and only integers.\n // Examples\n // >>> isSorted((new ArrayList(Arrays.asList((long)5l))))\n // (true)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l))))\n // (true)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l))))\n // (false)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l))))\n // (true)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l))))\n // (true)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l))))\n // (false)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l))))\n // (true)\n // >>> isSorted((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l))))\n // (false)\n public static boolean isSorted(ArrayList lst) {\n for (int i = 0; i < lst.size() - 1; i++) {\n if (lst.get(i) > lst.get(i + 1)) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given two intervals,\n // where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n // The given intervals are closed which means that the interval (start, end)\n // includes both start and end.\n // For each given interval, it is assumed that its start is less or equal its end.\n // Your task is to determine whether the length of intersection of these two \n // intervals is a prime number.\n // Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n // which its length is 1, which not a prime number.\n // If the length of the intersection is a prime number, return \"YES\",\n // otherwise, return \"NO\".\n // If the two intervals don't intersect, return \"NO\".\n // [input/output] samples:\n // >>> intersection((Pair.with(1l, 2l)), (Pair.with(2l, 3l)))\n // (\"NO\")\n // >>> intersection((Pair.with(-1l, 1l)), (Pair.with(0l, 4l)))\n // (\"NO\")\n // >>> intersection((Pair.with(-3l, -1l)), (Pair.with(-5l, 5l)))\n // (\"YES\")\n public static String intersection(Pair interval1, Pair interval2) {\n long start1 = interval1.getValue0();\n long end1 = interval1.getValue1();\n long start2 = interval2.getValue0();\n long end2 = interval2.getValue1();\n long start = Math.max(start1, start2);\n long end = Math.min(end1, end2);\n long length = end - start + 1;\n if (length <= 1) {\n return \"NO\";\n }\n for (long i = 2; i * i <= length; i++) {\n if (length % i == 0) {\n return \"NO\";\n }\n }\n return \"YES\";"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given an array array list arr of integers and you need to return\n // sum of magnitudes of integers multiplied by product of all signs\n // of each number in the array array list, represented by 1, -1 or 0.\n // Note: return null for empty arr.\n // Example:\n // >>> prodSigns((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)2l, (long)-4l))))\n // Optional.of(9l)\n // >>> prodSigns((new ArrayList(Arrays.asList((long)0l, (long)1l))))\n // Optional.of(0l)\n // >>> prodSigns((new ArrayList(Arrays.asList())))\n // Optional.empty()\n public static Optional prodSigns(ArrayList arr) {\n if (arr.isEmpty()) {\n return Optional.empty();\n }\n long sum = 0;\n long product = 1;\n for (long num : arr) {\n sum += Math.abs(num);\n if (num < 0) {\n product *= -1;\n } else if (num == 0) {\n product *= 0;\n }\n }\n return Optional.of(sum * product);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n // each cell of the grid contains a value. Every integer in the range [1, N * N]\n // inclusive appears exactly once on the cells of the grid.\n // You have to find the minimum path of length k in the grid. You can start\n // from any cell, and in each step you can move to any of the neighbor cells,\n // in other words, you can go to cells which share an edge with you current\n // cell.\n // Please note that a path of length k means visiting exactly k cells (not\n // necessarily distinct).\n // You CANNOT go off the grid.\n // A path A (of length k) is considered less than a path B (of length k) if\n // after making the ordered array lists of the values on the cells that A and B go\n // through (let's call them lst_A and lst_B), lst_A is lexicographically less\n // than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n // lst_A[j] = lst_B[j].\n // It is guaranteed that the answer is unique.\n // Return an ordered array list of the values on the cells that the minimum path go through.\n // Examples: \n // >>> minPath((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l)), (ArrayList)new ArrayList(Arrays.asList((long)4l, (long)5l, (long)6l)), (ArrayList)new ArrayList(Arrays.asList((long)7l, (long)8l, (long)9l))))), (3l))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)1l)))\n // >>> minPath((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)5l, (long)9l, (long)3l)), (ArrayList)new ArrayList(Arrays.asList((long)4l, (long)1l, (long)6l)), (ArrayList)new ArrayList(Arrays.asList((long)7l, (long)8l, (long)2l))))), (1l))\n // (new ArrayList(Arrays.asList((long)1l)))\n public static ArrayList minPath(ArrayList> grid, long k) {\n int n = grid.size();\n ArrayList>> adj = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n adj.add(new ArrayList<>());\n for (int j = 0; j < n; j++) {\n if (i > 0) adj.get(i * n + j).add(new Pair<>(i - 1, j));\n if (i < n - 1) adj.get(i * n + j).add(new Pair<>(i + 1, j));\n if (j > 0) adj.get(i * n + j).add(new Pair<>(i, j - 1));\n if (j < n - 1) adj.get(i * n + j).add(new Pair<>(i, j + 1));\n }\n }\n ArrayList ans = new ArrayList<>();\n PriorityQueue> pq = new PriorityQueue<>(Comparator.comparing(Pair::getValue0));\n pq.add(new Pair<>(0L, 0));\n while (!pq.isEmpty()) {\n Pair cur = pq.poll();\n int i = cur.getValue1() / n, j = cur.getValue1() % n;\n if (ans.size() == k) break;\n ans.add(grid.get(i).get(j));\n for (Pair next : adj.get(i * n + j)) {\n int ni = next.getValue0(), nj = next.getValue1();\n pq.add(new Pair<>(cur.getValue0() + Math.abs(grid.get(i).get(j) - grid.get(ni).get(nj)), ni * n + nj));\n }\n }\n return ans;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Out of array list of strings, return the longest one. Return the first one in case of multiple\n // strings of the same length. Return null in case the input array list is empty.\n // >>> longest((new ArrayList(Arrays.asList())))\n // Optional.empty()\n // >>> longest((new ArrayList(Arrays.asList((String)\"a\", (String)\"b\", (String)\"c\"))))\n // Optional.of(\"a\")\n // >>> longest((new ArrayList(Arrays.asList((String)\"a\", (String)\"bb\", (String)\"ccc\"))))\n // Optional.of(\"ccc\")\n public static Optional longest(ArrayList strings) {\n return strings.stream().max(Comparator.comparing(String::length)).map(Optional::of).orElse(Optional.empty());"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n // the last couple centuries. However, what people don't know is Tribonacci sequence.\n // Tribonacci sequence is defined by the recurrence:\n // tri(1) = 3\n // tri(n) = 1 + n / 2, if n is even.\n // tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n // For example:\n // tri(2) = 1 + (2 / 2) = 2\n // tri(4) = 3\n // tri(3) = tri(2) + tri(1) + tri(4)\n // = 2 + 3 + 3 = 8 \n // You are given a non-negative integer number n, you have to a return an array array list of the \n // first n + 1 numbers of the Tribonacci sequence.\n // Examples:\n // >>> tri((3l))\n // (new ArrayList(Arrays.asList((long)1l, (long)3l, (long)2l, (long)8l)))\n public static ArrayList tri(long n) {\n ArrayList result = new ArrayList();\n result.add(1L);\n result.add(3L);\n for (int i = 2; i <= n; i++) {\n if (i % 2 == 0) {\n result.add(1L + i / 2);\n } else {\n result.add(result.get(i - 2) + result.get(i - 1) + result.get(i));\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer n, return the product of the odd digits.\n // Return 0 if all digits are even.\n // For example:\n // >>> digits((1l))\n // (1l)\n // >>> digits((4l))\n // (0l)\n // >>> digits((235l))\n // (15l)\n public static long digits(long n) {\n long product = 1;\n while (n > 0) {\n long digit = n % 10;\n if (digit % 2 != 0) {\n product *= digit;\n }\n n /= 10;\n }\n return product;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function that takes a string as input which contains only square brackets.\n // The function should return true if and only if there is a valid subsequence of brackets \n // where at least one bracket in the subsequence is nested.\n // >>> isNested((\"[[]]\"))\n // (true)\n // >>> isNested((\"[]]]]]]][[[[[]\"))\n // (false)\n // >>> isNested((\"[][]\"))\n // (false)\n // >>> isNested((\"[]\"))\n // (false)\n // >>> isNested((\"[[][]]\"))\n // (true)\n // >>> isNested((\"[[]][[\"))\n // (true)\n public static boolean isNested(String string) {\n Stack stack = new Stack<>();\n for (int i = 0; i < string.length(); i++) {\n char c = string.charAt(i);\n if (c == '[') {\n stack.push(c);\n } else if (c == ']') {\n if (stack.isEmpty()) {\n return false;\n }\n stack.pop();\n }\n }\n return !stack.isEmpty();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given an array array list of numbers.\n // You need to return the sum of squared numbers in the given array list,\n // round each element in the array list to the upper int(Ceiling) first.\n // Examples:\n // >>> lst((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f))))\n // (14l)\n // >>> lst((new ArrayList(Arrays.asList((float)1.0f, (float)4.0f, (float)9.0f))))\n // (98l)\n // >>> lst((new ArrayList(Arrays.asList((float)1.0f, (float)3.0f, (float)5.0f, (float)7.0f))))\n // (84l)\n // >>> lst((new ArrayList(Arrays.asList((float)1.4f, (float)4.2f, (float)0.0f))))\n // (29l)\n // >>> lst((new ArrayList(Arrays.asList((float)-2.4f, (float)1.0f, (float)1.0f))))\n // (6l)\n public static long sumSquares(ArrayList lst) {\n long sum = 0;\n for (float num : lst) {\n sum += Math.round(Math.pow(num, 2));\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function that returns true if the last character\n // of a given string is an alphabetical character and is not\n // a part of a word, and false otherwise.\n // Note: \"word\" is a group of characters separated by space.\n // Examples:\n // >>> checkIfLastCharIsALetter((\"apple pie\"))\n // (false)\n // >>> checkIfLastCharIsALetter((\"apple pi e\"))\n // (true)\n // >>> checkIfLastCharIsALetter((\"apple pi e \"))\n // (false)\n // >>> checkIfLastCharIsALetter((\"\"))\n // (false)\n public static boolean checkIfLastCharIsALetter(String txt) {\n // Check if the string is empty\n if (txt.isEmpty()) {\n return false;\n }\n // Split the string into words\n String[] words = txt.split(\" \");\n // Get the last word\n String lastWord = words[words.length - 1];\n // Check if the last character of the last word is an alphabetical character\n char lastChar = lastWord.charAt(lastWord.length() - 1);\n if (Character.isLetter(lastChar)) {\n // Check if the last character is not a part of a word\n if (lastWord.length() == 1) {\n return true;\n } else {\n return false;\n }\n } else {\n return false;\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function which returns the largest index of an element which\n // is not greater than or equal to the element immediately preceding it. If\n // no such element exists then return -1. The given array array list will not contain\n // duplicate values.\n // Examples:\n // >>> canArrange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l))))\n // (3l)\n // >>> canArrange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (-1l)\n public static long canArrange(ArrayList arr) {\n long maxIndex = -1;\n for (int i = 1; i < arr.size(); i++) {\n if (arr.get(i) < arr.get(i-1)) {\n maxIndex = i-1;\n }\n }\n return maxIndex;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function that returns a pair (a, b), where 'a' is\n // the largest of negative integers, and 'b' is the smallest\n // of positive integers in an array array list.\n // If there is no negative or positive integers, return them as null.\n // Examples:\n // >>> largestSmallestIntegers((new ArrayList(Arrays.asList((long)2l, (long)4l, (long)1l, (long)3l, (long)5l, (long)7l))))\n // Pair.with(Optional.of(Optional.empty()), Optional.of(1l))\n // >>> largestSmallestIntegers((new ArrayList(Arrays.asList())))\n // Pair.with(Optional.of(Optional.empty()), Optional.of(Optional.empty()))\n // >>> largestSmallestIntegers((new ArrayList(Arrays.asList((long)0l))))\n // Pair.with(Optional.of(Optional.empty()), Optional.of(Optional.empty()))\n public static Pair, Optional> largestSmallestIntegers(ArrayList lst) {\n Optional largestNegative = lst.stream()\n .filter(n -> n < 0)\n .max(Comparator.naturalOrder());\n Optional smallestPositive = lst.stream()\n .filter(n -> n > 0)\n .min(Comparator.naturalOrder());\n return Pair.with(largestNegative, smallestPositive);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n // Example\n // >>> isEqualToSumEven((4l))\n // (false)\n // >>> isEqualToSumEven((6l))\n // (false)\n // >>> isEqualToSumEven((8l))\n // (true)\n public static boolean isEqualToSumEven(long n) {\n if (n % 2 != 0) {\n return false;\n }\n long sum = 0;\n for (int i = 1; i <= 4; i++) {\n sum += i * 2;\n }\n return sum == n;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // The Brazilian factorial is defined as:\n // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n // where n > 0\n // For example:\n // >>> specialFactorial((4l))\n // (288l)\n // The function will receive an integer as input and should return the special\n // factorial of this integer.\n public static long specialFactorial(long n) {\n long result = 1;\n for (long i = n; i > 0; i--) {\n result *= i;\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return a greatest common divisor of two integers a and b\n // >>> greatestCommonDivisor((3l), (5l))\n // (1l)\n // >>> greatestCommonDivisor((25l), (15l))\n // (5l)\n public static long greatestCommonDivisor(long a, long b) {\n if (b == 0) {\n return a;\n }\n return greatestCommonDivisor(b, a % b);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string text, replace all spaces in it with underscores, \n // and if a string has more than 2 consecutive spaces, \n // then replace all consecutive spaces with - \n // >>> fixSpaces((\" Example\"))\n // (\"Example\")\n // >>> fixSpaces((\" Example 1\"))\n // (\"Example_1\")\n // >>> fixSpaces((\" Example 2\"))\n // (\"_Example_2\")\n // >>> fixSpaces((\" Example 3\"))\n // (\"_Example-3\")\n public static String fixSpaces(String text) {\n String[] words = text.trim().split(\"\\\\s+\");\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < words.length; i++) {\n if (i > 0) {\n sb.append(\"_\");\n }\n sb.append(words[i]);\n }\n String result = sb.toString();\n if (result.contains(\"__\")) {\n result = result.replaceAll(\"__\", \"-\");\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function which takes a string representing a file's name, and returns\n // 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n // A file's name is considered to be valid if and only if all the following conditions \n // are met:\n // - There should not be more than three digits ('0'-'9') in the file's name.\n // - The file's name contains exactly one dot '.'\n // - The substring before the dot should not be empty, and it starts with a letter from \n // the latin alphapet ('a'-'z' and 'A'-'Z').\n // - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n // Examples:\n // >>> fileNameCheck((\"example.txt\"))\n // (\"Yes\")\n // >>> fileNameCheck((\"1example.dll\"))\n // (\"No\")\n public static String fileNameCheck(String file_name) {\n // Check if the file's name contains more than three digits\n int digit_count = 0;\n for (int i = 0; i < file_name.length(); i++) {\n if (Character.isDigit(file_name.charAt(i))) {\n digit_count++;\n }\n }\n if (digit_count > 3) {\n return \"No\";\n }\n\n // Check if the file's name contains exactly one dot\n int dot_count = 0;\n for (int i = 0; i < file_name.length(); i++) {\n if (file_name.charAt(i) == '.') {\n dot_count++;\n }\n }\n if (dot_count != 1) {\n return \"No\";\n }\n\n // Check if the substring before the dot is not empty and starts with a letter\n String[] parts = file_name.split(\"\\\\.\");\n String before_dot = parts[0];\n if (before_dot.isEmpty() || !Character.isLetter(before_dot.charAt(0))) {\n return \"No\";\n }\n\n // Check if the substring after the dot is one of the allowed extensions\n String after_dot = parts[1];\n if (!after_dot.equals(\"txt\") && !after_dot.equals(\"exe\") && !after_dot.equals(\"dll\")) {\n return \"No\";\n }\n\n // If all conditions are met, return \"Yes\"\n return \"Yes\";"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // \"\n // This function will take an array array list of integers. For all entries in the array list, the function shall square the integer entry if its index is a \n // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n // change the entries in the array list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n // Examples:\n // >>> lst\n // (long)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))\n // >>> lst\n // (long)new ArrayList(Arrays.asList())\n // >>> lst\n // (long)new ArrayList(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l))\n public static long sumSquares(ArrayList lst) {\n long sum = 0;\n for (int i = 0; i < lst.size(); i++) {\n if (i % 3 == 0) {\n sum += Math.pow(lst.get(i), 2);\n } else if (i % 4 == 0) {\n sum += Math.pow(lst.get(i), 3);\n } else {\n sum += lst.get(i);\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a string representing a sentence,\n // the sentence contains some words separated by a space,\n // and you have to return a string that contains the words from the original sentence,\n // whose lengths are prime numbers,\n // the order of the words in the new string should be the same as the original one.\n // Example 1:\n // >>> wordsInSentence((\"This is a test\"))\n // (\"is\")\n // Example 2:\n // >>> wordsInSentence((\"lets go for swimming\"))\n // (\"go for\")\n // Constraints:\n // * 1 <= len(sentence) <= 100\n // * sentence contains only letters\n public static String wordsInSentence(String sentence) {\n String[] words = sentence.split(\" \");\n List primeWords = new ArrayList<>();\n for (String word : words) {\n if (isPrime(word.length())) {\n primeWords.add(word);\n }\n }\n return String.join(\" \", primeWords);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Your task is to implement a function that will simplify the expression\n // x * n. The function returns true if x * n evaluates to a whole number and false\n // otherwise. Both x and n, are string representation of a fraction, and have the following format,\n // / where both numerator and denominator are positive whole numbers.\n // You can assume that x, and n are valid fractions, and do not have zero as denominator.\n // >>> simplify((\"1/5\"), (\"5/1\"))\n // (true)\n // >>> simplify((\"1/6\"), (\"2/1\"))\n // (false)\n // >>> simplify((\"7/10\"), (\"10/2\"))\n // (false)\n public static boolean simplify(String x, String n) {\n String[] x_parts = x.split(\"/\");\n String[] n_parts = n.split(\"/\");\n int x_num = Integer.parseInt(x_parts[0]);\n int x_den = Integer.parseInt(x_parts[1]);\n int n_num = Integer.parseInt(n_parts[0]);\n int n_den = Integer.parseInt(n_parts[1]);\n int result_num = x_num * n_num;\n int result_den = x_den * n_den;\n return result_num % result_den == 0;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function which sorts the given array list of integers\n // in ascending order according to the sum of their digits.\n // Note: if there are several items with similar sum of their digits,\n // order them based on their index in original array list.\n // For example:\n // >>> orderByPoints((new ArrayList(Arrays.asList((long)1l, (long)11l, (long)-1l, (long)-11l, (long)-12l))))\n // (new ArrayList(Arrays.asList((long)-1l, (long)-11l, (long)1l, (long)-12l, (long)11l)))\n // >>> orderByPoints((new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n public static ArrayList orderByPoints(ArrayList nums) {\n ArrayList> pairs = new ArrayList<>();\n for (int i = 0; i < nums.size(); i++) {\n long num = nums.get(i);\n int sum = 0;\n while (num != 0) {\n sum += num % 10;\n num /= 10;\n }\n pairs.add(new Pair<>(nums.get(i), sum));\n }\n Collections.sort(pairs, (a, b) -> {\n if (a.getValue1() != b.getValue1()) {\n return a.getValue1() - b.getValue1();\n } else {\n return nums.indexOf(a.getValue0()) - nums.indexOf(b.getValue0());\n }\n });\n ArrayList result = new ArrayList<>();\n for (Pair pair : pairs) {\n result.add(pair.getValue0());\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that takes an array array list of numbers as input and returns \n // the number of elements in the array array list that are greater than 10 and both \n // first and last digits of a number are odd (1, 3, 5, 7, 9).\n // For example:\n // >>> specialFilter((new ArrayList(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l))))\n // (1l)\n // >>> specialFilter((new ArrayList(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l))))\n // (2l)\n public static long specialFilter(ArrayList nums) {\n return nums.stream()\n .filter(num -> num > 10 && num % 2 != 0 && (num % 10) % 2 != 0)\n .count();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a positive integer n. You have to create an integer array array list a of length n.\n // For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n // and a[i] + a[j] + a[k] is a multiple of 3.\n // Example :\n // >>> getMaxTriples((5l))\n // (1l)\n // Explanation: \n // a = [1, 3, 7, 13, 21]\n // The only valid triple is (1, 7, 13).\n public static long getMaxTriples(long n) {\n long count = 0;\n for (long i = 1; i <= n; i++) {\n for (long j = i + 1; j <= n; j++) {\n for (long k = j + 1; k <= n; k++) {\n long sum = i * i - i + 1 + j * j - j + 1 + k * k - k + 1;\n if (sum % 3 == 0) {\n count++;\n }\n }\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // There are eight planets in our solar system: the closerst to the Sun \n // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n // Uranus, Neptune.\n // Write a function that takes two planet names as strings planet1 and planet2. \n // The function should return a pair containing all planets whose orbits are \n // located between the orbit of planet1 and the orbit of planet2, sorted by \n // the proximity to the sun. \n // The function should return an empty pair if planet1 or planet2\n // are not correct planet names. \n // Examples\n // >>> bf((\"Jupiter\"), (\"Neptune\"))\n // (new ArrayList(Arrays.asList((String)\"Saturn\", (String)\"Uranus\")))\n // >>> bf((\"Earth\"), (\"Mercury\"))\n // (ArrayList(\"Venus\"))\n // >>> bf((\"Mercury\"), (\"Uranus\"))\n // (new ArrayList(Arrays.asList((String)\"Venus\", (String)\"Earth\", (String)\"Mars\", (String)\"Jupiter\", (String)\"Saturn\")))\n public static ArrayList bf(String planet1, String planet2) {\n ArrayList planets = new ArrayList(Arrays.asList(\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\"));\n int index1 = planets.indexOf(planet1);\n int index2 = planets.indexOf(planet2);\n if (index1 == -1 || index2 == -1) {\n return new ArrayList();\n }\n if (index1 > index2) {\n int temp = index1;\n index1 = index2;\n index2 = temp;\n }\n ArrayList result = new ArrayList();\n for (int i = index1 + 1; i < index2; i++) {\n result.add(planets.get(i));\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that accepts an array array list of strings as a parameter,\n // deletes the strings that have odd lengths from it,\n // and returns the resulted array list with a sorted order,\n // The array list is always an array array list of strings and never an array array list of numbers,\n // and it may contain duplicates.\n // The order of the array list should be ascending by length of each word, and you\n // should return the array list sorted by that rule.\n // If two words have the same length, sort the array list alphabetically.\n // The function should return an array array list of strings in sorted order.\n // You may assume that all words will have the same length.\n // For example:\n // >>> listSort((new ArrayList(Arrays.asList((String)\"aa\", (String)\"a\", (String)\"aaa\"))))\n // (new ArrayList(Arrays.asList((String)\"aa\")))\n // >>> listSort((new ArrayList(Arrays.asList((String)\"ab\", (String)\"a\", (String)\"aaa\", (String)\"cd\"))))\n // (new ArrayList(Arrays.asList((String)\"ab\", (String)\"cd\")))\n public static ArrayList sortedListSum(ArrayList lst) {\n // filter out the strings with odd lengths\n ArrayList filteredList = lst.stream()\n .filter(s -> s.length() % 2 == 0)\n .collect(Collectors.toCollection(ArrayList::new));\n\n // sort the filtered list by length and then alphabetically\n Collections.sort(filteredList, Comparator.comparing(String::length).thenComparing(String::compareTo));\n\n return filteredList;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return array list of all prefixes from shortest to longest of the input string\n // >>> allPrefixes((\"abc\"))\n // (new ArrayList(Arrays.asList((String)\"a\", (String)\"ab\", (String)\"abc\")))\n public static ArrayList allPrefixes(String string) {\n ArrayList prefixes = new ArrayList();\n for (int i = 1; i <= string.length(); i++) {\n prefixes.add(string.substring(0, i));\n }\n return prefixes;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // A simple program which should return the value of x if n is \n // a prime number and should return the value of y otherwise.\n // Examples:\n // >>> xOrY((7l), (34l), (12l))\n // (34l)\n // >>> xOrY((15l), (8l), (5l))\n // (5l)\n public static long xOrY(long n, long x, long y) {\n if (isPrime(n)) {\n return x;\n } else {\n return y;\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of numbers, return the sum of squares of the numbers\n // in the array list that are odd. Ignore numbers that are negative or not integers.\n // >>> doubleTheDifference((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)2l, (long)0l))))\n // (10l)\n // >>> doubleTheDifference((new ArrayList(Arrays.asList((long)-1l, (long)-2l, (long)0l))))\n // (0l)\n // >>> doubleTheDifference((new ArrayList(Arrays.asList((long)9l, (long)-2l))))\n // (81l)\n // >>> doubleTheDifference((new ArrayList(Arrays.asList((long)0l))))\n // (0l)\n // If the input array list is empty, return 0.\n public static long doubleTheDifference(ArrayList lst) {\n long sum = 0;\n for (Float num : lst) {\n if (num.intValue() % 2 != 0 && num >= 0) {\n sum += num.intValue() * num.intValue();\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // I think we all remember that feeling when the result of some long-awaited\n // event is finally known. The feelings and thoughts you have at that moment are\n // definitely worth noting down and comparing.\n // Your task is to determine if a person correctly guessed the results of a number of matches.\n // You are given two array array lists of scores and guesses of equal length, where each index shows a match. \n // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly,\n // the value is 0, and if not, the value is the absolute difference between the guess and the score.\n // example:\n // >>> compare((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l))))\n // (new ArrayList(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l)))\n // >>> compare((new ArrayList(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l))))\n // (new ArrayList(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l)))\n public static ArrayList compare(ArrayList game, ArrayList guess) {\n ArrayList result = new ArrayList();\n for (int i = 0; i < game.size(); i++) {\n long diff = Math.abs(game.get(i) - guess.get(i));\n result.add(diff);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You will be given the name of a class (a string) and an array array list of extensions.\n // The extensions are to be used to load additional classes to the class. The\n // strength of the extension is as follows: Let CAP be the number of the uppercase\n // letters in the extension's name, and let SM be the number of lowercase letters \n // in the extension's name, the strength is given by the fraction CAP - SM. \n // You should find the strongest extension and return a string in this \n // format: ClassName.StrongestExtensionName.\n // If there are two or more extensions with the same strength, you should\n // choose the one that comes first in the array list.\n // For example, if you are given \"Slices\" as the class and an array array list of the\n // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n // (its strength is -1).\n // Example:\n // >>> StrongestExtension((\"my_class\"), (new ArrayList(Arrays.asList((String)\"AA\", (String)\"Be\", (String)\"CC\"))))\n // (\"my_class.AA\")\n public static String StrongestExtension(String class_name, ArrayList extensions) {\n // Your code here"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n // >>> cycpatternCheck((\"abcd\"), (\"abd\"))\n // (false)\n // >>> cycpatternCheck((\"hello\"), (\"ell\"))\n // (true)\n // >>> cycpatternCheck((\"whassup\"), (\"psus\"))\n // (false)\n // >>> cycpatternCheck((\"abab\"), (\"baa\"))\n // (true)\n // >>> cycpatternCheck((\"efef\"), (\"eeff\"))\n // (false)\n // >>> cycpatternCheck((\"himenss\"), (\"simen\"))\n // (true)\n public static boolean cycpatternCheck(String a, String b) {\n String concatenated = a + a;\n return concatenated.contains(b);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an integer. return a pair that has the number of even and odd digits respectively.\n // Example:\n // >>> evenOddCount((-12l))\n // (Pair.with(1l, 1l))\n // >>> evenOddCount((123l))\n // (Pair.with(1l, 2l))\n public static Pair evenOddCount(long num) {\n long evenCount = 0;\n long oddCount = 0;\n long n = Math.abs(num);\n while (n > 0) {\n long digit = n % 10;\n if (digit % 2 == 0) {\n evenCount++;\n } else {\n oddCount++;\n }\n n /= 10;\n }\n return Pair.with(evenCount, oddCount);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer, obtain its roman numeral equivalent as a string,\n // and return it in lowercase.\n // Restrictions: 1 <= num <= 1000\n // Examples:\n // >>> intToMiniRoman((19l))\n // (\"xix\")\n // >>> intToMiniRoman((152l))\n // (\"clii\")\n // >>> intToMiniRoman((426l))\n // (\"cdxxvi\")\n public static String intToMiniRoman(long number) {\n if (number < 1 || number > 1000) {\n throw new IllegalArgumentException(\"Number must be between 1 and 1000\");\n }\n StringBuilder result = new StringBuilder();\n while (number >= 100) {\n result.append(\"c\");\n number -= 100;\n }\n while (number >= 90) {\n result.append(\"xc\");\n number -= 90;\n }\n while (number >= 50) {\n result.append(\"l\");\n number -= 50;\n }\n while (number >= 40) {\n result.append(\"xl\");\n number -= 40;\n }\n while (number >= 10) {\n result.append(\"x\");\n number -= 10;\n }\n while (number >= 9) {\n result.append(\"ix\");\n number -= 9;\n }\n while (number >= 5) {\n result.append(\"v\");\n number -= 5;\n }\n while (number >= 4) {\n result.append(\"iv\");\n number -= 4;\n }\n while (number >= 1) {\n result.append(\"i\");\n number -= 1;\n }\n return result.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given the lengths of the three sides of a triangle. Return true if the three\n // sides form a right-angled triangle, false otherwise.\n // A right-angled triangle is a triangle in which one angle is right angle or \n // 90 degree.\n // Example:\n // >>> rightAngleTriangle((3l), (4l), (5l))\n // (true)\n // >>> rightAngleTriangle((1l), (2l), (3l))\n // (false)\n public static boolean rightAngleTriangle(long a, long b, long c) {\n long[] sides = {a, b, c};\n Arrays.sort(sides);\n return (sides[0]*sides[0] + sides[1]*sides[1] == sides[2]*sides[2]);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that accepts an array array list of strings.\n // The array list contains different words. Return the word with maximum number\n // of unique characters. If multiple strings have maximum number of unique\n // characters, return the one which comes first in lexicographical order.\n // >>> findMax((new ArrayList(Arrays.asList((String)\"name\", (String)\"of\", (String)\"string\"))))\n // (\"string\")\n // >>> findMax((new ArrayList(Arrays.asList((String)\"name\", (String)\"enam\", (String)\"game\"))))\n // (\"enam\")\n // >>> findMax((new ArrayList(Arrays.asList((String)\"aaaaaaa\", (String)\"bb\", (String)\"cc\"))))\n // (\"aaaaaaa\")\n public static String findMax(ArrayList words) {\n // Create a map to store the count of unique characters for each word\n Map charCount = new HashMap<>();\n for (String word : words) {\n Set uniqueChars = new HashSet<>();\n for (char c : word.toCharArray()) {\n uniqueChars.add(c);\n }\n charCount.put(word, uniqueChars.size());\n }\n // Find the word with maximum number of unique characters\n String maxWord = \"\";\n int maxCount = 0;\n for (String word : words) {\n int count = charCount.get(word);\n if (count > maxCount || (count == maxCount && word.compareTo(maxWord) < 0)) {\n maxWord = word;\n maxCount = count;\n }\n }\n return maxWord;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You're a hungry rabbit, and you already have eaten a certain number of carrots,\n // but now you need to eat more carrots to complete the day's meals.\n // you should return an array array list of [ total number of eaten carrots after your meals,\n // the number of carrots left after your meals ]\n // if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n // Example:\n // >>> eat((5l), (6l), (10l))\n // (new ArrayList(Arrays.asList((long)11l, (long)4l)))\n // >>> eat((4l), (8l), (9l))\n // (new ArrayList(Arrays.asList((long)12l, (long)1l)))\n // >>> eat((1l), (10l), (10l))\n // (new ArrayList(Arrays.asList((long)11l, (long)0l)))\n // >>> eat((2l), (11l), (5l))\n // (new ArrayList(Arrays.asList((long)7l, (long)0l)))\n // Variables:\n // @number : integer\n // the number of carrots that you have eaten.\n // @need : integer\n // the number of carrots that you need to eat.\n // @remaining : integer\n // the number of remaining carrots thet exist in stock\n // Constrain:\n // * 0 <= number <= 1000\n // * 0 <= need <= 1000\n // * 0 <= remaining <= 1000\n // Have fun :)\n public static ArrayList eat(long number, long need, long remaining) {\n long total = number + need;\n long left = remaining - need;\n if (left < 0) {\n left = 0;\n }\n ArrayList result = new ArrayList();\n result.add(total);\n result.add(left);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n // >>> stringSequence((0l))\n // (\"0\")\n // >>> stringSequence((5l))\n // (\"0 1 2 3 4 5\")\n public static String stringSequence(long n) {\n StringBuilder sb = new StringBuilder();\n for (long i = 0; i <= n; i++) {\n sb.append(i).append(\" \");\n }\n return sb.toString().trim();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given two array lists operator, and operand. The first array list has basic algebra operations, and \n // the second array list is an array array list of integers. Use the two given array lists to build the algebric \n // expression and return the evaluation of this expression.\n // The basic algebra operations:\n // Addition ( + ) \n // Subtraction ( - ) \n // Multiplication ( * ) \n // Floor division ( // ) \n // Exponentiation ( ** ) \n // Example:\n // operator['+', '*', '-']\n // array array list = [2, 3, 4, 5]\n // result = 2 + 3 * 4 - 5\n // => result = 9\n // Note:\n // The length of operator array list is equal to the length of operand array list minus one.\n // Operand is an array array list of of non-negative integers.\n // Operator array list has at least one operator, and operand array list has at least two operands.\n public static long doAlgebra(ArrayList op, ArrayList operand) {\n long result = operand.get(0);\n for (int i = 1; i < operand.size(); i++) {\n switch (op.get(i-1)) {\n case \"+\":\n result += operand.get(i);\n break;\n case \"-\":\n result -= operand.get(i);\n break;\n case \"*\":\n result *= operand.get(i);\n break;\n case \"//\":\n result /= operand.get(i);\n break;\n case \"**\":\n result = (long) Math.pow(result, operand.get(i));\n break;\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a string s.\n // if s[i] is a letter, reverse its case from lower to upper or vise versa, \n // otherwise keep it as it is.\n // If the string contains no letters, reverse the string.\n // The function should return the resulted string.\n // Examples\n // >>> solve((\"1234\"))\n // (\"4321\")\n // >>> solve((\"ab\"))\n // (\"AB\")\n // >>> solve((\"#a@C\"))\n // (\"#A@c\")\n public static String solve(String s) {\n if (s.matches(\"[a-zA-Z]+\")) {\n StringBuilder sb = new StringBuilder();\n for (char c : s.toCharArray()) {\n if (Character.isUpperCase(c)) {\n sb.append(Character.toLowerCase(c));\n } else {\n sb.append(Character.toUpperCase(c));\n }\n }\n return sb.toString();\n } else {\n return new StringBuilder(s).reverse().toString();\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string 'text', return its md5 hash equivalent string.\n // If 'text' is an empty string, return null.\n // >>> stringToMd5((\"Hello world\"))\n // Optional.of(\"3e25960a79dbc69b674cd4ec67a72c62\")\n public static Optional stringToMd5(String text) {\n if (text.isEmpty()) {\n return Optional.empty();\n }\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n byte[] messageDigest = md.digest(text.getBytes());\n BigInteger no = new BigInteger(1, messageDigest);\n String hashtext = no.toString(16);\n while (hashtext.length() < 32) {\n hashtext = \"0\" + hashtext;\n }\n return Optional.of(hashtext);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given two positive integers a and b, return the even digits between a\n // and b, in ascending order.\n // For example:\n // >>> generateIntegers((2l), (8l))\n // (new ArrayList(Arrays.asList((long)2l, (long)4l, (long)6l, (long)8l)))\n // >>> generateIntegers((8l), (2l))\n // (new ArrayList(Arrays.asList((long)2l, (long)4l, (long)6l, (long)8l)))\n // >>> generateIntegers((10l), (14l))\n // (new ArrayList(Arrays.asList()))\n public static ArrayList generateIntegers(long a, long b) {\n ArrayList result = new ArrayList();\n for (long i = Math.min(a, b); i <= Math.max(a, b); i++) {\n if (i % 2 == 0) {\n result.add(i);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string, find out how many distinct characters (regardless of case) does it consist of\n // >>> countDistinctCharacters((\"xyzXYZ\"))\n // (3l)\n // >>> countDistinctCharacters((\"Jerry\"))\n // (4l)\n public static long countDistinctCharacters(String string) {\n return string.toLowerCase().chars().distinct().count();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Input to this function is a string representing musical notes in a special ASCII format.\n // Your task is to parse this string and return array list of integers corresponding to how many beats does each\n // not last.\n // Here is a legend:\n // 'o' - whole note, lasts four beats\n // 'o|' - half note, lasts two beats\n // '.|' - quater note, lasts one beat\n // >>> parseMusic((\"o o| .| o| o| .| .| .| .| o o\"))\n // (new ArrayList(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l)))\n public static ArrayList parseMusic(String music_string) {\n ArrayList beats = new ArrayList();\n String[] notes = music_string.split(\" \");\n for (String note : notes) {\n if (note.equals(\"o\")) {\n beats.add(4L);\n } else if (note.equals(\"o|\")) {\n beats.add(2L);\n } else if (note.equals(\".|\")) {\n beats.add(1L);\n }\n }\n return beats;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Find how many times a given substring can be found in the original string. Count overlaping cases.\n // >>> howManyTimes((\"\"), (\"a\"))\n // (0l)\n // >>> howManyTimes((\"aaa\"), (\"a\"))\n // (3l)\n // >>> howManyTimes((\"aaaa\"), (\"aa\"))\n // (3l)\n public static long howManyTimes(String string, String substring) {\n long count = 0;\n int index = 0;\n while ((index = string.indexOf(substring, index)) != -1) {\n count++;\n index += substring.length();\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Input is a space-delimited string of numberals from 'zero' to 'nine'.\n // Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n // Return the string with numbers sorted from smallest to largest\n // >>> sortNumbers((\"three one five\"))\n // (\"one three five\")\n public static String sortNumbers(String numbers) {\n String[] nums = numbers.split(\" \");\n Map map = new HashMap<>();\n map.put(\"zero\", 0);\n map.put(\"one\", 1);\n map.put(\"two\", 2);\n map.put(\"three\", 3);\n map.put(\"four\", 4);\n map.put(\"five\", 5);\n map.put(\"six\", 6);\n map.put(\"seven\", 7);\n map.put(\"eight\", 8);\n map.put(\"nine\", 9);\n List list = new ArrayList<>();\n for (String num : nums) {\n list.add(map.get(num));\n }\n Collections.sort(list);\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < list.size(); i++) {\n for (Map.Entry entry : map.entrySet()) {\n if (entry.getValue() == list.get(i)) {\n sb.append(entry.getKey());\n if (i != list.size() - 1) {\n sb.append(\" \");\n }\n break;\n }\n }\n }\n return sb.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n // separate those group into separate strings and return the array list of those.\n // Separate groups are balanced (each open brace is properly closed) and not nested within each other\n // Ignore any spaces in the input string.\n // >>> separateParenGroups((\"( ) (( )) (( )( ))\"))\n // (new ArrayList(Arrays.asList((String)\"()\", (String)\"(())\", (String)\"(()())\")))\n public static ArrayList separateParenGroups(String paren_string) {\n ArrayList result = new ArrayList();\n Stack stack = new Stack();\n int start = 0;\n for (int i = 0; i < paren_string.length(); i++) {\n char c = paren_string.charAt(i);\n if (c == '(') {\n stack.push(i);\n } else if (c == ')') {\n int start_index = stack.pop();\n if (stack.isEmpty()) {\n result.add(paren_string.substring(start_index, i + 1));\n start = i + 1;\n }\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // From a supplied array list of numbers (of length at least two) select and return two that are the closest to each\n // other and return them in order (smaller number, larger number).\n // >>> findClosestElements((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.2f))))\n // (Pair.with(2.0f, 2.2f))\n // >>> findClosestElements((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))))\n // (Pair.with(2.0f, 2.0f))\n public static Pair findClosestElements(ArrayList numbers) {\n Collections.sort(numbers);\n float minDiff = Float.MAX_VALUE;\n Pair closestPair = Pair.with(numbers.get(0), numbers.get(1));\n for (int i = 1; i < numbers.size(); i++) {\n float diff = Math.abs(numbers.get(i) - numbers.get(i-1));\n if (diff < minDiff) {\n minDiff = diff;\n closestPair = Pair.with(numbers.get(i-1), numbers.get(i));\n }\n }\n return closestPair;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given array list of numbers (of at least two elements), apply a linear transform to that array list,\n // such that the smallest number will become 0 and the largest will become 1\n // >>> rescaleToUnit((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f))))\n // (new ArrayList(Arrays.asList((float)0.0f, (float)0.25f, (float)0.5f, (float)0.75f, (float)1.0f)))\n public static ArrayList rescaleToUnit(ArrayList numbers) {\n float min = Collections.min(numbers);\n float max = Collections.max(numbers);\n ArrayList rescaled = new ArrayList();\n for (float num : numbers) {\n float rescaledNum = (num - min) / (max - min);\n rescaled.add(rescaledNum);\n }\n return rescaled;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Filter given array list of any javathon values only for integers\n // >>> filterIntegers((new ArrayList(Arrays.asList((String)\"a\", (String)3.14f, (String)5l))))\n // (new ArrayList(Arrays.asList((long)5l)))\n // >>> filterIntegers((new ArrayList(Arrays.asList(1l, 2l, 3l, \"abc\", new HashMap(Map.of()), new ArrayList(Arrays.asList())))))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l)))\n public static ArrayList filterIntegers(ArrayList values) {\n ArrayList result = new ArrayList();\n for (Object value : values) {\n if (value instanceof Integer) {\n result.add(((Integer) value).longValue());\n } else if (value instanceof Long) {\n result.add((Long) value);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return length of given string\n // >>> stringLength((\"\"))\n // (0l)\n // >>> stringLength((\"abc\"))\n // (3l)\n public static long strlen(String string) {\n return string.length();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // For a given number n, find the largest number that divides n evenly, smaller than n\n // >>> largestDivisor((15l))\n // (5l)\n public static long largestDivisor(long n) {\n long largest = 1;\n for (long i = 2; i <= Math.sqrt(n); i++) {\n if (n % i == 0) {\n largest = i;\n }\n }\n return largest;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return array list of prime factors of given integer in the order from smallest to largest.\n // Each of the factors should be array listed number of times corresponding to how many times it appeares in factorization.\n // Input number should be equal to the product of all factors\n // >>> factorize((8l))\n // (new ArrayList(Arrays.asList((long)2l, (long)2l, (long)2l)))\n // >>> factorize((25l))\n // (new ArrayList(Arrays.asList((long)5l, (long)5l)))\n // >>> factorize((70l))\n // (new ArrayList(Arrays.asList((long)2l, (long)5l, (long)7l)))\n public static ArrayList factorize(long n) {\n ArrayList factors = new ArrayList();\n for (long i = 2; i <= n; i++) {\n while (n % i == 0) {\n factors.add(i);\n n /= i;\n }\n }\n return factors;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // From an array array list of integers, remove all elements that occur more than once.\n // Keep order of elements left the same as in the input.\n // >>> removeDuplicates((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)3l, (long)4l)))\n public static ArrayList removeDuplicates(ArrayList numbers) {\n ArrayList result = new ArrayList();\n for (Long num : numbers) {\n if (!result.contains(num)) {\n result.add(num);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n // >>> flipCase((\"Hello\"))\n // (\"hELLO\")\n public static String flipCase(String string) {\n StringBuilder result = new StringBuilder();\n for (char c : string.toCharArray()) {\n if (Character.isUpperCase(c)) {\n result.append(Character.toLowerCase(c));\n } else {\n result.append(Character.toUpperCase(c));\n }\n }\n return result.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Concatenate array list of strings into a single string\n // >>> concatenate((new ArrayList(Arrays.asList())))\n // (\"\")\n // >>> concatenate((new ArrayList(Arrays.asList((String)\"a\", (String)\"b\", (String)\"c\"))))\n // (\"abc\")\n public static String concatenate(ArrayList strings) {\n StringBuilder sb = new StringBuilder();\n for (String s : strings) {\n sb.append(s);\n }\n return sb.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Filter an input array list of strings only for ones that start with a given prefix.\n // >>> filterByPrefix((new ArrayList(Arrays.asList())), (\"a\"))\n // (new ArrayList(Arrays.asList()))\n // >>> filterByPrefix((new ArrayList(Arrays.asList((String)\"abc\", (String)\"bcd\", (String)\"cde\", (String)\"array\"))), (\"a\"))\n // (new ArrayList(Arrays.asList((String)\"abc\", (String)\"array\")))\n public static ArrayList filterByPrefix(ArrayList strings, String prefix) {\n ArrayList result = new ArrayList();\n for (String s : strings) {\n if (s.startsWith(prefix)) {\n result.add(s);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive floating point number, it can be decomposed into\n // and integer part (largest integer smaller than given number) and decimals\n // (leftover part always smaller than 1).\n // Return the decimal part of the number.\n // >>> truncateNumber((3.5f))\n // (0.5f)\n public static float truncateNumber(float number) {\n int integerPart = (int) number;\n float decimalPart = number - integerPart;\n return decimalPart;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return only positive numbers in the array list.\n // >>> getPositive((new ArrayList(Arrays.asList((long)-1l, (long)2l, (long)-4l, (long)5l, (long)6l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)5l, (long)6l)))\n // >>> getPositive((new ArrayList(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l))))\n // (new ArrayList(Arrays.asList((long)5l, (long)3l, (long)2l, (long)3l, (long)9l, (long)123l, (long)1l)))\n public static ArrayList getPositive(ArrayList l) {\n ArrayList result = new ArrayList();\n for (Long num : l) {\n if (num > 0) {\n result.add(num);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return true if a given number is prime, and false otherwise.\n // >>> isPrime((6l))\n // (false)\n // >>> isPrime((101l))\n // (true)\n // >>> isPrime((11l))\n // (true)\n // >>> isPrime((13441l))\n // (true)\n // >>> isPrime((61l))\n // (true)\n // >>> isPrime((4l))\n // (false)\n // >>> isPrime((1l))\n // (false)\n public static boolean isPrime(long n) {\n if (n <= 1) {\n return false;\n }\n for (long i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // This function takes an array array list l and returns an array array list l' such that\n // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n // to the values of the corresponding indicies of l, but sorted.\n // >>> sortThird((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l)))\n // >>> sortThird((new ArrayList(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l)))\n public static ArrayList sortThird(ArrayList l) {\n ArrayList l_prime = new ArrayList();\n ArrayList divisible_by_three = new ArrayList();\n for (int i = 0; i < l.size(); i++) {\n if (i % 3 == 0) {\n divisible_by_three.add(l.get(i));\n } else {\n l_prime.add(l.get(i));\n }\n }\n Collections.sort(divisible_by_three);\n int j = 0;\n for (int i = 0; i < l.size(); i++) {\n if (i % 3 == 0) {\n l_prime.add(i, divisible_by_three.get(j));\n j++;\n }\n }\n return l_prime;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return sorted unique elements in an array array list\n // >>> unique((new ArrayList(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l))))\n // (new ArrayList(Arrays.asList((long)0l, (long)2l, (long)3l, (long)5l, (long)9l, (long)123l)))\n public static ArrayList unique(ArrayList l) {\n ArrayList result = new ArrayList();\n for (Long i : l) {\n if (!result.contains(i)) {\n result.add(i);\n }\n }\n Collections.sort(result);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return maximum element in the array list.\n // >>> maxElement((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (3l)\n // >>> maxElement((new ArrayList(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l))))\n // (123l)\n public static long maxElement(ArrayList l) {\n return l.stream().mapToLong(i -> i).max().getAsLong();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n // >>> fizzBuzz((50l))\n // (0l)\n // >>> fizzBuzz((78l))\n // (2l)\n // >>> fizzBuzz((79l))\n // (3l)\n public static long fizzBuzz(long n) {\n long count = 0;\n for (long i = 1; i < n; i++) {\n if (i % 11 == 0 || i % 13 == 0) {\n String str = Long.toString(i);\n count += str.chars().filter(ch -> ch == '7').count();\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // This function takes an array array list l and returns an array array list l' such that\n // l' is identical to l in the odd indicies, while its values at the even indicies are equal\n // to the values of the even indicies of l, but sorted.\n // >>> sortEven((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l)))\n // >>> sortEven((new ArrayList(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l))))\n // (new ArrayList(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l)))\n public static ArrayList sortEven(ArrayList l) {\n ArrayList even = new ArrayList();\n ArrayList odd = new ArrayList();\n for (int i = 0; i < l.size(); i++) {\n if (i % 2 == 0) {\n even.add(l.get(i));\n } else {\n odd.add(l.get(i));\n }\n }\n Collections.sort(even);\n ArrayList result = new ArrayList();\n for (int i = 0; i < l.size(); i++) {\n if (i % 2 == 0) {\n result.add(even.get(i / 2));\n } else {\n result.add(odd.get(i / 2));\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n // >>> primeFib((1l))\n // (2l)\n // >>> primeFib((2l))\n // (3l)\n // >>> primeFib((3l))\n // (5l)\n // >>> primeFib((4l))\n // (13l)\n // >>> primeFib((5l))\n // (89l)\n public static long primeFib(long n) {\n long count = 0;\n long fib = 0;\n long i = 0;\n while (count < n) {\n if (isPrime(fib)) {\n count++;\n }\n if (count == n) {\n return fib;\n }\n fib = fibonacci(i);\n i++;\n }\n return -1;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You're given an array array list of deposit and withdrawal operations on a bank account that starts with\n // zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n // at that point function should return true. Otherwise it should return false.\n // >>> belowZero((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (false)\n // >>> belowZero((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l))))\n // (true)\n public static boolean belowZero(ArrayList operations) {\n long balance = 0;\n for (long op : operations) {\n balance += op;\n if (balance < 0) {\n return true;\n }\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // triples_sum_to_zero takes an array array list of integers as an input.\n // it returns true if there are three distinct elements in the array list that\n // sum to zero, and false otherwise.\n // >>> triplesSumToZero((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l))))\n // (false)\n // >>> triplesSumToZero((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l))))\n // (true)\n // >>> triplesSumToZero((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l))))\n // (false)\n // >>> triplesSumToZero((new ArrayList(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l))))\n // (true)\n // >>> triplesSumToZero((new ArrayList(Arrays.asList((long)1l))))\n // (false)\n public static boolean triplesSumToZero(ArrayList l) {\n for (int i = 0; i < l.size(); i++) {\n for (int j = i + 1; j < l.size(); j++) {\n for (int k = j + 1; k < l.size(); k++) {\n if (l.get(i) + l.get(j) + l.get(k) == 0) {\n return true;\n }\n }\n }\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Imagine a road that's a perfectly straight infinitely long line.\n // n cars are driving left to right; simultaneously, a different set of n cars\n // are driving right to left. The two sets of cars start out being very far from\n // each other. All cars move in the same speed. Two cars are said to collide\n // when a car that's moving left to right hits a car that's moving right to left.\n // However, the cars are infinitely sturdy and strong; as a result, they continue moving\n // in their trajectory as if they did not collide.\n // This function outputs the number of such collisions.\n public static long carRaceCollision(long n) {\n return n * (n - 1) / 2;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return array list with elements incremented by 1.\n // >>> incrList((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l, (long)4l)))\n // >>> incrList((new ArrayList(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l))))\n // (new ArrayList(Arrays.asList((long)6l, (long)4l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l)))\n public static ArrayList incrList(ArrayList l) {\n ArrayList result = new ArrayList();\n for (Long num : l) {\n result.add(num + 1);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // pairs_sum_to_zero takes an array array list of integers as an input.\n // it returns true if there are two distinct elements in the array list that\n // sum to zero, and false otherwise.\n // >>> pairsSumToZero((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l))))\n // (false)\n // >>> pairsSumToZero((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l))))\n // (false)\n // >>> pairsSumToZero((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l))))\n // (false)\n // >>> pairsSumToZero((new ArrayList(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l))))\n // (true)\n // >>> pairsSumToZero((new ArrayList(Arrays.asList((long)1l))))\n // (false)\n public static boolean pairsSumToZero(ArrayList l) {\n HashSet set = new HashSet();\n for (Long i : l) {\n if (set.contains(-i)) {\n return true;\n }\n set.add(i);\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Change numerical base of input number x to base.\n // return string representation after the conversion.\n // base numbers are less than 10.\n // >>> changeBase((8l), (3l))\n // (\"22\")\n // >>> changeBase((8l), (2l))\n // (\"1000\")\n // >>> changeBase((7l), (2l))\n // (\"111\")\n public static String changeBase(long x, long base) {\n return Long.toString(x, (int) base);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given length of a side and high return area for a triangle.\n // >>> triangleArea((5l), (3l))\n // (7.5f)\n public static float triangleArea(long a, long h) {\n float area = (float) (0.5 * a * h);\n return area;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n // fib4(0) -> 0\n // fib4(1) -> 0\n // fib4(2) -> 2\n // fib4(3) -> 0\n // fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n // Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n // >>> fib4((5l))\n // (4l)\n // >>> fib4((6l))\n // (8l)\n // >>> fib4((7l))\n // (14l)\n public static long fib4(long n) {\n if (n == 0) {\n return 0;\n } else if (n == 1) {\n return 0;\n } else if (n == 2) {\n return 2;\n } else if (n == 3) {\n return 0;\n } else {\n long a = 0;\n long b = 0;\n long c = 2;\n long d = 0;\n for (int i = 4; i <= n; i++) {\n long temp = a + b + c + d;\n a = b;\n b = c;\n c = d;\n d = temp;\n }\n return d;\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return median of elements in the array list l.\n // >>> median((new ArrayList(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l))))\n // (float)3l\n // >>> median((new ArrayList(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l))))\n // (15.0f)\n public static float median(ArrayList l) {\n Collections.sort(l);\n int n = l.size();\n if (n % 2 == 0) {\n return (l.get(n / 2 - 1) + l.get(n / 2)) / 2.0f;\n } else {\n return l.get(n / 2);\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Checks if given string is a palindrome\n // >>> isPalindrome((\"\"))\n // (true)\n // >>> isPalindrome((\"aba\"))\n // (true)\n // >>> isPalindrome((\"aaaaa\"))\n // (true)\n // >>> isPalindrome((\"zbcd\"))\n // (false)\n public static boolean isPalindrome(String text) {\n int length = text.length();\n for (int i = 0; i < length / 2; i++) {\n if (text.charAt(i) != text.charAt(length - i - 1)) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return 2^n modulo p (be aware of numerics).\n // >>> modp((3l), (5l))\n // (3l)\n // >>> modp((1101l), (101l))\n // (2l)\n // >>> modp((0l), (101l))\n // (1l)\n // >>> modp((3l), (11l))\n // (8l)\n // >>> modp((100l), (101l))\n // (1l)\n public static long modp(long n, long p) {\n return BigInteger.valueOf(n).modPow(BigInteger.ONE, BigInteger.valueOf(p)).longValue();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // For a given array list of input numbers, calculate Mean Absolute Deviation\n // around the mean of this dataset.\n // Mean Absolute Deviation is the average absolute difference between each\n // element and a centerpoint (mean in this case):\n // MAD = average | x - x_mean |\n // >>> meanAbsoluteDeviation((new ArrayList(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f))))\n // (1.0f)\n public static float meanAbsoluteDeviation(ArrayList numbers) {\n float sum = 0;\n for (float num : numbers) {\n sum += num;\n }\n float mean = sum / numbers.size();\n float madSum = 0;\n for (float num : numbers) {\n madSum += Math.abs(num - mean);\n }\n float mad = madSum / numbers.size();\n return mad;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // remove_vowels is a function that takes string and returns string without vowels.\n // >>> removeVowels((\"\"))\n // (\"\")\n // >>> removeVowels((\"abcdef\"))\n // (\"bcdf\")\n // >>> removeVowels((\"aaaaa\"))\n // (\"\")\n // >>> removeVowels((\"aaBAA\"))\n // (\"B\")\n // >>> removeVowels((\"zbcd\"))\n // (\"zbcd\")\n public static String removeVowels(String text) {\n String vowels = \"aeiouAEIOU\";\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (vowels.indexOf(c) == -1) {\n result.append(c);\n }\n }\n return result.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return true if all numbers in the array list l are below threshold t.\n // >>> belowThreshold((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l))\n // (true)\n // >>> belowThreshold((new ArrayList(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l))\n // (false)\n public static boolean belowThreshold(ArrayList l, long t) {\n for (long num : l) {\n if (num >= t) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Add two numbers x and y\n // >>> add((2l), (3l))\n // (5l)\n // >>> add((5l), (7l))\n // (12l)\n public static long add(long x, long y) {\n return x + y;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Check if two words have the same characters.\n // >>> sameChars((\"eabcdzzzz\"), (\"dddzzzzzzzddeddabc\"))\n // (true)\n // >>> sameChars((\"abcd\"), (\"dddddddabc\"))\n // (true)\n // >>> sameChars((\"dddddddabc\"), (\"abcd\"))\n // (true)\n // >>> sameChars((\"eabcd\"), (\"dddddddabc\"))\n // (false)\n // >>> sameChars((\"abcd\"), (\"dddddddabce\"))\n // (false)\n // >>> sameChars((\"eabcdzzzz\"), (\"dddzzzzzzzddddabc\"))\n // (false)\n public static boolean sameChars(String s0, String s1) {\n char[] c0 = s0.toCharArray();\n char[] c1 = s1.toCharArray();\n Arrays.sort(c0);\n Arrays.sort(c1);\n return Arrays.equals(c0, c1);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return n-th Fibonacci number.\n // >>> fib((10l))\n // (55l)\n // >>> fib((1l))\n // (1l)\n // >>> fib((8l))\n // (21l)\n public static long fib(long n) {\n if (n <= 1) {\n return n;\n }\n long a = 0;\n long b = 1;\n for (long i = 2; i <= n; i++) {\n long c = a + b;\n a = b;\n b = c;\n }\n return b;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // brackets is a string of \"<\" and \">\".\n // return true if every opening bracket has a corresponding closing bracket.\n // >>> correctBracketing((\"<\"))\n // (false)\n // >>> correctBracketing((\"<>\"))\n // (true)\n // >>> correctBracketing((\"<<><>>\"))\n // (true)\n // >>> correctBracketing((\"><<>\"))\n // (false)\n public static boolean correctBracketing(String brackets) {\n int count = 0;\n for (int i = 0; i < brackets.length(); i++) {\n if (brackets.charAt(i) == '<') {\n count++;\n } else {\n count--;\n if (count < 0) {\n return false;\n }\n }\n }\n return count == 0;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return true is array list elements are monotonically increasing or decreasing.\n // >>> monotonic((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l))))\n // (true)\n // >>> monotonic((new ArrayList(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))))\n // (false)\n // >>> monotonic((new ArrayList(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l))))\n // (true)\n public static boolean monotonic(ArrayList l) {\n boolean increasing = true;\n boolean decreasing = true;\n for (int i = 0; i < l.size() - 1; i++) {\n if (l.get(i) > l.get(i + 1)) {\n increasing = false;\n }\n if (l.get(i) < l.get(i + 1)) {\n decreasing = false;\n }\n }\n return increasing || decreasing;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return sorted unique common elements for two array lists.\n // >>> common((new ArrayList(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)5l, (long)653l)))\n // >>> common((new ArrayList(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList(Arrays.asList((long)3l, (long)2l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l)))\n public static ArrayList common(ArrayList l1, ArrayList l2) {\n Set set1 = new HashSet<>(l1);\n Set set2 = new HashSet<>(l2);\n set1.retainAll(set2);\n ArrayList result = new ArrayList<>(set1);\n Collections.sort(result);\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Return the largest prime factor of n. Assume n > 1 and is not a prime.\n // >>> largestPrimeFactor((13195l))\n // (29l)\n // >>> largestPrimeFactor((2048l))\n // (2l)\n public static long largestPrimeFactor(long n) {\n long largestFactor = 0;\n for (long i = 2; i <= n; i++) {\n while (n % i == 0) {\n largestFactor = i;\n n /= i;\n }\n }\n return largestFactor;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Insert a number 'delimeter' between every two consecutive elements of input array list `numbers'\n // >>> intersperse((new ArrayList(Arrays.asList())), (4l))\n // (new ArrayList(Arrays.asList()))\n // >>> intersperse((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))), (4l))\n // (new ArrayList(Arrays.asList((long)1l, (long)4l, (long)2l, (long)4l, (long)3l)))\n public static ArrayList intersperse(ArrayList numbers, long delimeter) {\n ArrayList result = new ArrayList();\n for (int i = 0; i < numbers.size(); i++) {\n result.add(numbers.get(i));\n if (i != numbers.size() - 1) {\n result.add(delimeter);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // sum_to_n is a function that sums numbers from 1 to n.\n // >>> sumToN((30l))\n // (465l)\n // >>> sumToN((100l))\n // (5050l)\n // >>> sumToN((5l))\n // (15l)\n // >>> sumToN((10l))\n // (55l)\n // >>> sumToN((1l))\n // (1l)\n public static long sumToN(long n) {\n return (n * (n + 1)) / 2;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // brackets is a string of \"(\" and \")\".\n // return true if every opening bracket has a corresponding closing bracket.\n // >>> correctBracketing((\"(\"))\n // (false)\n // >>> correctBracketing((\"()\"))\n // (true)\n // >>> correctBracketing((\"(()())\"))\n // (true)\n // >>> correctBracketing((\")(()\"))\n // (false)\n public static boolean correctBracketing(String brackets) {\n Stack stack = new Stack<>();\n for (char c : brackets.toCharArray()) {\n if (c == '(') {\n stack.push(c);\n } else if (c == ')') {\n if (stack.isEmpty()) {\n return false;\n }\n stack.pop();\n }\n }\n return stack.isEmpty();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // xs represent coefficients of a polynomial.\n // xs[0] + xs[1] * x + xs[2] * x^2 + ....\n // Return derivative of this polynomial in the same form.\n // >>> derivative((new ArrayList(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)4l, (long)12l, (long)20l)))\n // >>> derivative((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)6l)))\n public static ArrayList derivative(ArrayList xs) {\n ArrayList result = new ArrayList();\n for (int i = 1; i < xs.size(); i++) {\n result.add(xs.get(i) * i);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n // fibfib(0) == 0\n // fibfib(1) == 0\n // fibfib(2) == 1\n // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n // Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n // >>> fibfib((1l))\n // (0l)\n // >>> fibfib((5l))\n // (4l)\n // >>> fibfib((8l))\n // (24l)\n public static long fibfib(long n) {\n if (n == 0) {\n return 0;\n } else if (n == 1 || n == 2) {\n return 1;\n } else {\n long[] fib = new long[(int)n+1];\n fib[0] = 0;\n fib[1] = 0;\n fib[2] = 1;\n for (int i = 3; i <= n; i++) {\n fib[i] = fib[i-1] + fib[i-2] + fib[i-3];\n }\n return fib[(int)n];\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function vowels_count which takes a string representing\n // a word as input and returns the number of vowels in the string.\n // Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n // vowel, but only when it is at the end of the given word.\n // Example:\n // >>> vowelsCount((\"abcde\"))\n // (2l)\n // >>> vowelsCount((\"ACEDY\"))\n // (3l)\n public static long vowelsCount(String s) {\n long count = 0;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||\n (c == 'y' && i == s.length() - 1)) {\n count++;\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Circular shift the digits of the integer x, shift the digits right by shift\n // and return the result as a string.\n // If shift > number of digits, return digits reversed.\n // >>> circularShift((12l), (1l))\n // (\"21\")\n // >>> circularShift((12l), (2l))\n // (\"12\")\n public static String circularShift(long x, long shift) {\n String str = Long.toString(x);\n int len = str.length();\n if (shift > len) {\n return new StringBuilder(str).reverse().toString();\n }\n String shifted = str.substring(len - (int) shift) + str.substring(0, len - (int) shift);\n return shifted;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Task\n // Write a function that takes a string as input and returns the sum of the upper characters only'\n // ASCII codes.\n // Examples:\n // >>> digitSum((\"\"))\n // (0l)\n // >>> digitSum((\"abAB\"))\n // (131l)\n // >>> digitSum((\"abcCd\"))\n // (67l)\n // >>> digitSum((\"helloE\"))\n // (69l)\n // >>> digitSum((\"woArBld\"))\n // (131l)\n // >>> digitSum((\"aAaaaXa\"))\n // (153l)\n public static long digitSum(String s) {\n long sum = 0;\n for (char c : s.toCharArray()) {\n if (Character.isUpperCase(c)) {\n sum += (int) c;\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // In this task, you will be given a string that represents a number of apples and oranges \n // that are distributed in a basket of fruit this basket contains \n // apples, oranges, and mango fruits. Given the string that represents the total number of \n // the oranges and apples and an integer that represent the total number of the fruits \n // in the basket return the number of the mango fruits in the basket.\n // for examble:\n // >>> fruitDistribution((\"5 apples and 6 oranges\"), (19l))\n // (8l)\n // >>> fruitDistribution((\"0 apples and 1 oranges\"), (3l))\n // (2l)\n // >>> fruitDistribution((\"2 apples and 3 oranges\"), (100l))\n // (95l)\n // >>> fruitDistribution((\"100 apples and 1 oranges\"), (120l))\n // (19l)\n public static long fruitDistribution(String s, long n) {\n String[] parts = s.split(\" and \");\n long apples = Long.parseLong(parts[0].split(\" \")[0]);\n long oranges = Long.parseLong(parts[1].split(\" \")[0]);\n long mangoes = n - apples - oranges;\n return mangoes;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // \"Given an array array list representing a branch of a tree that has non-negative integer nodes\n // your task is to pluck one of the nodes and return it.\n // The plucked node should be the node with the smallest even value.\n // If multiple nodes with the same smallest even value are found return the node that has smallest index.\n // The plucked node should be returned in an array array list, [ smalest_value, its index ],\n // If there are no even values or the given array array list is empty, return [].\n // Example 1:\n // >>> pluck((new ArrayList(Arrays.asList((long)4l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)1l)))\n // Explanation: 2 has the smallest even value, and 2 has the smallest index.\n // Example 2:\n // >>> pluck((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))\n // (new ArrayList(Arrays.asList((long)2l, (long)1l)))\n // Explanation: 2 has the smallest even value, and 2 has the smallest index.\n // Example 3:\n // >>> pluck((new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n // Example 4:\n // >>> pluck((new ArrayList(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l))))\n // (new ArrayList(Arrays.asList((long)0l, (long)1l)))\n // Explanation: 0 is the smallest value, but there are two zeros,\n // so we will choose the first zero, which has the smallest index.\n // Constraints:\n // * 1 <= nodes.length <= 10000\n // * 0 <= node.value\n public static ArrayList pluck(ArrayList arr) {\n ArrayList result = new ArrayList<>();\n long minEven = Long.MAX_VALUE;\n int minIndex = -1;\n for (int i = 0; i < arr.size(); i++) {\n long num = arr.get(i);\n if (num % 2 == 0 && num < minEven) {\n minEven = num;\n minIndex = i;\n }\n }\n if (minIndex != -1) {\n result.add(minEven);\n result.add((long) minIndex);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a non-empty array list of positive integers. Return the greatest integer that is greater than \n // zero, and has a frequency greater than or equal to the value of the integer itself. \n // The frequency of an integer is the number of times it appears in the array list.\n // If no such a value exist, return -1.\n // Examples:\n // >>> search((new ArrayList(Arrays.asList((long)4l, (long)1l, (long)2l, (long)2l, (long)3l, (long)1l))))\n // (2l)\n // >>> search((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l, (long)4l, (long)4l))))\n // (3l)\n // >>> search((new ArrayList(Arrays.asList((long)5l, (long)5l, (long)4l, (long)4l, (long)4l))))\n // (-1l)\n public static long search(ArrayList lst) {\n Map freq = lst.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n return freq.entrySet().stream().filter(e -> e.getKey() > 0 && e.getValue() >= e.getKey()).map(Map.Entry::getKey).max(Comparator.naturalOrder()).orElse(-1L);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n // For each of the group, output the deepest level of nesting of parentheses.\n // E.g. (()()) has maximum two levels of nesting while ((())) has three.\n // >>> parseNestedParens((\"(()()) ((())) () ((())()())\"))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l)))\n public static ArrayList parseNestedParens(String paren_string) {\n ArrayList result = new ArrayList();\n String[] groups = paren_string.split(\" \");\n for (String group : groups) {\n long max_depth = 0;\n long current_depth = 0;\n for (char c : group.toCharArray()) {\n if (c == '(') {\n current_depth++;\n } else if (c == ')') {\n current_depth--;\n }\n max_depth = Math.max(max_depth, current_depth);\n }\n result.add(max_depth);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given array list of integers, return array list in strange order.\n // Strange sorting, is when you start with the minimum value,\n // then maximum of the remaining integers, then minimum and so on.\n // Examples:\n // >>> strangeSortList((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l)))\n // >>> strangeSortList((new ArrayList(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))\n // (new ArrayList(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))\n // >>> strangeSortList((new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n public static ArrayList strangeSortList(ArrayList lst) {\n ArrayList result = new ArrayList();\n while (!lst.isEmpty()) {\n Long min = Collections.min(lst);\n result.add(min);\n lst.remove(min);\n if (!lst.isEmpty()) {\n Long max = Collections.max(lst);\n result.add(max);\n lst.remove(max);\n }\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given the lengths of the three sides of a triangle. Return the area of\n // the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n // Otherwise return -1\n // Three sides make a valid triangle when the sum of any two sides is greater \n // than the third side.\n // Example:\n // >>> triangleArea((3l), (4l), (5l))\n // (6.0f)\n // >>> triangleArea((1l), (2l), (10l))\n // (float)-1l\n public static float triangleArea(long a, long b, long c) {\n if (a + b > c && b + c > a && c + a > b) {\n float s = (a + b + c) / 2f;\n float area = (float) Math.sqrt(s * (s - a) * (s - b) * (s - c));\n return Math.round(area * 100.0f) / 100.0f;\n } else {\n return -1f;\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that returns true if the object q will fly, and false otherwise.\n // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w.\n // Example:\n // >>> willItFly((new ArrayList(Arrays.asList((long)1l, (long)2l))), (5l))\n // (false)\n // # 1+2 is less than the maximum possible weight, but it's unbalanced.\n // >>> willItFly((new ArrayList(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l))\n // (false)\n // # it's balanced, but 3+2+3 is more than the maximum possible weight.\n // >>> willItFly((new ArrayList(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l))\n // (true)\n // # 3+2+3 is less than the maximum possible weight, and it's balanced.\n // >>> willItFly((new ArrayList(Arrays.asList((long)3l))), (5l))\n // (true)\n // # 3 is less than the maximum possible weight, and it's balanced.\n public static boolean willItFly(ArrayList q, long w) {\n // Check if the array list is balanced\n boolean isBalanced = true;\n for (int i = 0; i < q.size() / 2; i++) {\n if (!q.get(i).equals(q.get(q.size() - i - 1))) {\n isBalanced = false;\n break;\n }\n }\n // Check if the sum of the elements is less than or equal to the maximum possible weight\n long sum = 0;\n for (long num : q) {\n sum += num;\n }\n boolean isWeightLessThanMax = sum <= w;\n // Return true if both conditions are met, false otherwise\n return isBalanced && isWeightLessThanMax;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list arr of integers, find the minimum number of elements that\n // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that\n // is read the same backwards and forwards. In one change, you can change one element to any other element.\n // For example:\n // >>> smallestChange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l))))\n // (4l)\n // >>> smallestChange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l))))\n // (1l)\n // >>> smallestChange((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l))))\n // (0l)\n public static long smallestChange(ArrayList arr) {\n int n = arr.size();\n int left = 0;\n int right = n - 1;\n int count = 0;\n while (left < right) {\n if (arr.get(left) != arr.get(right)) {\n count++;\n }\n left++;\n right--;\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that accepts two array lists of strings and returns the array list that has \n // total number of chars in the all strings of the array list less than the other array list.\n // if the two array lists have the same number of chars, return the first array list.\n // Examples\n // >>> totalMatch((new ArrayList(Arrays.asList())), (new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n // >>> totalMatch((new ArrayList(Arrays.asList((String)\"hi\", (String)\"admin\"))), (new ArrayList(Arrays.asList((String)\"hI\", (String)\"Hi\"))))\n // (new ArrayList(Arrays.asList((String)\"hI\", (String)\"Hi\")))\n // >>> totalMatch((new ArrayList(Arrays.asList((String)\"hi\", (String)\"admin\"))), (new ArrayList(Arrays.asList((String)\"hi\", (String)\"hi\", (String)\"admin\", (String)\"project\"))))\n // (new ArrayList(Arrays.asList((String)\"hi\", (String)\"admin\")))\n // >>> totalMatch((new ArrayList(Arrays.asList((String)\"hi\", (String)\"admin\"))), (new ArrayList(Arrays.asList((String)\"hI\", (String)\"hi\", (String)\"hi\"))))\n // (new ArrayList(Arrays.asList((String)\"hI\", (String)\"hi\", (String)\"hi\")))\n // >>> totalMatch((new ArrayList(Arrays.asList((String)\"4\"))), (new ArrayList(Arrays.asList((String)\"1\", (String)\"2\", (String)\"3\", (String)\"4\", (String)\"5\"))))\n // (new ArrayList(Arrays.asList((String)\"4\")))\n public static ArrayList totalMatch(ArrayList lst1, ArrayList lst2) {\n int total1 = lst1.stream().mapToInt(String::length).sum();\n int total2 = lst2.stream().mapToInt(String::length).sum();\n if (total1 < total2) {\n return lst1;\n } else if (total2 < total1) {\n return lst2;\n } else {\n return lst1;\n }"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that returns true if the given number is the multiplication of 3 prime numbers\n // and false otherwise.\n // Knowing that (a) is less then 100. \n // Example:\n // >>> isMultiplyPrime((30l))\n // (true)\n // 30 = 2 * 3 * 5\n public static boolean isMultiplyPrime(long a) {\n if (a < 6) {\n return false;\n }\n List primes = new ArrayList<>();\n for (long i = 2; i <= a; i++) {\n boolean isPrime = true;\n for (long j = 2; j <= Math.sqrt(i); j++) {\n if (i % j == 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) {\n primes.add(i);\n }\n }\n for (int i = 0; i < primes.size(); i++) {\n for (int j = i; j < primes.size(); j++) {\n for (int k = j; k < primes.size(); k++) {\n if (primes.get(i) * primes.get(j) * primes.get(k) == a) {\n return true;\n }\n }\n }\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Your task is to write a function that returns true if a number x is a simple\n // power of n and false in other cases.\n // x is a simple power of n if n**int=x\n // For example:\n // >>> isSimplePower((1l), (4l))\n // (true)\n // >>> isSimplePower((2l), (2l))\n // (true)\n // >>> isSimplePower((8l), (2l))\n // (true)\n // >>> isSimplePower((3l), (2l))\n // (false)\n // >>> isSimplePower((3l), (1l))\n // (false)\n // >>> isSimplePower((5l), (3l))\n // (false)\n public static boolean isSimplePower(long x, long n) {\n if (x == 1) {\n return true;\n }\n long power = 1;\n while (power < x) {\n power *= n;\n }\n return power == x;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that takes an integer a and returns true \n // if this ingeger is a cube of some integer number.\n // Note: you may assume the input is always valid.\n // Examples:\n // >>> iscube((1l))\n // (true)\n // >>> iscube((2l))\n // (false)\n // >>> iscube((-1l))\n // (true)\n // >>> iscube((64l))\n // (true)\n // >>> iscube((0l))\n // (true)\n // >>> iscube((180l))\n // (false)\n public static boolean iscube(long a) {\n long cubeRoot = (long) Math.round(Math.pow(Math.abs(a), 1.0/3.0));\n return cubeRoot * cubeRoot * cubeRoot == a;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You have been tasked to write a function that receives \n // a hexadecimal number as a string and counts the number of hexadecimal \n // digits that are primes (prime number, or a prime, is a natural number \n // greater than 1 that is not a product of two smaller natural numbers).\n // Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n // Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n // So you have to determine a number of the following digits: 2, 3, 5, 7, \n // B (=decimal 11), D (=decimal 13).\n // Note: you may assume the input is always correct or empty string, \n // and symbols A,B,C,D,E,F are always uppercase.\n // Examples:\n // >>> hexKey((\"AB\"))\n // (1l)\n // >>> hexKey((\"1077E\"))\n // (2l)\n // >>> hexKey((\"ABED1A33\"))\n // (4l)\n // >>> hexKey((\"123456789ABCDEF0\"))\n // (6l)\n // >>> hexKey((\"2020\"))\n // (2l)\n public static long hexKey(String num) {\n // Define a set of prime hexadecimal digits\n Set primeDigits = new HashSet<>(Arrays.asList('2', '3', '5', '7', 'B', 'D'));\n\n // Count the number of prime hexadecimal digits in the input string\n long count = num.chars()\n .mapToObj(c -> (char) c)\n .filter(c -> primeDigits.contains(c))\n .count();\n\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You will be given a number in decimal form and your task is to convert it to\n // binary format. The function should return a string, with each character representing a binary\n // number. Each character in the string will be '0' or '1'.\n // There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n // The extra characters are there to help with the format.\n // Examples:\n // >>> decimalToBinary((15l))\n // (\"db1111db\")\n // >>> decimalToBinary((32l))\n // (\"db100000db\")\n public static String decimalToBinary(long decimal) {\n String binary = Long.toBinaryString(decimal);\n return \"db\" + binary + \"db\";"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Filter an input array list of strings only for ones that contain given substring\n // >>> filterBySubstring((new ArrayList(Arrays.asList())), (\"a\"))\n // (new ArrayList(Arrays.asList()))\n // >>> filterBySubstring((new ArrayList(Arrays.asList((String)\"abc\", (String)\"bacd\", (String)\"cde\", (String)\"array\"))), (\"a\"))\n // (new ArrayList(Arrays.asList((String)\"abc\", (String)\"bacd\", (String)\"array\")))\n public static ArrayList filterBySubstring(ArrayList strings, String substring) {\n ArrayList filteredStrings = new ArrayList();\n for (String s : strings) {\n if (s.contains(substring)) {\n filteredStrings.add(s);\n }\n }\n return filteredStrings;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a string s.\n // Your task is to check if the string is hapjava or not.\n // A string is hapjava if its length is at least 3 and every 3 consecutive letters are distinct\n // For example:\n // >>> isHappy((\"a\"))\n // (false)\n // >>> isHappy((\"aa\"))\n // (false)\n // >>> isHappy((\"abcd\"))\n // (true)\n // >>> isHappy((\"aabb\"))\n // (false)\n // >>> isHappy((\"adb\"))\n // (true)\n // >>> isHappy((\"xyy\"))\n // (false)\n public static boolean isHappy(String s) {\n if (s.length() < 3) {\n return false;\n }\n for (int i = 0; i < s.length() - 2; i++) {\n if (s.charAt(i) == s.charAt(i + 1) || s.charAt(i) == s.charAt(i + 2) || s.charAt(i + 1) == s.charAt(i + 2)) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // It is the last week of the semester and the teacher has to give the grades\n // to students. The teacher has been making her own algorithm for grading.\n // The only problem is, she has lost the code she used for grading.\n // She has given you an array array list of GPAs for some students and you have to write \n // a function that can output an array array list of letter grades using the following table:\n // GPA | Letter grade\n // 4.0 A+\n // > 3.7 A \n // > 3.3 A- \n // > 3.0 B+\n // > 2.7 B \n // > 2.3 B-\n // > 2.0 C+\n // > 1.7 C\n // > 1.3 C-\n // > 1.0 D+ \n // > 0.7 D \n // > 0.0 D-\n // 0.0 E\n // Example:\n // >>> gradeEquation((new ArrayList(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f))))\n // (new ArrayList(Arrays.asList((String)\"A+\", (String)\"B\", (String)\"C-\", (String)\"C\", (String)\"A-\")))\n public static ArrayList numericalLetterGrade(ArrayList grades) {\n ArrayList letterGrades = new ArrayList();\n for (Float grade : grades) {\n if (grade >= 4.0) {\n letterGrades.add(\"A+\");\n } else if (grade >= 3.7) {\n letterGrades.add(\"A\");\n } else if (grade >= 3.3) {\n letterGrades.add(\"A-\");\n } else if (grade >= 3.0) {\n letterGrades.add(\"B+\");\n } else if (grade >= 2.7) {\n letterGrades.add(\"B\");\n } else if (grade >= 2.3) {\n letterGrades.add(\"B-\");\n } else if (grade >= 2.0) {\n letterGrades.add(\"C+\");\n } else if (grade >= 1.7) {\n letterGrades.add(\"C\");\n } else if (grade >= 1.3) {\n letterGrades.add(\"C-\");\n } else if (grade >= 1.0) {\n letterGrades.add(\"D+\");\n } else if (grade >= 0.7) {\n letterGrades.add(\"D\");\n } else if (grade >= 0.0) {\n letterGrades.add(\"D-\");\n } else {\n letterGrades.add(\"E\");\n }\n }\n return letterGrades;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that takes a string and returns true if the string\n // length is a prime number or false otherwise\n // Examples\n // >>> primeLength((\"Hello\"))\n // (true)\n // >>> primeLength((\"abcdcba\"))\n // (true)\n // >>> primeLength((\"kittens\"))\n // (true)\n // >>> primeLength((\"orange\"))\n // (false)\n public static boolean primeLength(String string) {\n int length = string.length();\n if (length < 2) {\n return false;\n }\n for (int i = 2; i <= Math.sqrt(length); i++) {\n if (length % i == 0) {\n return false;\n }\n }\n return true;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer n, return the count of the numbers of n-digit\n // positive integers that start or end with 1.\n public static long startsOneEnds(long n) {\n if (n == 1) {\n return 1;\n }\n long count = 0;\n for (int i = 1; i <= n; i++) {\n if (i == 1 || i == n) {\n count += Math.pow(2, n - 1);\n } else {\n count += Math.pow(2, n - 2);\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a positive integer N, return the total sum of its digits in binary.\n // Example\n // >>> solve((1000l))\n // (\"1\")\n // >>> solve((150l))\n // (\"110\")\n // >>> solve((147l))\n // (\"1100\")\n // Variables:\n // @N integer\n // Constraints: 0 \u2264 N \u2264 10000.\n // Output:\n // a string of binary number\n public static String solve(long N) {\n String binary = Long.toBinaryString(N);\n int sum = 0;\n for (char c : binary.toCharArray()) {\n sum += Character.getNumericValue(c);\n }\n return Integer.toBinaryString(sum);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a non-empty array list of integers lst. add the even elements that are at odd indices..\n // Examples:\n // >>> add((new ArrayList(Arrays.asList((long)4l, (long)2l, (long)6l, (long)7l))))\n // (2l)\n public static long add(ArrayList lst) {\n long sum = 0;\n for (int i = 1; i < lst.size(); i += 2) {\n if (lst.get(i) % 2 == 0) {\n sum += lst.get(i);\n }\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that takes a string and returns an ordered version of it.\n // Ordered version of string, is a string where all words (separated by space)\n // are replaced by a new word where all the characters arranged in\n // ascending order based on ascii value.\n // Note: You should keep the order of words and blank spaces in the sentence.\n // For example:\n // >>> antiShuffle((\"Hi\"))\n // (\"Hi\")\n // >>> antiShuffle((\"hello\"))\n // (\"ehllo\")\n // >>> antiShuffle((\"Hello World!!!\"))\n // (\"Hello !!!Wdlor\")\n public static String antiShuffle(String s) {\n String[] words = s.split(\" \");\n StringBuilder result = new StringBuilder();\n for (String word : words) {\n char[] chars = word.toCharArray();\n Arrays.sort(chars);\n result.append(new String(chars));\n result.append(\" \");\n }\n return result.toString().trim();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given a 2 dimensional data, as a nested array lists,\n // which is similar to matrix, however, unlike matrices,\n // each row may contain a different number of columns.\n // Given lst, and integer x, find integers x in the array list,\n // and return array list of pairs, [(x1, y1), (x2, y2) ...] such that\n // each pair is a coordinate - (row, columns), starting with 0.\n // Sort coordinates initially by rows in ascending order.\n // Also, sort coordinates of the row by columns in descending order.\n // Examples:\n // >>> getRow((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)), (ArrayList)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)1l, (long)6l)), (ArrayList)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))))), (1l))\n // (new ArrayList>(Arrays.asList((Pair)Pair.with(0l, 0l), (Pair)Pair.with(1l, 4l), (Pair)Pair.with(1l, 0l), (Pair)Pair.with(2l, 5l), (Pair)Pair.with(2l, 0l))))\n // >>> getRow((new ArrayList>(Arrays.asList())), (1l))\n // (new ArrayList>(Arrays.asList()))\n // >>> getRow((new ArrayList>(Arrays.asList((ArrayList)new ArrayList(Arrays.asList()), (ArrayList)new ArrayList(Arrays.asList((long)1l)), (ArrayList)new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l))))), (3l))\n // (new ArrayList>(Arrays.asList((Pair)Pair.with(2l, 2l))))\n public static ArrayList> getRow(ArrayList> lst, long x) {\n ArrayList> res = new ArrayList<>();\n for (long i = 0; i < lst.size(); i++) {\n ArrayList row = lst.get((int)i);\n for (long j = 0; j < row.size(); j++) {\n if (row.get((int)j) == x) {\n res.add(Pair.with(i, j));\n }\n }\n }\n Collections.sort(res, new Comparator>() {\n public int compare(Pair p1, Pair p2) {\n if (p1.getValue0() == p2.getValue0()) {\n return p2.getValue1().compareTo(p1.getValue1());\n }\n return p1.getValue0().compareTo(p2.getValue0());\n }\n });\n return res;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given an array array list of non-negative integers, return a cojava of the given array array list after sorting,\n // you will sort the given array array list in ascending order if the sum( first index value, last index value) is odd,\n // or sort it in descending order if the sum( first index value, last index value) is even.\n // Note:\n // * don't change the given array array list.\n // Examples:\n // >>> sortArray((new ArrayList(Arrays.asList())))\n // (new ArrayList(Arrays.asList()))\n // >>> sortArray((new ArrayList(Arrays.asList((long)5l))))\n // (new ArrayList(Arrays.asList((long)5l)))\n // >>> sortArray((new ArrayList(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l))))\n // (new ArrayList(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))\n // >>> sortArray((new ArrayList(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l, (long)6l))))\n // (new ArrayList(Arrays.asList((long)6l, (long)5l, (long)4l, (long)3l, (long)2l, (long)1l, (long)0l)))\n public static ArrayList sortArray(ArrayList array) {\n ArrayList result = new ArrayList(array);\n if (result.size() == 0) {\n return result;\n }\n long sum = result.get(0) + result.get(result.size() - 1);\n if (sum % 2 == 0) {\n Collections.sort(result, Collections.reverseOrder());\n } else {\n Collections.sort(result);\n }\n return result;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function encrypt that takes a string as an argument and\n // returns a string encrypted with the alphabet being rotated. \n // The alphabet should be rotated in a manner such that the letters \n // shift down by two multiplied to two places.\n // For example:\n // >>> encrypt((\"hi\"))\n // (\"lm\")\n // >>> encrypt((\"asdfghjkl\"))\n // (\"ewhjklnop\")\n // >>> encrypt((\"gf\"))\n // (\"kj\")\n // >>> encrypt((\"et\"))\n // (\"ix\")\n public static String encrypt(String s) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (Character.isLetter(c)) {\n int shift = (Character.isUpperCase(c) ? 'A' : 'a');\n c = (char) (((c - shift + 2 * 2) % 26) + shift);\n }\n sb.append(c);\n }\n return sb.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // For a given array list of integers, return a pair consisting of a sum and a product of all the integers in an array array list.\n // Empty sum should be equal to 0 and empty product should be equal to 1.\n // >>> sumProduct((new ArrayList(Arrays.asList())))\n // (Pair.with(0l, 1l))\n // >>> sumProduct((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))\n // (Pair.with(10l, 24l))\n public static Pair sumProduct(ArrayList numbers) {\n long sum = 0;\n long product = 1;\n for (long number : numbers) {\n sum += number;\n product *= number;\n }\n return Pair.with(sum, product);"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given an array array list of integers.\n // Write a function next_smallest() that returns the 2nd smallest element of the array list.\n // Return null if there is no such element.\n // >>> nextSmallest((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l))))\n // Optional.of(2l)\n // >>> nextSmallest((new ArrayList(Arrays.asList((long)5l, (long)1l, (long)4l, (long)3l, (long)2l))))\n // Optional.of(2l)\n // >>> nextSmallest((new ArrayList(Arrays.asList())))\n // Optional.empty()\n // >>> nextSmallest((new ArrayList(Arrays.asList((long)1l, (long)1l))))\n // Optional.empty()\n public static Optional nextSmallest(ArrayList lst) {\n if (lst.size() < 2) {\n return Optional.empty();\n }\n Collections.sort(lst);\n return Optional.of(lst.get(1));"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You'll be given a string of words, and your task is to count the number\n // of boredoms. A boredom is a sentence that starts with the word \"I\".\n // Sentences are delimited by '.', '?' or '!'.\n // For example:\n // >>> isBored((\"Hello world\"))\n // (0l)\n // >>> isBored((\"The sky is blue. The sun is shining. I love this weather\"))\n // (1l)\n public static long isBored(String S) {\n String[] sentences = S.split(\"[.!?]\");\n long boredomCount = 0;\n for (String sentence : sentences) {\n if (sentence.trim().startsWith(\"I\")) {\n boredomCount++;\n }\n }\n return boredomCount;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function that takes 3 numbers.\n // Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n // Returns false in any other cases.\n // Examples\n // >>> anyInt((float)5l, (float)2l, (float)7l)\n // (true)\n // >>> anyInt((float)3l, (float)2l, (float)2l)\n // (false)\n // >>> anyInt((float)3l, (float)-2l, (float)1l)\n // (true)\n // >>> anyInt((3.6f), (-2.2f), (float)2l)\n // (false)\n public static boolean anyInt(float x, float y, float z) {\n // Check if all numbers are integers\n if (x % 1 != 0 || y % 1 != 0 || z % 1 != 0) {\n return false;\n }\n // Check if one of the numbers is equal to the sum of the other two\n if (x == y + z || y == x + z || z == x + y) {\n return true;\n }\n return false;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Write a function that takes a message, and encodes in such a \n // way that it swaps case of all letters, replaces all vowels in \n // the message with the letter that appears 2 places ahead of that \n // vowel in the english alphabet. \n // Assume only letters. \n // Examples:\n // >>> encode((\"test\"))\n // (\"TGST\")\n // >>> encode((\"This is a message\"))\n // (\"tHKS KS C MGSSCGG\")\n public static String encode(String message) {\n StringBuilder encodedMessage = new StringBuilder();\n for (int i = 0; i < message.length(); i++) {\n char c = message.charAt(i);\n if (Character.isLetter(c)) {\n if (Character.isUpperCase(c)) {\n c = Character.toLowerCase(c);\n } else {\n c = Character.toUpperCase(c);\n }\n switch (c) {\n case 'a':\n c = 'c';\n break;\n case 'e':\n c = 'g';\n break;\n case 'i':\n c = 'k';\n break;\n case 'o':\n c = 'm';\n break;\n case 'u':\n c = 'q';\n break;\n }\n }\n encodedMessage.append(c);\n }\n return encodedMessage.toString();"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // You are given an array array list of integers.\n // You need to find the largest prime value and return the sum of its digits.\n // Examples:\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l))))\n // (10l)\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l))))\n // (25l)\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l))))\n // (13l)\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l))))\n // (11l)\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l))))\n // (3l)\n // >>> skjkasdkd((new ArrayList(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l))))\n // (7l)\n public static long skjkasdkd(ArrayList lst) {\n long maxPrime = 0;\n for (long num : lst) {\n if (isPrime(num) && num > maxPrime) {\n maxPrime = num;\n }\n }\n long sum = 0;\n while (maxPrime > 0) {\n sum += maxPrime % 10;\n maxPrime /= 10;\n }\n return sum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a hash map, return true if all keys are strings in lower \n // case or all keys are strings in upper case, else return false.\n // The function should return false is the given hash map is empty.\n // Examples:\n // >>> checkDictCase((new HashMap(Map.of(\"a\", \"apple\", \"b\", \"banana\"))))\n // (true)\n // >>> checkDictCase((new HashMap(Map.of(\"a\", \"apple\", \"A\", \"banana\", \"B\", \"banana\"))))\n // (false)\n // >>> checkDictCase((new HashMap(Map.of(\"a\", \"apple\", 8l, \"banana\", \"a\", \"apple\"))))\n // (false)\n // >>> checkDictCase((new HashMap(Map.of(\"Name\", \"John\", \"Age\", \"36\", \"City\", \"Houston\"))))\n // (false)\n // >>> checkDictCase((new HashMap(Map.of(\"STATE\", \"NC\", \"ZIP\", \"12345\"))))\n // (true)\n public static boolean checkDictCase(HashMap dict) {\n if (dict.isEmpty()) {\n return false;\n }\n boolean allLower = true;\n boolean allUpper = true;\n for (String key : dict.keySet()) {\n if (!key.equals(key.toLowerCase())) {\n allLower = false;\n }\n if (!key.equals(key.toUpperCase())) {\n allUpper = false;\n }\n }\n return allLower || allUpper;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Implement a function that takes an non-negative integer and returns an array array list of the first n\n // integers that are prime numbers and less than n.\n // for example:\n // >>> countUpTo((5l))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l)))\n // >>> countUpTo((11l))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l)))\n // >>> countUpTo((0l))\n // (new ArrayList(Arrays.asList()))\n // >>> countUpTo((20l))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l)))\n // >>> countUpTo((1l))\n // (new ArrayList(Arrays.asList()))\n // >>> countUpTo((18l))\n // (new ArrayList(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l)))\n public static ArrayList countUpTo(long n) {\n ArrayList primes = new ArrayList();\n for (long i = 2; i < n; i++) {\n boolean isPrime = true;\n for (long j = 2; j <= Math.sqrt(i); j++) {\n if (i % j == 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) {\n primes.add(i);\n }\n }\n return primes;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Complete the function that takes two integers and returns \n // the product of their unit digits.\n // Assume the input is always valid.\n // Examples:\n // >>> multiply((148l), (412l))\n // (16l)\n // >>> multiply((19l), (28l))\n // (72l)\n // >>> multiply((2020l), (1851l))\n // (0l)\n // >>> multiply((14l), (-15l))\n // (20l)\n public static long multiply(long a, long b) {\n long unitDigitA = Math.abs(a % 10);\n long unitDigitB = Math.abs(b % 10);\n return unitDigitA * unitDigitB;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Given a string s, count the number of uppercase vowels in even indices.\n // For example:\n // >>> countUpper((\"aBCdEf\"))\n // (1l)\n // >>> countUpper((\"abcdefg\"))\n // (0l)\n // >>> countUpper((\"dBBE\"))\n // (0l)\n public static long countUpper(String s) {\n long count = 0;\n for (int i = 0; i < s.length(); i += 2) {\n char c = s.charAt(i);\n if (Character.isUpperCase(c) && \"AEIOU\".indexOf(c) != -1) {\n count++;\n }\n }\n return count;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // Create a function that takes a value (string) representing a number\n // and returns the closest integer to it. If the number is equidistant\n // from two integers, round it away from zero.\n // Examples\n // >>> closestInteger((\"10\"))\n // (10l)\n // >>> closestInteger((\"15.3\"))\n // (15l)\n // Note:\n // Rounding away from zero means that if the given number is equidistant\n // from two integers, the one you should return is the one that is the\n // farthest from zero. For example closest_integer(\"14.5\") should\n // return 15 and closest_integer(\"-14.5\") should return -15.\n public static long closestInteger(String value) {\n double num = Double.parseDouble(value);\n long roundedNum = Math.round(num);\n return roundedNum;"], ["import java.util.*;\nimport java.lang.reflect.*;\nimport org.javatuples.*;\nimport java.security.*;\nimport java.math.*;\nimport java.io.*;\nimport java.util.stream.*;\nclass Problem {\n // From a given array list of integers, generate an array array list of rolling maximum element found until given moment\n // in the sequence.\n // >>> rollingMax((new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)3l, (long)4l, (long)2l))))\n // (new ArrayList(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l, (long)4l)))\n public static ArrayList rollingMax(ArrayList numbers) {\n ArrayList result = new ArrayList<>();\n long max = Long.MIN_VALUE;\n for (Long num : numbers) {\n max = Math.max(max, num);\n result.add(max);\n }\n return result;"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-jl_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-jl_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..3eadd5897250fc654bbe66f974db4b1a1ba86d07 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-jl_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["\"\"\" Check if in given vector of numbers, are any two numbers closer to each other than\ngiven threshold.\n>>> has_close_elements([1.0, 2.0, 3.0], 0.5)\nfalse\n>>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\ntrue\"\"\"\nfunction has_close_elements(numbers::Vector{Float64}, threshold::Float64)::Bool\n for i in 1:length(numbers)-1\n for j in i+1:length(numbers)\n if abs(numbers[i] - numbers[j]) < threshold\n return true\n end\n end\n end\n return false\nend\n"], ["\"\"\"Given a positive integer n, you have to make a pile of n levels of stones.\nThe first level has n stones.\nThe number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\nReturn the number of stones in each level in a vector, where element at index\ni represents the number of stones in the level (i+1).\nExamples:\n>>> make_a_pile(3)\n[3, 5, 7]\"\"\"\nfunction make_a_pile(n::Int64)::Vector{Int64}\n stones = [n]\n for i in 1:n-1\n if n % 2 == 0\n n += 2\n else\n n += 2\n end\n push!(stones, n)\n end\n return stones\nend\n"], ["\"\"\"You will be given a string of words separated by commas or spaces. Your task is\nto split the string into words and return a vector of the words.\nFor example:\n>>> words_string(\"Hi, my name is John\")\n[\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n>>> words_string(\"One, two, three, four, five, six\")\n[\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\"\"\"\nfunction words_string(s::String)::Vector{String}\n return split(s, r\"[,\\s]+\")\nend\n"], ["\"\"\"This function takes two positive numbers x and y and returns the\nbiggest even integer number that is in the range [x, y] inclusive. If \nthere's no such number, then the function should return -1.\nFor example:\n>>> choose_num(12, 15)\n14\n>>> choose_num(13, 12)\n-1\"\"\"\nfunction choose_num(x::Int64, y::Int64)::Int64\n for i in y:-2:x\n if i % 2 == 0\n return i\n end\n end\n return -1\nend\n"], ["\"\"\"You are given two positive integers n and m, and your task is to compute the\naverage of the integers from n through m (including n and m). \nRound the answer to the nearest integer and convert that to binary.\nIf n is greater than m, return -1.\nExample:\n>>> rounded_avg(1, 5)\n\"0b11\"\n>>> rounded_avg(7, 5)\n-1\n>>> rounded_avg(10, 20)\n\"0b1111\"\n>>> rounded_avg(20, 33)\n\"0b11010\"\"\"\"\nfunction rounded_avg(n::Int64, m::Int64)::Union{String, Int64}\n if n > m\n return -1\n end\n avg = round(Int64, (n + m) / 2)\n return bin(avg)\nend\n"], ["\"\"\"Given a vector of positive integers x. return a sorted vector of all \nelements that hasn't any even digit.\nNote: Returned vector should be sorted in increasing order.\nFor example:\n>>> unique_digits([15, 33, 1422, 1])\n[1, 15, 33]\n>>> unique_digits([152, 323, 1422, 10])\n[]\"\"\"\nfunction unique_digits(x::Vector{Int64})::Vector{Int64}\n result = []\n for num in x\n has_even_digit = false\n for digit in string(num)\n if digit in \"02468\"\n has_even_digit = true\n break\n end\n end\n if !has_even_digit\n push!(result, num)\n end\n end\n sort(result)\nend\n"], ["\"\"\"Given a vector of integers, sort the integers that are between 1 and 9 inclusive,\nreverse the resulting vector, and then replace each digit by its corresponding name from\n\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\nFor example:\n>>> by_length([2, 1, 1, 4, 5, 8, 2, 3])\n[\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n If the vector is empty, return an empty vector:\n>>> by_length([])\n[]\n If the vector has any strange number ignore it:\n>>> by_length([1, -1, 55])\n[\"One\"]\"\"\"\nfunction by_length(arr::Vector{Int64})::Vector{String}\n names = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"]\n filtered = filter(x -> 1 <= x <= 9, arr)\n sorted = sort(filtered)\n reversed = reverse(sorted)\n result = map(x -> names[x], reversed)\n return result\nend\n"], ["\"\"\" Implement the function f that takes n as a parameter,\nand returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even\nor the sum of numbers from 1 to i otherwise.\ni starts from 1.\nthe factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\nExample:\n>>> f(5)\n[1, 2, 6, 24, 15]\"\"\"\nfunction f(n::Int64)::Vector{Int64}\n result = Vector{Int64}(undef, n)\n for i in 1:n\n if i % 2 == 0\n result[i] = factorial(i)\n else\n result[i] = sum(1:i)\n end\n end\n return result\nend\n"], ["\"\"\"Given a positive integer n, return a tuple that has the number of even and odd\ninteger palindromes that fall within the range(1, n), inclusive.\nExample 1:\n>>> even_odd_palindrome(3)\n(1, 2)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\nExample 2:\n>>> even_odd_palindrome(12)\n(4, 6)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\nNote:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\"\"\"\nfunction even_odd_palindrome(n::Int64)::Tuple{Int64, Int64}\n even_count = 0\n odd_count = 0\n for i in 1:n\n if is_palindrome(i)\n if i % 2 == 0\n even_count += 1\n else\n odd_count += 1\n end\n end\n end\n return (even_count, odd_count)\nend"], ["\"\"\"Write a function count_nums which takes a vector of integers and returns\nthe number of elements which has a sum of digits > 0.\nIf a number is negative, then its first signed digit will be negative:\ne.g. -123 has signed digits -1, 2, and 3.\n>>> count_nums([])\n0\n>>> count_nums([-1, 11, -11])\n1\n>>> count_nums([1, 1, 2])\n3\"\"\"\nfunction count_nums(arr::Vector{Int64})::Int64\n count = 0\n for num in arr\n if num < 0\n num = -num\n end\n sum_digits = sum(parse(Int64, string(digit))) for digit in string(num)\n if sum_digits > 0\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"We have a vector 'arr' of N integers arr[1], arr[2], ..., arr[N].The\nnumbers in the vector will be randomly ordered. Your task is to determine if\nit is possible to get a vector sorted in non-decreasing order by performing \nthe following operation on the given vector:\n You are allowed to perform right shift operation any number of times.\nOne right shift operation means shifting all elements of the vector by one\nposition in the right direction. The last element of the vector will be moved to\nthe starting position in the vector i.e. 0th index. \nIf it is possible to obtain the sorted vector by performing the above operation\nthen return true else return false.\nIf the given vector is empty then return true.\nNote: The given vector is guaranteed to have unique elements.\nFor Example:\n>>> move_one_ball([3, 4, 5, 1, 2])\ntrue\nExplanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given vector.\n>>> move_one_ball([3, 5, 4, 1, 2])\nfalse\nExplanation:It is not possible to get non-decreasing order for the given\n vector by performing any number of right shift operations.\"\"\"\nfunction move_one_ball(arr::Vector{Int64})::Bool\n n = length(arr)\n if n == 0\n return true\n end\n count = 0\n for i in 1:n\n if arr[i] > arr[(i % n) + 1]\n count += 1\n end\n end\n return count <= 1\nend\n"], ["\"\"\" Find the shortest palindrome that begins with a supplied string.\nAlgorithm idea is simple:\n- Find the longest postfix of supplied string that is a palindrome.\n- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n>>> make_palindrome(\"\")\n\"\"\n>>> make_palindrome(\"cat\")\n\"catac\"\n>>> make_palindrome(\"cata\")\n\"catac\"\"\"\"\nfunction make_palindrome(string::String)::String\n n = length(string)\n for i in n:-1:1\n if string[1:i] == reverse(string[i+1:n])\n return string * reverse(string[1:i])\n end\n end\n return string * reverse(string)\nend\n"], ["\"\"\"In this problem, you will implement a function that takes two vectors of numbers,\nand determines whether it is possible to perform an exchange of elements\nbetween them to make lst1 a vector of only even numbers.\nThere is no limit on the number of exchanged elements between lst1 and lst2.\nIf it is possible to exchange elements between the lst1 and lst2 to make\nall the elements of lst1 to be even, return \"YES\".\nOtherwise, return \"NO\".\nFor example:\n>>> exchange([1, 2, 3, 4], [1, 2, 3, 4])\n\"YES\"\n>>> exchange([1, 2, 3, 4], [1, 5, 3, 4])\n\"NO\"\nIt is assumed that the input vectors will be non-empty.\"\"\"\nfunction exchange(lst1::Vector{Int64}, lst2::Vector{Int64})::String\n # Count the number of odd numbers in lst1\n num_odd_lst1 = count(x -> x % 2 != 0, lst1)\n # Count the number of even numbers in lst2\n num_even_lst2 = count(x -> x % 2 == 0, lst2)\n # If the number of odd numbers in lst1 is greater than the number of even numbers in lst2,\n # it is not possible to exchange elements to make all elements in lst1 even\n if num_odd_lst1 > num_even_lst2\n return \"NO\"\n else\n return \"YES\"\n end\nend\n"], ["\"\"\"Given a string representing a space separated lowercase letters, return a dictionary\nof the letter with the most repetition and containing the corresponding count.\nIf several letters have the same occurrence, return all of them.\nExample:\n>>> histogram(\"a b c\")\nDict(\"a\" => 1, \"b\" => 1, \"c\" => 1)\n>>> histogram(\"a b b a\")\nDict(\"a\" => 2, \"b\" => 2)\n>>> histogram(\"a b c a b\")\nDict(\"a\" => 2, \"b\" => 2)\n>>> histogram(\"b b b b a\")\nDict(\"b\" => 4)\n>>> histogram(\"\")\nDict()\"\"\"\nfunction histogram(test::String)::Dict{String, Int64}>\n letters = split(test)\n counts = Dict{String, Int64}()\n for letter in letters\n if letter in keys(counts)\n counts[letter] += 1\n else\n counts[letter] = 1\n end\n end\n max_count = maximum(values(counts))\n result = Dict{String, Int64}()\n for (letter, count) in counts\n if count == max_count\n result[letter] = count\n end\n end\n return result\nend\n"], ["\"\"\"Task\nWe are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\nthen check if the result string is palindrome.\nA string is called palindrome if it reads the same backward as forward.\nYou should return a tuple containing the result string and true/false for the check.\nExample\n>>> reverse_delete(\"abcde\", \"ae\")\n(\"bcd\", false)\n>>> reverse_delete(\"abcdef\", \"b\")\n(\"acdef\", false)\n>>> reverse_delete(\"abcdedcba\", \"ab\")\n(\"cdedc\", true)\"\"\"\nfunction reverse_delete(s::String, c::String)::Tuple{String, Bool}\n # Delete all characters in s that are equal to any character in c\n s_filtered = filter(x -> !(x in c), s)\n # Check if the result string is a palindrome\n is_palindrome = s_filtered == reverse(s_filtered)\n # Return a tuple containing the result string and true/false for the check\n return (s_filtered, is_palindrome)\nend\n"], ["\"\"\"Given a vector of strings, where each string consists of only digits, return a vector.\nEach element i of the output should be \"the number of odd elements in the\nstring i of the input.\" where all the i's should be replaced by the number\nof odd digits in the i'th string of the input.\n>>> odd_count([\"1234567\"])\n[\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n>>> odd_count([\"3\", \"11111111\"])\n[\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\"\"\"\nfunction odd_count(lst::Vector{String})::Vector{String}\n result = []\n for str in lst\n count = 0\n for char in str\n if parse(Int, char) % 2 != 0\n count += 1\n end\n end\n push!(result, \"the number of odd elements $(count)n the str$(count)ng $(count) of the $(count)nput.\")\n end\n return result\nend\n"], ["\"\"\"Given a vector of integers nums, find the minimum sum of any non-empty sub-vector\nof nums.\nExample\n>>> minSubArraySum([2, 3, 4, 1, 2, 4])\n1\n>>> minSubArraySum([-1, -2, -3])\n-6\"\"\"\nfunction minSubArraySum(nums::Vector{Int64})::Int64\n minSum = nums[1]\n currSum = 0\n for num in nums\n currSum += num\n if currSum < minSum\n minSum = currSum\n end\n if currSum > 0\n currSum = 0\n end\n end\n return minSum\nend\n"], ["\"\"\"You are given a rectangular grid of wells. Each row represents a single well,\nand each 1 in a row represents a single unit of water.\nEach well has a corresponding bucket that can be used to extract water from it, \nand all buckets have the same capacity.\nYour task is to use the buckets to empty the wells.\nOutput the number of times you need to lower the buckets.\nExample 1:\n>>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)\n6\nExample 2:\n>>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)\n5\nExample 3:\n>>> max_fill([[0, 0, 0], [0, 0, 0]], 5)\n0\nConstraints:\n * all wells have the same length\n * 1 <= grid.length <= 10^2\n * 1 <= grid[:,1].length <= 10^2\n * grid[i][j] -> 0 | 1\n * 1 <= capacity <= 10\"\"\"\nfunction max_fill(grid::Vector{Vector{Int64}}, capacity::Int64)::Int64\n num_rows = length(grid)\n num_cols = length(grid[1])\n num_buckets = 0\n for col = 1:num_cols\n num_wells = 0\n for row = 1:num_rows\n num_wells += grid[row][col]\n end\n num_buckets += ceil(num_wells / capacity)\n end\n return num_buckets\nend\n"], ["\"\"\"In this Kata, you have to sort a vector of non-negative integers according to\nnumber of ones in their binary representation in ascending order.\nFor similar number of ones, sort based on decimal value.\nIt must be implemented like this:\n>>> sort_array([1, 5, 2, 3, 4])\n[1, 2, 3, 4, 5]\n>>> sort_array([-2, -3, -4, -5, -6])\n[-6, -5, -4, -3, -2]\n>>> sort_array([1, 0, 2, 3, 4])\n[0, 1, 2, 3, 4]\"\"\"\nfunction sort_array(arr::Vector{Int64})::Vector{Int64}\n ones_count = [count_ones(i) for i in arr]\n sorted_arr = sortperm(ones_count)\n return arr[sorted_arr]\nend"], ["\"\"\"Given a string s and a natural number n, you have been tasked to implement \na function that returns a vector of all words from string s that contain exactly \nn consonants, in order these words appear in the string s.\nIf the string s is empty then the function should return an empty vector.\nNote: you may assume the input string contains only letters and spaces.\nExamples:\n>>> select_words(\"Mary had a little lamb\", 4)\n[\"little\"]\n>>> select_words(\"Mary had a little lamb\", 3)\n[\"Mary\", \"lamb\"]\n>>> select_words(\"simple white space\", 2)\n[]\n>>> select_words(\"Hello world\", 4)\n[\"world\"]\n>>> select_words(\"Uncle sam\", 3)\n[\"Uncle\"]\"\"\"\nfunction select_words(s::String, n::Int64)::Vector{String}\n words = split(s)\n selected_words = String[]\n for word in words\n consonants = filter(c -> !(c in \"aeiouAEIOU\"), word)\n if length(consonants) == n\n push!(selected_words, word)\n end\n end\n return selected_words\nend\n"], ["\"\"\"You are given a word. Your task is to find the closest vowel that stands between \ntwo consonants from the right side of the word (case sensitive).\nVowels in the beginning and ending doesn't count. Return empty string if you didn't\nfind any vowel met the above condition. \nYou may assume that the given string contains English letter only.\nExample:\n>>> get_closest_vowel(\"yogurt\")\n\"u\"\n>>> get_closest_vowel(\"FULL\")\n\"U\"\n>>> get_closest_vowel(\"quick\")\n\"\"\n>>> get_closest_vowel(\"ab\")\n\"\"\"\"\"\nfunction get_closest_vowel(word::String)::String\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n for i in length(word)-2:-1:2\n if word[i] \u2209 vowels && word[i+1] \u2208 vowels && word[i-1] \u2209 vowels\n return string(word[i+1])\n end\n end\n return \"\"\nend\n"], ["\"\"\"You are given a vector of two strings, both strings consist of open\nparentheses '(' or close parentheses ')' only.\nYour job is to check if it is possible to concatenate the two strings in\nsome order, that the resulting string will be good.\nA string S is considered to be good if and only if all parentheses in S\nare balanced. For example: the string '(())()' is good, while the string\n'())' is not.\nReturn 'Yes' if there's a way to make a good string, and return 'No' otherwise.\nExamples:\n>>> match_parens([\"()(\", \")\"])\n\"Yes\"\n>>> match_parens([\")\", \")\"])\n\"No\"\"\"\"\nfunction match_parens(lst::Vector{String})::String\n s = join(lst)\n stack = []\n for c in s\n if c == '('\n push!(stack, c)\n elseif c == ')'\n if isempty(stack)\n return \"No\"\n else\n pop!(stack)\n end\n end\n end\n return isempty(stack) ? \"Yes\" : \"No\"\nend\n"], ["\"\"\" Input are two strings a and b consisting only of 1s and 0s.\nPerform binary XOR on these inputs and return result also as a string.\n>>> string_xor(\"010\", \"110\")\n\"100\"\"\"\"\nfunction string_xor(a::String, b::String)::String\n result = \"\"\n for i in 1:length(a)\n if a[i] == b[i]\n result *= \"0\"\n else\n result *= \"1\"\n end\n end\n return result\nend\n"], ["\"\"\"Given a vector arr of integers and a positive integer k, return a sorted vector \nof length k with the maximum k numbers in arr.\nExample 1:\n>>> maximum([-3, -4, 5], 3)\n[-4, -3, 5]\nExample 2:\n>>> maximum([4, -4, 4], 2)\n[4, 4]\nExample 3:\n>>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)\n[2]\nNote:\n 1. The length of the vector will be in the range of [1, 1000].\n 2. The elements in the vector will be in the range of [-1000, 1000].\n 3. 0 <= k <= len(arr)\"\"\"\nfunction maximum(arr::Vector{Int64}, k::Int64)::Vector{Int64}\n return sort(arr, rev=true)[1:k]\nend\n"], ["\"\"\"Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions.\nExamples\n>>> solution([5, 8, 7, 1])\n12\n>>> solution([3, 3, 3, 3, 3])\n9\n>>> solution([30, 13, 24, 321])\n0\"\"\"\nfunction solution(lst::Vector{Int64})::Int64\n return sum(lst[2:2:end] .% 2 .* lst[1:2:end])\nend\n"], ["\"\"\"Given a non-empty vector of integers arr and an integer k, return\nthe sum of the elements with at most two digits from the first k elements of arr.\nExample:\n>>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)\n24\nConstraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\"\"\"\nfunction add_elements(arr::Vector{Int64}, k::Int64)::Int64\n sum = 0\n for i in 1:k\n if arr[i] < 100\n sum += arr[i]\n end\n end\n return sum\nend\n"], ["\"\"\"Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence.\nThe Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\nas follows: start with any positive integer n. Then each term is obtained from the \nprevious term as follows: if the previous term is even, the next term is one half of \nthe previous term. If the previous term is odd, the next term is 3 times the previous\nterm plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\nNote: \n 1. Collatz(1) is [1].\n 2. returned vector sorted in increasing order.\nFor example:\nget_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n>>> get_odd_collatz(5)\n[1, 5]\"\"\"\nfunction get_odd_collatz(n::Int64)::Vector{Int64}\n collatz_seq = [n]\n while n != 1\n if n % 2 == 0\n n = n \ufffd 2\n else\n n = 3n + 1\n end\n push!(collatz_seq, n)\n end\n return sort(filter(x -> x % 2 != 0, collatz_seq))\nend\n"], ["\"\"\"You have to write a function which validates a given date string and\nreturns true if the date is valid otherwise false.\nThe date is valid if all of the following rules are satisfied:\n1. The date string is not empty.\n2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n3. The months should not be less than 1 or higher than 12.\n4. The date should be in the format: mm-dd-yyyy\n>>> valid_date(\"03-11-2000\")\ntrue\n>>> valid_date(\"15-01-2012\")\nfalse\n>>> valid_date(\"04-0-2040\")\nfalse\n>>> valid_date(\"06-04-2020\")\ntrue\n>>> valid_date(\"06/04/2020\")\nfalse\"\"\"\nfunction valid_date(date::String)::Bool\n # Check if the date string is not empty\n if isempty(date)\n return false\n end"], ["\"\"\"Given a string of words, return a vector of words split on whitespace, if no whitespaces exists in the text you\nshould split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\nalphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\nExamples\n>>> split_words(\"Hello world!\")\n[\"Hello\", \"world!\"]\n>>> split_words(\"Hello,world!\")\n[\"Hello\", \"world!\"]\n>>> split_words(\"abcdef\")\n3\"\"\"\nfunction split_words(txt::String)::Union{Vector{String}, Int64}\n if occursin(r\"\\s\", txt)\n return split(txt)\n elseif occursin(\",\", txt)\n return split(txt, \",\")\n else\n count = 0\n for c in txt\n if islowercase(c) && c % 2 == 1\n count += 1\n end\n end\n return count\n end\nend\n"], ["\"\"\"Given a vector of numbers, return whether or not they are sorted\nin ascending order. If vector has more than 1 duplicate of the same\nnumber, return false. Assume no negative numbers and only integers.\nExamples\n>>> is_sorted([5])\ntrue\n>>> is_sorted([1, 2, 3, 4, 5])\ntrue\n>>> is_sorted([1, 3, 2, 4, 5])\nfalse\n>>> is_sorted([1, 2, 3, 4, 5, 6])\ntrue\n>>> is_sorted([1, 2, 3, 4, 5, 6, 7])\ntrue\n>>> is_sorted([1, 3, 2, 4, 5, 6, 7])\nfalse\n>>> is_sorted([1, 2, 2, 3, 3, 4])\ntrue\n>>> is_sorted([1, 2, 2, 2, 3, 4])\nfalse\"\"\"\nfunction is_sorted(lst::Vector{Int64})::Bool\n for i in 2:length(lst)\n if lst[i] < lst[i-1]\n return false\n end\n end\n return true\nend\n"], ["\"\"\"You are given two intervals,\nwhere each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\nThe given intervals are closed which means that the interval (start, end)\nincludes both start and end.\nFor each given interval, it is assumed that its start is less or equal its end.\nYour task is to determine whether the length of intersection of these two \nintervals is a prime number.\nExample, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\nwhich its length is 1, which not a prime number.\nIf the length of the intersection is a prime number, return \"YES\",\notherwise, return \"NO\".\nIf the two intervals don't intersect, return \"NO\".\n[input/output] samples:\n>>> intersection((1, 2), (2, 3))\n\"NO\"\n>>> intersection((-1, 1), (0, 4))\n\"NO\"\n>>> intersection((-3, -1), (-5, 5))\n\"YES\"\"\"\"\nfunction intersection(interval1::Tuple{Int64, Int64}, interval2::Tuple{Int64, Int64})::String\n start1, end1 = interval1\n start2, end2 = interval2\n intersection_start = max(start1, start2)\n intersection_end = min(end1, end2)\n intersection_length = intersection_end - intersection_start + 1\n if intersection_length <= 1\n return \"NO\"\n end\n for i in 2:intersection_length-1\n if intersection_length % i == 0\n return \"NO\"\n end\n end\n return \"YES\"\nend\n"], ["\"\"\"You are given a vector arr of integers and you need to return\nsum of magnitudes of integers multiplied by product of all signs\nof each number in the vector, represented by 1, -1 or 0.\nNote: return nothing for empty arr.\nExample:\n>>> prod_signs([1, 2, 2, -4])\n9\n>>> prod_signs([0, 1])\n0\n>>> prod_signs([])\nnothing\"\"\"\nfunction prod_signs(arr::Vector{Int64})::Union{Int64, Nothing}\n if isempty(arr)\n return nothing\n end\n sum_magnitudes = sum(abs(x) for x in arr)\n product_signs = prod(x == 0 ? 0 : x > 0 ? 1 : -1 for x in arr)\n return sum_magnitudes * product_signs\nend\n"], ["\"\"\"Given a grid with N rows and N columns (N >= 2) and a positive integer k, \neach cell of the grid contains a value. Every integer in the range [1, N * N]\ninclusive appears exactly once on the cells of the grid.\nYou have to find the minimum path of length k in the grid. You can start\nfrom any cell, and in each step you can move to any of the neighbor cells,\nin other words, you can go to cells which share an edge with you current\ncell.\nPlease note that a path of length k means visiting exactly k cells (not\nnecessarily distinct).\nYou CANNOT go off the grid.\nA path A (of length k) is considered less than a path B (of length k) if\nafter making the ordered vectors of the values on the cells that A and B go\nthrough (let's call them lst_A and lst_B), lst_A is lexicographically less\nthan lst_B, in other words, there exist an integer index i (1 <= i <= k)\nsuch that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\nlst_A[j] = lst_B[j].\nIt is guaranteed that the answer is unique.\nReturn an ordered vector of the values on the cells that the minimum path go through.\nExamples: \n>>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)\n[1, 2, 1]\n>>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)\n[1]\"\"\"\nfunction minPath(grid::Vector{Vector{Int64}}, k::Int64)::Vector{Int64}\n n = length(grid)\n dp = [[[0 for _ in 1:k] for _ in 1:n] for _ in 1:n]\n for i in 1:n, j in 1:n\n dp[i][j][1] = grid[i][j]\n end\n for l in 2:k\n for i in 1:n, j in 1:n\n for di in -1:1, dj in -1:1\n if di == 0 && dj == 0\n continue\n end\n ni = i + di\n nj = j + dj\n if ni < 1 || ni > n || nj < 1 || nj > n\n continue\n end\n dp[i][j][l] = min(dp[i][j][l], dp[ni][nj][l-1])\n end\n end\n end\n ans = [0 for _ in 1:k]\n for i in 1:n, j in 1:n\n ans[1] = min(ans[1], dp[i][j][k])\n end\n for l in 2:k\n for i in 1:n, j in 1:n\n if dp[i][j][l] == ans[l-1]\n ans[l] = grid[i][j]\n break\n end\n end\n end\n return ans\nend\n"], ["\"\"\" Out of vector of strings, return the longest one. Return the first one in case of multiple\nstrings of the same length. Return nothing in case the input vector is empty.\n>>> longest([])\nnothing\n>>> longest([\"a\", \"b\", \"c\"])\n\"a\"\n>>> longest([\"a\", \"bb\", \"ccc\"])\n\"ccc\"\"\"\"\nfunction longest(strings::Vector{String})::Union{String, Nothing}\n isempty(strings) && return nothing\n max_length = 0\n longest_string = \"\"\n for string in strings\n if length(string) > max_length\n max_length = length(string)\n longest_string = string\n end\n end\n return longest_string\nend\n"], ["\"\"\"Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \nthe last couple centuries. However, what people don't know is Tribonacci sequence.\nTribonacci sequence is defined by the recurrence:\ntri(1) = 3\ntri(n) = 1 + n / 2, if n is even.\ntri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\nFor example:\ntri(2) = 1 + (2 / 2) = 2\ntri(4) = 3\ntri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \nYou are given a non-negative integer number n, you have to a return a vector of the \nfirst n + 1 numbers of the Tribonacci sequence.\nExamples:\n>>> tri(3)\n[1, 3, 2, 8]\"\"\"\nfunction tri(n::Int64)::Vector{Int64}\n if n == 0\n return [0]\n elseif n == 1\n return [0, 3]\n else\n seq = [0, 3]\n for i in 2:n\n if i % 2 == 0\n push!(seq, 1 + i / 2)\n else\n push!(seq, seq[i-1] + seq[i-2] + seq[i+1])\n end\n end\n return seq\n end\nend\n"], ["\"\"\"Given a positive integer n, return the product of the odd digits.\nReturn 0 if all digits are even.\nFor example:\n>>> digits(1)\n1\n>>> digits(4)\n0\n>>> digits(235)\n15\"\"\"\nfunction digits(n::Int64)::Int64\n product = 1\n for digit in string(n)\n if digit % 2 != 0\n product *= parse(Int64, digit)\n end\n end\n return product\nend\n"], ["\"\"\"Create a function that takes a string as input which contains only square brackets.\nThe function should return true if and only if there is a valid subsequence of brackets \nwhere at least one bracket in the subsequence is nested.\n>>> is_nested(\"[[]]\")\ntrue\n>>> is_nested(\"[]]]]]]][[[[[]\")\nfalse\n>>> is_nested(\"[][]\")\nfalse\n>>> is_nested(\"[]\")\nfalse\n>>> is_nested(\"[[][]]\")\ntrue\n>>> is_nested(\"[[]][[\")\ntrue\"\"\"\nfunction is_nested(string::String)::Bool\n stack = []\n for bracket in string\n if bracket == '['\n push!(stack, bracket)\n elseif bracket == ']'\n if isempty(stack)\n return false\n else\n popfirst!(stack)\n end\n end\n end\n return !isempty(stack)\nend\n"], ["\"\"\"You are given a vector of numbers.\nYou need to return the sum of squared numbers in the given vector,\nround each element in the vector to the upper int(Ceiling) first.\nExamples:\n>>> lst([1.0, 2.0, 3.0])\n14\n>>> lst([1.0, 4.0, 9.0])\n98\n>>> lst([1.0, 3.0, 5.0, 7.0])\n84\n>>> lst([1.4, 4.2, 0.0])\n29\n>>> lst([-2.4, 1.0, 1.0])\n6\"\"\"\nfunction sum_squares(lst::Vector{Float64})::Int64\n return sum(ceil.(lst).^2)\nend\n"], ["\"\"\"Create a function that returns true if the last character\nof a given string is an alphabetical character and is not\na part of a word, and false otherwise.\nNote: \"word\" is a group of characters separated by space.\nExamples:\n>>> check_if_last_char_is_a_letter(\"apple pie\")\nfalse\n>>> check_if_last_char_is_a_letter(\"apple pi e\")\ntrue\n>>> check_if_last_char_is_a_letter(\"apple pi e \")\nfalse\n>>> check_if_last_char_is_a_letter(\"\")\nfalse\"\"\"\nfunction check_if_last_char_is_a_letter(txt::String)::Bool\n if isempty(txt)\n return false\n end\n last_char = txt[end]\n if !isalpha(last_char)\n return false\n end\n if isspace(txt[end-1])\n return false\n end\n return true\nend\n"], ["\"\"\"Create a function which returns the largest index of an element which\nis not greater than or equal to the element immediately preceding it. If\nno such element exists then return -1. The given vector will not contain\nduplicate values.\nExamples:\n>>> can_arrange([1, 2, 4, 3, 5])\n3\n>>> can_arrange([1, 2, 3])\n-1\"\"\"\nfunction can_arrange(arr::Vector{Int64})::Int64\n for i in 2:length(arr)\n if arr[i] <= arr[i-1]\n return i-1\n end\n end\n return -1\nend\n"], ["\"\"\"Create a function that returns a tuple (a, b), where 'a' is\nthe largest of negative integers, and 'b' is the smallest\nof positive integers in a vector.\nIf there is no negative or positive integers, return them as nothing.\nExamples:\n>>> largest_smallest_integers([2, 4, 1, 3, 5, 7])\n(nothing, 1)\n>>> largest_smallest_integers([])\n(nothing, nothing)\n>>> largest_smallest_integers([0])\n(nothing, nothing)\"\"\"\nfunction largest_smallest_integers(lst::Vector{Int64})::Tuple{Union{Int64, Nothing}, Union{Int64, Nothing}}\n negatives = filter(x -> x < 0, lst)\n positives = filter(x -> x > 0, lst)\n if isempty(negatives) && isempty(positives)\n return (nothing, nothing)\n elseif isempty(negatives)\n return (nothing, minimum(positives))\n elseif isempty(positives)\n return (maximum(negatives), nothing)\n else\n return (maximum(negatives), minimum(positives))\n end\nend\n"], ["\"\"\"Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\nExample\n>>> is_equal_to_sum_even(4)\nfalse\n>>> is_equal_to_sum_even(6)\nfalse\n>>> is_equal_to_sum_even(8)\ntrue\"\"\"\nfunction is_equal_to_sum_even(n::Int64)::Bool\n if n % 4 != 0 || n < 8\n return false\n end\n return true\nend\n"], ["\"\"\"The Brazilian factorial is defined as:\nbrazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\nwhere n > 0\nFor example:\n>>> special_factorial(4)\n288\nThe function will receive an integer as input and should return the special\nfactorial of this integer.\"\"\"\nfunction special_factorial(n::Int64)::Int64\n result = 1\n for i in 1:n\n result *= factorial(i)\n end\n return result\nend\n"], ["\"\"\" Return a greatest common divisor of two integers a and b\n>>> greatest_common_divisor(3, 5)\n1\n>>> greatest_common_divisor(25, 15)\n5\"\"\"\nfunction greatest_common_divisor(a::Int64, b::Int64)::Int64\n while b != 0\n a, b = b, a % b\n end\n return a\nend\n"], ["\"\"\"Given a string text, replace all spaces in it with underscores, \nand if a string has more than 2 consecutive spaces, \nthen replace all consecutive spaces with - \n>>> fix_spaces(\" Example\")\n\"Example\"\n>>> fix_spaces(\" Example 1\")\n\"Example_1\"\n>>> fix_spaces(\" Example 2\")\n\"_Example_2\"\n>>> fix_spaces(\" Example 3\")\n\"_Example-3\"\"\"\"\nfunction fix_spaces(text::String)::String\n text = replace(text, \" \" => \"-\")\n text = replace(text, \" \" => \"_\")\n return text\nend\n"], ["\"\"\"Create a function which takes a string representing a file's name, and returns\n'Yes' if the the file's name is valid, and returns 'No' otherwise.\nA file's name is considered to be valid if and only if all the following conditions \nare met:\n- There should not be more than three digits ('0'-'9') in the file's name.\n- The file's name contains exactly one dot '.'\n- The substring before the dot should not be empty, and it starts with a letter from \nthe latin alphapet ('a'-'z' and 'A'-'Z').\n- The substring after the dot should be one of these: ['txt', 'exe', 'dll']\nExamples:\n>>> file_name_check(\"example.txt\")\n\"Yes\"\n>>> file_name_check(\"1example.dll\")\n\"No\"\"\"\"\nfunction file_name_check(file_name::String)::String\n # Check if there are more than three digits in the file name\n if length(filter(isdigit, file_name)) > 3\n return \"No\"\n end"], ["\"\"\"\"\nThis function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a \nmultiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \nchange the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \nExamples:\n>>> lst\n[1, 2, 3]\n>>> lst\n[]\n>>> lst\n[-1, -5, 2, -1, -5]\"\"\"\nfunction sum_squares(lst::Vector{Int64})::Int64\n sum = 0\n for i in 1:length(lst)\n if i % 3 == 0\n sum += lst[i]^2\n elseif i % 4 == 0 && i % 3 != 0\n sum += lst[i]^3\n else\n sum += lst[i]\n end\n end\n return sum\nend\n"], ["\"\"\"You are given a string representing a sentence,\nthe sentence contains some words separated by a space,\nand you have to return a string that contains the words from the original sentence,\nwhose lengths are prime numbers,\nthe order of the words in the new string should be the same as the original one.\nExample 1:\n>>> words_in_sentence(\"This is a test\")\n\"is\"\nExample 2:\n>>> words_in_sentence(\"lets go for swimming\")\n\"go for\"\nConstraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\"\"\"\nfunction words_in_sentence(sentence::String)::String\n words = split(sentence)\n prime_words = []\n for word in words\n if isprime(length(word))\n push!(prime_words, word)\n end\n end\n return join(prime_words, \" \")\nend\n"], ["\"\"\"Your task is to implement a function that will simplify the expression\nx * n. The function returns true if x * n evaluates to a whole number and false\notherwise. Both x and n, are string representation of a fraction, and have the following format,\n/ where both numerator and denominator are positive whole numbers.\nYou can assume that x, and n are valid fractions, and do not have zero as denominator.\n>>> simplify(\"1/5\", \"5/1\")\ntrue\n>>> simplify(\"1/6\", \"2/1\")\nfalse\n>>> simplify(\"7/10\", \"10/2\")\nfalse\"\"\"\nfunction simplify(x::String, n::String)::Bool\n x_num, x_den = parse.(Int, split(x, \"/\"))\n n_num, n_den = parse.(Int, split(n, \"/\"))\n return (x_num * n_den) % (x_den * n_num) == 0\nend\n"], ["\"\"\"Write a function which sorts the given vector of integers\nin ascending order according to the sum of their digits.\nNote: if there are several items with similar sum of their digits,\norder them based on their index in original vector.\nFor example:\n>>> order_by_points([1, 11, -1, -11, -12])\n[-1, -11, 1, -12, 11]\n>>> order_by_points([])\n[]\"\"\"\nfunction order_by_points(nums::Vector{Int64})::Vector{Int64}\n # Helper function to calculate the sum of digits of a number\n function sum_of_digits(num::Int64)::Int64\n sum = 0\n while num > 0\n sum += num % 10\n num = div(num, 10)\n end\n return sum\n end"], ["\"\"\"Write a function that takes a vector of numbers as input and returns \nthe number of elements in the vector that are greater than 10 and both \nfirst and last digits of a number are odd (1, 3, 5, 7, 9).\nFor example:\n>>> specialFilter([15, -73, 14, -15])\n1\n>>> specialFilter([33, -2, -3, 45, 21, 109])\n2\"\"\"\nfunction specialFilter(nums::Vector{Int64})::Int64\n count::Int64 = 0\n for num in nums\n if num > 10 && num % 2 != 0 && (num % 10) % 2 != 0\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\" You are given a positive integer n. You have to create an integer vector a of length n.\nFor each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\nReturn the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n Example :\n >>> get_max_triples(5)\n 1\nExplanation: \na = [1, 3, 7, 13, 21]\nThe only valid triple is (1, 7, 13).\"\"\"\nfunction get_max_triples(n::Int64)::Int64\n a = [i^2 - i + 1 for i in 1:n]\n count = 0\n for i in 1:n-2\n for j in i+1:n-1\n for k in j+1:n\n if (a[i] + a[j] + a[k]) % 3 == 0\n count += 1\n end\n end\n end\n end\n return count\nend\n"], ["\"\"\"Write a function that accepts a vector of strings as a parameter,\ndeletes the strings that have odd lengths from it,\nand returns the resulted vector with a sorted order,\nThe vector is always a vector of strings and never a vector of numbers,\nand it may contain duplicates.\nThe order of the vector should be ascending by length of each word, and you\nshould return the vector sorted by that rule.\nIf two words have the same length, sort the vector alphabetically.\nThe function should return a vector of strings in sorted order.\nYou may assume that all words will have the same length.\nFor example:\n>>> list_sort([\"aa\", \"a\", \"aaa\"])\n[\"aa\"]\n>>> list_sort([\"ab\", \"a\", \"aaa\", \"cd\"])\n[\"ab\", \"cd\"]\"\"\"\nfunction sorted_list_sum(lst::Vector{String})::Vector{String}\n even_lst = filter(x -> length(x) % 2 == 0, lst)\n sort(even_lst, by=length)\nend\n"], ["\"\"\" Return vector of all prefixes from shortest to longest of the input string\n>>> all_prefixes(\"abc\")\n[\"a\", \"ab\", \"abc\"]\"\"\"\nfunction all_prefixes(string::String)::Vector{String}\n prefixes = String[]\n for i in 1:length(string)\n push!(prefixes, string[1:i])\n end\n return prefixes\nend\n"], ["\"\"\"A simple program which should return the value of x if n is \na prime number and should return the value of y otherwise.\nExamples:\n>>> x_or_y(7, 34, 12)\n34\n>>> x_or_y(15, 8, 5)\n5\"\"\"\nfunction x_or_y(n::Int64, x::Int64, y::Int64)::Int64\n if isprime(n)\n return x\n else\n return y\n end\nend\n"], ["\"\"\"Given a vector of numbers, return the sum of squares of the numbers\nin the vector that are odd. Ignore numbers that are negative or not integers.\n>>> double_the_difference([1, 3, 2, 0])\n10\n>>> double_the_difference([-1, -2, 0])\n0\n>>> double_the_difference([9, -2])\n81\n>>> double_the_difference([0])\n0\nIf the input vector is empty, return 0.\"\"\"\nfunction double_the_difference(lst::Vector{Float64})::Int64\n sum = 0\n for num in lst\n if num >= 0 && isinteger(num) && num % 2 != 0\n sum += num^2\n end\n end\n return sum\nend\n"], ["\"\"\"I think we all remember that feeling when the result of some long-awaited\nevent is finally known. The feelings and thoughts you have at that moment are\ndefinitely worth noting down and comparing.\nYour task is to determine if a person correctly guessed the results of a number of matches.\nYou are given two vectors of scores and guesses of equal length, where each index shows a match. \nReturn a vector of the same length denoting how far off each guess was. If they have guessed correctly,\nthe value is 0, and if not, the value is the absolute difference between the guess and the score.\nexample:\n>>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])\n[0, 0, 0, 0, 3, 3]\n>>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2])\n[4, 4, 1, 0, 0, 6]\"\"\"\nfunction compare(game::Vector{Int64}, guess::Vector{Int64})::Vector{Int64}\n return abs.(game .- guess)\nend\n"], ["\"\"\"You will be given the name of a class (a string) and a vector of extensions.\nThe extensions are to be used to load additional classes to the class. The\nstrength of the extension is as follows: Let CAP be the number of the uppercase\nletters in the extension's name, and let SM be the number of lowercase letters \nin the extension's name, the strength is given by the fraction CAP - SM. \nYou should find the strongest extension and return a string in this \nformat: ClassName.StrongestExtensionName.\nIf there are two or more extensions with the same strength, you should\nchoose the one that comes first in the vector.\nFor example, if you are given \"Slices\" as the class and a vector of the\nextensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\nreturn 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n(its strength is -1).\nExample:\n>>> Strongest_Extension(\"my_class\", [\"AA\", \"Be\", \"CC\"])\n\"my_class.AA\"\"\"\"\nfunction Strongest_Extension(class_name::String, extensions::Vector{String})::String\n strengths = [sum(isupper.(extension)) - sum(islower.(extension)) for extension in extensions]\n strongest_index = findmax(strengths)[2]\n return \"$class_name.$(extensions[strongest_index])\"\nend\n"], ["\"\"\"You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n>>> cycpattern_check(\"abcd\", \"abd\")\nfalse\n>>> cycpattern_check(\"hello\", \"ell\")\ntrue\n>>> cycpattern_check(\"whassup\", \"psus\")\nfalse\n>>> cycpattern_check(\"abab\", \"baa\")\ntrue\n>>> cycpattern_check(\"efef\", \"eeff\")\nfalse\n>>> cycpattern_check(\"himenss\", \"simen\")\ntrue\"\"\"\nfunction cycpattern_check(a::String, b::String)::Bool\n n = length(b)\n for i in 1:n\n if b[i:end] in a && b[1:i-1] in a\n return true\n end\n end\n return false\nend\n"], ["\"\"\"Given an integer. return a tuple that has the number of even and odd digits respectively.\nExample:\n >>> even_odd_count(-12)\n (1, 1)\n >>> even_odd_count(123)\n (1, 2)\"\"\"\nfunction even_odd_count(num::Int64)::Tuple{Int64, Int64}\n num = abs(num)\n even_count = 0\n odd_count = 0\n while num > 0\n digit = num % 10\n if digit % 2 == 0\n even_count += 1\n else\n odd_count += 1\n end\n num = num \ufffd 10\n end\n return (even_count, odd_count)\nend\n"], ["\"\"\"Given a positive integer, obtain its roman numeral equivalent as a string,\nand return it in lowercase.\nRestrictions: 1 <= num <= 1000\nExamples:\n>>> int_to_mini_roman(19)\n\"xix\"\n>>> int_to_mini_roman(152)\n\"clii\"\n>>> int_to_mini_roman(426)\n\"cdxxvi\"\"\"\"\nfunction int_to_mini_roman(number::Int64)::String\n if number < 1 || number > 1000\n throw(DomainError(\"Number must be between 1 and 1000\"))\n end\n roman_numerals = [\"m\", \"cm\", \"d\", \"cd\", \"c\", \"xc\", \"l\", \"xl\", \"x\", \"ix\", \"v\", \"iv\", \"i\"]\n values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n result = \"\"\n for i in 1:length(values)\n while number >= values[i]\n result *= roman_numerals[i]\n number -= values[i]\n end\n end\n return lowercase(result)\nend\n"], ["\"\"\"Given the lengths of the three sides of a triangle. Return true if the three\nsides form a right-angled triangle, false otherwise.\nA right-angled triangle is a triangle in which one angle is right angle or \n90 degree.\nExample:\n>>> right_angle_triangle(3, 4, 5)\ntrue\n>>> right_angle_triangle(1, 2, 3)\nfalse\"\"\"\nfunction right_angle_triangle(a::Int64, b::Int64, c::Int64)::Bool\n sides = [a, b, c]\n sort(sides)\n return sides[1]^2 + sides[2]^2 == sides[3]^2\nend\n"], ["\"\"\"Write a function that accepts a vector of strings.\nThe vector contains different words. Return the word with maximum number\nof unique characters. If multiple strings have maximum number of unique\ncharacters, return the one which comes first in lexicographical order.\n>>> find_max([\"name\", \"of\", \"string\"])\n\"string\"\n>>> find_max([\"name\", \"enam\", \"game\"])\n\"enam\"\n>>> find_max([\"aaaaaaa\", \"bb\", \"cc\"])\n\"aaaaaaa\"\"\"\"\nfunction find_max(words::Vector{String})::String\n max_unique = 0\n max_word = \"\"\n for word in words\n unique_chars = Set(word)\n num_unique = length(unique_chars)\n if num_unique > max_unique || (num_unique == max_unique && word < max_word)\n max_unique = num_unique\n max_word = word\n end\n end\n return max_word\nend\n"], ["\"\"\"You're a hungry rabbit, and you already have eaten a certain number of carrots,\nbut now you need to eat more carrots to complete the day's meals.\nyou should return a vector of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\nif there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\nExample:\n>>> eat(5, 6, 10)\n[11, 4]\n>>> eat(4, 8, 9)\n[12, 1]\n>>> eat(1, 10, 10)\n[11, 0]\n>>> eat(2, 11, 5)\n[7, 0]\nVariables:\n@number : integer\n the number of carrots that you have eaten.\n@need : integer\n the number of carrots that you need to eat.\n@remaining : integer\n the number of remaining carrots thet exist in stock\nConstrain:\n* 0 <= number <= 1000\n* 0 <= need <= 1000\n* 0 <= remaining <= 1000\nHave fun :)\"\"\"\nfunction eat(number::Int64, need::Int64, remaining::Int64)::Vector{Int64}\n eaten = number + min(need, remaining)\n left = max(0, need - remaining)\n return [eaten, left]\nend\n"], ["\"\"\" Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n>>> string_sequence(0)\n\"0\"\n>>> string_sequence(5)\n\"0 1 2 3 4 5\"\"\"\"\nfunction string_sequence(n::Int64)::String\n return join(string.(collect(0:n)), \" \")\nend\n"], ["\"\"\"Given two vectors operator, and operand. The first vector has basic algebra operations, and \nthe second vector is a vector of integers. Use the two given vectors to build the algebric \nexpression and return the evaluation of this expression.\nThe basic algebra operations:\nAddition ( + ) \nSubtraction ( - ) \nMultiplication ( * ) \nFloor division ( // ) \nExponentiation ( ** ) \nExample:\noperator['+', '*', '-']\nvector = [2, 3, 4, 5]\nresult = 2 + 3 * 4 - 5\n=> result = 9\nNote:\n The length of operator vector is equal to the length of operand vector minus one.\n Operand is a vector of of non-negative integers.\n Operator vector has at least one operator, and operand vector has at least two operands.\"\"\"\nfunction do_algebra(operator::Vector{String}, operand::Vector{Int64})::Int64\n result = operand[1]\n for i in 1:length(operator)\n op = operator[i]\n num = operand[i+1]\n if op == \"+\"\n result += num\n elseif op == \"-\"\n result -= num\n elseif op == \"*\"\n result *= num\n elseif op == \"//\"\n result = div(result, num)\n elseif op == \"**\"\n result = result ^ num\n end\n end\n return result\nend\n"], ["\"\"\"You are given a string s.\nif s[i] is a letter, reverse its case from lower to upper or vise versa, \notherwise keep it as it is.\nIf the string contains no letters, reverse the string.\nThe function should return the resulted string.\nExamples\n>>> solve(\"1234\")\n\"4321\"\n>>> solve(\"ab\")\n\"AB\"\n>>> solve(\"#a@C\")\n\"#A@c\"\"\"\"\nfunction solve(s::String)::String\n if any(isletter, s)\n return mapreduce(c -> isletter(c) ? c \u22bb 32 : c, string, s)\n else\n return reverse(s)\n end\nend\n"], ["\"\"\"Given a string 'text', return its md5 hash equivalent string.\nIf 'text' is an empty string, return nothing.\n>>> string_to_md5(\"Hello world\")\n\"3e25960a79dbc69b674cd4ec67a72c62\"\"\"\"\nfunction string_to_md5(text::String)::Union{String, Nothing}\n if text == \"\"\n return nothing\n else\n return bytes2hex(md5(text))\n end\nend\n"], ["\"\"\"Given two positive integers a and b, return the even digits between a\nand b, in ascending order.\nFor example:\n>>> generate_integers(2, 8)\n[2, 4, 6, 8]\n>>> generate_integers(8, 2)\n[2, 4, 6, 8]\n>>> generate_integers(10, 14)\n[]\"\"\"\nfunction generate_integers(a::Int64, b::Int64)::Vector{Int64}\n if a > b\n a, b = b, a\n end\n result = Int64[]\n for i in a:b\n if i % 2 == 0\n push!(result, i)\n end\n end\n return result\nend\n"], ["\"\"\" Given a string, find out how many distinct characters (regardless of case) does it consist of\n>>> count_distinct_characters(\"xyzXYZ\")\n3\n>>> count_distinct_characters(\"Jerry\")\n4\"\"\"\nfunction count_distinct_characters(string::String)::Int64\n return length(unique(lowercase(string)))\nend\n"], ["\"\"\" Input to this function is a string representing musical notes in a special ASCII format.\nYour task is to parse this string and return vector of integers corresponding to how many beats does each\nnot last.\nHere is a legend:\n'o' - whole note, lasts four beats\n'o|' - half note, lasts two beats\n'.|' - quater note, lasts one beat\n>>> parse_music(\"o o| .| o| o| .| .| .| .| o o\")\n[4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\"\"\"\nfunction parse_music(music_string::String)::Vector{Int64}\n notes = split(music_string, \" \")\n beats = Vector{Int64}()\n for note in notes\n if note == \"o\"\n push!(beats, 4)\n elseif note == \"o|\"\n push!(beats, 2)\n elseif note == \".|\"\n push!(beats, 1)\n end\n end\n return beats\nend"], ["\"\"\" Find how many times a given substring can be found in the original string. Count overlaping cases.\n>>> how_many_times(\"\", \"a\")\n0\n>>> how_many_times(\"aaa\", \"a\")\n3\n>>> how_many_times(\"aaaa\", \"aa\")\n3\"\"\"\nfunction how_many_times(string::String, substring::String)::Int64\n count = 0\n index = 1\n while index <= length(string) - length(substring) + 1\n if string[index:index+length(substring)-1] == substring\n count += 1\n end\n index += 1\n end\n return count\nend\n"], ["\"\"\" Input is a space-delimited string of numberals from 'zero' to 'nine'.\nValid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\nReturn the string with numbers sorted from smallest to largest\n>>> sort_numbers(\"three one five\")\n\"one three five\"\"\"\"\nfunction sort_numbers(numbers::String)::String\n num_dict = Dict(\"zero\"=>0, \"one\"=>1, \"two\"=>2, \"three\"=>3, \"four\"=>4, \"five\"=>5, \"six\"=>6, \"seven\"=>7, \"eight\"=>8, \"nine\"=>9)\n num_list = [num_dict[num] for num in split(numbers)]\n sorted_num_list = sort(num_list)\n sorted_numbers = join([k for (k,v) in num_dict if v in sorted_num_list], \" \")\n return sorted_numbers\nend\n"], ["\"\"\" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\nseparate those group into separate strings and return the vector of those.\nSeparate groups are balanced (each open brace is properly closed) and not nested within each other\nIgnore any spaces in the input string.\n>>> separate_paren_groups(\"( ) (( )) (( )( ))\")\n[\"()\", \"(())\", \"(()())\"]\"\"\"\nfunction separate_paren_groups(paren_string::String)::Vector{String}\n groups = String[]\n current_group = \"\"\n open_count = 0\n for char in paren_string\n if char == '('\n open_count += 1\n elseif char == ')'\n open_count -= 1\n end\n if open_count == 0 && !isempty(current_group)\n push!(groups, current_group)\n current_group = \"\"\n elseif char != ' '\n current_group *= char\n end\n end\n return groups\nend\n"], ["\"\"\" From a supplied vector of numbers (of length at least two) select and return two that are the closest to each\nother and return them in order (smaller number, larger number).\n>>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n(2.0, 2.2)\n>>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n(2.0, 2.0)\"\"\"\nfunction find_closest_elements(numbers::Vector{Float64})::Tuple{Float64, Float64}\n sorted_numbers = sort(numbers)\n closest_pair = (sorted_numbers[1], sorted_numbers[2])\n min_diff = abs(sorted_numbers[2] - sorted_numbers[1])\n for i in 2:length(sorted_numbers)-1\n diff = abs(sorted_numbers[i+1] - sorted_numbers[i])\n if diff < min_diff\n min_diff = diff\n closest_pair = (sorted_numbers[i], sorted_numbers[i+1])\n end\n end\n return closest_pair\nend\n"], ["\"\"\" Given vector of numbers (of at least two elements), apply a linear transform to that vector,\nsuch that the smallest number will become 0 and the largest will become 1\n>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n[0.0, 0.25, 0.5, 0.75, 1.0]\"\"\"\nfunction rescale_to_unit(numbers::Vector{Float64})::Vector{Float64}\n min_num = minimum(numbers)\n max_num = maximum(numbers)\n range_num = max_num - min_num\n return [(num - min_num) / range_num for num in numbers]\nend\n"], ["\"\"\" Filter given vector of any jlthon values only for integers\n>>> filter_integers([\"a\", 3.14, 5])\n[5]\n>>> filter_integers([1, 2, 3, \"abc\", Dict(), []])\n[1, 2, 3]\"\"\"\nfunction filter_integers(values::Vector{Any})::Vector{Int64}\n return filter(x -> typeof(x) == Int64, values)\nend\n"], ["\"\"\" Return length of given string\n>>> strlen(\"\")\n0\n>>> strlen(\"abc\")\n3\"\"\"\nfunction strlen(string::String)::Int64\n return length(string)\nend\n"], ["\"\"\" For a given number n, find the largest number that divides n evenly, smaller than n\n>>> largest_divisor(15)\n5\"\"\"\nfunction largest_divisor(n::Int64)::Int64\n for i in reverse(1:sqrt(n))\n if n % i == 0\n return i\n end\n end\n return 1\nend"], ["\"\"\" Return vector of prime factors of given integer in the order from smallest to largest.\nEach of the factors should be vectored number of times corresponding to how many times it appeares in factorization.\nInput number should be equal to the product of all factors\n>>> factorize(8)\n[2, 2, 2]\n>>> factorize(25)\n[5, 5]\n>>> factorize(70)\n[2, 5, 7]\"\"\"\nfunction factorize(n::Int64)::Vector{Int64}\n factors = []\n i = 2\n while i <= n\n if n % i == 0\n push!(factors, i)\n n = n \ufffd i\n else\n i += 1\n end\n end\n return factors\nend\n"], ["\"\"\" From a vector of integers, remove all elements that occur more than once.\nKeep order of elements left the same as in the input.\n>>> remove_duplicates([1, 2, 3, 2, 4])\n[1, 3, 4]\"\"\"\nfunction remove_duplicates(numbers::Vector{Int64})::Vector{Int64}\n unique_numbers = []\n for number in numbers\n if !(number in unique_numbers)\n push!(unique_numbers, number)\n end\n end\n return unique_numbers\nend\n"], ["\"\"\" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n>>> flip_case(\"Hello\")\n\"hELLO\"\"\"\"\nfunction flip_case(string::String)::String\n flipped_string = \"\"\n for char in string\n if islowercase(char)\n flipped_string *= uppercase(char)\n elseif isuppercase(char)\n flipped_string *= lowercase(char)\n else\n flipped_string *= char\n end\n end\n return flipped_string\nend"], ["\"\"\" Concatenate vector of strings into a single string\n>>> concatenate([])\n\"\"\n>>> concatenate([\"a\", \"b\", \"c\"])\n\"abc\"\"\"\"\nfunction concatenate(strings::Vector{String})::String\n return join(strings)\nend\n"], ["\"\"\" Filter an input vector of strings only for ones that start with a given prefix.\n>>> filter_by_prefix([], \"a\")\n[]\n>>> filter_by_prefix([\"abc\", \"bcd\", \"cde\", \"array\"], \"a\")\n[\"abc\", \"array\"]\"\"\"\nfunction filter_by_prefix(strings::Vector{String}, prefix::String)::Vector{String}\n return filter(s -> startswith(s, prefix), strings)\nend\n"], ["\"\"\" Given a positive floating point number, it can be decomposed into\nand integer part (largest integer smaller than given number) and decimals\n(leftover part always smaller than 1).\nReturn the decimal part of the number.\n>>> truncate_number(3.5)\n0.5\"\"\"\nfunction truncate_number(number::Float64)::Float64\n return number - floor(number)\nend\n"], ["\"\"\"Return only positive numbers in the vector.\n>>> get_positive([-1, 2, -4, 5, 6])\n[2, 5, 6]\n>>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n[5, 3, 2, 3, 9, 123, 1]\"\"\"\nfunction get_positive(l::Vector{Int64})::Vector{Int64}\n return filter(x -> x > 0, l)\nend\n"], ["\"\"\"Return true if a given number is prime, and false otherwise.\n>>> is_prime(6)\nfalse\n>>> is_prime(101)\ntrue\n>>> is_prime(11)\ntrue\n>>> is_prime(13441)\ntrue\n>>> is_prime(61)\ntrue\n>>> is_prime(4)\nfalse\n>>> is_prime(1)\nfalse\"\"\"\nfunction is_prime(n::Int64)::Bool\n if n < 2\n return false\n end\n for i in 2:sqrt(n)\n if n % i == 0\n return false\n end\n end\n return true\nend\n"], ["\"\"\"This function takes a vector l and returns a vector l' such that\nl' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\nto the values of the corresponding indicies of l, but sorted.\n>>> sort_third([1, 2, 3])\n[1, 2, 3]\n>>> sort_third([5, 6, 3, 4, 8, 9, 2])\n[2, 6, 3, 4, 8, 9, 5]\"\"\"\nfunction sort_third(l::Vector{Int64})::Vector{Int64}\n l_prime = copy(l)\n divisible_by_three = findall(x -> x % 3 == 0, l)\n sorted_divisible = sort(l[divisible_by_three])\n l_prime[divisible_by_three] = sorted_divisible\n return l_prime\nend\n"], ["\"\"\"Return sorted unique elements in a vector\n>>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n[0, 2, 3, 5, 9, 123]\"\"\"\nfunction unique(l::Vector{Int64})::Vector{Int64}\n return sort(unique(l))\nend\n"], ["\"\"\"Return maximum element in the vector.\n>>> max_element([1, 2, 3])\n3\n>>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n123\"\"\"\nfunction max_element(l::Vector{Int64})::Int64\n return maximum(l)\nend\n"], ["\"\"\"Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n>>> fizz_buzz(50)\n0\n>>> fizz_buzz(78)\n2\n>>> fizz_buzz(79)\n3\"\"\"\nfunction fizz_buzz(n::Int64)::Int64\n count = 0\n for i in 1:n-1\n if (i % 11 == 0 || i % 13 == 0) && occursin(\"7\", string(i))\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"This function takes a vector l and returns a vector l' such that\nl' is identical to l in the odd indicies, while its values at the even indicies are equal\nto the values of the even indicies of l, but sorted.\n>>> sort_even([1, 2, 3])\n[1, 2, 3]\n>>> sort_even([5, 6, 3, 4])\n[3, 6, 5, 4]\"\"\"\nfunction sort_even(l::Vector{Int64})::Vector{Int64}\n even_values = sort(l[2:2:end])\n l_prime = copy(l)\n l_prime[2:2:end] = even_values\n return l_prime\nend\n"], ["\"\"\"prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n>>> prime_fib(1)\n2\n>>> prime_fib(2)\n3\n>>> prime_fib(3)\n5\n>>> prime_fib(4)\n13\n>>> prime_fib(5)\n89\"\"\"\nfunction prime_fib(n::Int64)::Int64\n fib_nums = [1, 1]\n i = 2\n while length(fib_nums) < n\n next_fib = fib_nums[i-1] + fib_nums[i]\n push!(fib_nums, next_fib)\n i += 1\n end\n prime_fib_nums = filter(isprime, fib_nums)\n return prime_fib_nums[n]\nend\n"], ["\"\"\" You're given a vector of deposit and withdrawal operations on a bank account that starts with\nzero balance. Your task is to detect if at any point the balance of account fallls below zero, and\nat that point function should return true. Otherwise it should return false.\n>>> below_zero([1, 2, 3])\nfalse\n>>> below_zero([1, 2, -4, 5])\ntrue\"\"\"\nfunction below_zero(operations::Vector{Int64})::Bool\n balance = 0\n for op in operations\n balance += op\n if balance < 0\n return true\n end\n end\n return false\nend\n"], ["\"\"\"triples_sum_to_zero takes a vector of integers as an input.\nit returns true if there are three distinct elements in the vector that\nsum to zero, and false otherwise.\n>>> triples_sum_to_zero([1, 3, 5, 0])\nfalse\n>>> triples_sum_to_zero([1, 3, -2, 1])\ntrue\n>>> triples_sum_to_zero([1, 2, 3, 7])\nfalse\n>>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\ntrue\n>>> triples_sum_to_zero([1])\nfalse\"\"\"\nfunction triples_sum_to_zero(l::Vector{Int64})::Bool\n n = length(l)\n for i in 1:n-2\n for j in i+1:n-1\n for k in j+1:n\n if l[i] + l[j] + l[k] == 0\n return true\n end\n end\n end\n end\n return false\nend\n"], ["\"\"\"Imagine a road that's a perfectly straight infinitely long line.\nn cars are driving left to right; simultaneously, a different set of n cars\nare driving right to left. The two sets of cars start out being very far from\neach other. All cars move in the same speed. Two cars are said to collide\nwhen a car that's moving left to right hits a car that's moving right to left.\nHowever, the cars are infinitely sturdy and strong; as a result, they continue moving\nin their trajectory as if they did not collide.\nThis function outputs the number of such collisions.\"\"\"\nfunction car_race_collision(n::Int64)::Int64\n return n\nend\n"], ["\"\"\"Return vector with elements incremented by 1.\n>>> incr_list([1, 2, 3])\n[2, 3, 4]\n>>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n[6, 4, 6, 3, 4, 4, 10, 1, 124]\"\"\"\nfunction incr_list(l::Vector{Int64})::Vector{Int64}\n return l .+ 1\nend\n"], ["\"\"\"pairs_sum_to_zero takes a vector of integers as an input.\nit returns true if there are two distinct elements in the vector that\nsum to zero, and false otherwise.\n>>> pairs_sum_to_zero([1, 3, 5, 0])\nfalse\n>>> pairs_sum_to_zero([1, 3, -2, 1])\nfalse\n>>> pairs_sum_to_zero([1, 2, 3, 7])\nfalse\n>>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\ntrue\n>>> pairs_sum_to_zero([1])\nfalse\"\"\"\nfunction pairs_sum_to_zero(l::Vector{Int64})::Bool\n for i in 1:length(l)\n for j in i+1:length(l)\n if l[i] + l[j] == 0\n return true\n end\n end\n end\n return false\nend\n"], ["\"\"\"Change numerical base of input number x to base.\nreturn string representation after the conversion.\nbase numbers are less than 10.\n>>> change_base(8, 3)\n\"22\"\n>>> change_base(8, 2)\n\"1000\"\n>>> change_base(7, 2)\n\"111\"\"\"\"\nfunction change_base(x::Int64, base::Int64)::String\n return string(base, x, base=base)\nend\n"], ["\"\"\"Given length of a side and high return area for a triangle.\n>>> triangle_area(5, 3)\n7.5\"\"\"\nfunction triangle_area(a::Int64, h::Int64)::Float64\n return 0.5 * a * h\nend\n"], ["\"\"\"The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\nfib4(0) -> 0\nfib4(1) -> 0\nfib4(2) -> 2\nfib4(3) -> 0\nfib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\nPlease write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n>>> fib4(5)\n4\n>>> fib4(6)\n8\n>>> fib4(7)\n14\"\"\"\nfunction fib4(n::Int64)::Int64\n if n < 4\n return n == 3 ? 0 : 2\n end\n a, b, c, d = 0, 0, 2, 0\n for i in 4:n\n d = a + b + c + d\n a, b, c = b, c, d\n end\n return d\nend\n"], ["\"\"\"Return median of elements in the vector l.\n>>> median([3, 1, 2, 4, 5])\n3\n>>> median([-10, 4, 6, 1000, 10, 20])\n15.0\"\"\"\nfunction median(l::Vector{Int64})::Float64\n sorted_l = sort(l)\n n = length(sorted_l)\n if n % 2 == 0\n return (sorted_l[n \ufffd 2] + sorted_l[n \ufffd 2 + 1]) / 2.0\n else\n return sorted_l[n \ufffd 2 + 1]\n end\nend\n"], ["\"\"\"Checks if given string is a palindrome\n>>> is_palindrome(\"\")\ntrue\n>>> is_palindrome(\"aba\")\ntrue\n>>> is_palindrome(\"aaaaa\")\ntrue\n>>> is_palindrome(\"zbcd\")\nfalse\"\"\"\nfunction is_palindrome(text::String)::Bool\n return text == reverse(text)\nend\n"], ["\"\"\"Return 2^n modulo p (be aware of numerics).\n>>> modp(3, 5)\n3\n>>> modp(1101, 101)\n2\n>>> modp(0, 101)\n1\n>>> modp(3, 11)\n8\n>>> modp(100, 101)\n1\"\"\"\nfunction modp(n::Int64, p::Int64)::Int64\n return powermod(2, n, p)\nend\n"], ["\"\"\" For a given vector of input numbers, calculate Mean Absolute Deviation\naround the mean of this dataset.\nMean Absolute Deviation is the average absolute difference between each\nelement and a centerpoint (mean in this case):\nMAD = average | x - x_mean |\n>>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n1.0\"\"\"\nfunction mean_absolute_deviation(numbers::Vector{Float64})::Float64\n x_mean = mean(numbers)\n absolute_differences = abs.(numbers .- x_mean)\n MAD = mean(absolute_differences)\n return MAD\nend\n"], ["\"\"\"remove_vowels is a function that takes string and returns string without vowels.\n>>> remove_vowels(\"\")\n\"\"\n>>> remove_vowels(\"abcdef\")\n\"bcdf\"\n>>> remove_vowels(\"aaaaa\")\n\"\"\n>>> remove_vowels(\"aaBAA\")\n\"B\"\n>>> remove_vowels(\"zbcd\")\n\"zbcd\"\"\"\"\nfunction remove_vowels(text::String)::String\n return replace(lowercase(text), r\"[aeiou]\" => \"\")\nend\n"], ["\"\"\"Return true if all numbers in the vector l are below threshold t.\n>>> below_threshold([1, 2, 4, 10], 100)\ntrue\n>>> below_threshold([1, 20, 4, 10], 5)\nfalse\"\"\"\nfunction below_threshold(l::Vector{Int64}, t::Int64)::Bool\n for num in l\n if num >= t\n return false\n end\n end\n return true\nend\n"], ["\"\"\"Add two numbers x and y\n>>> add(2, 3)\n5\n>>> add(5, 7)\n12\"\"\"\nfunction add(x::Int64, y::Int64)::Int64\n return x + y\nend\n"], ["\"\"\"Check if two words have the same characters.\n>>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddeddabc\")\ntrue\n>>> same_chars(\"abcd\", \"dddddddabc\")\ntrue\n>>> same_chars(\"dddddddabc\", \"abcd\")\ntrue\n>>> same_chars(\"eabcd\", \"dddddddabc\")\nfalse\n>>> same_chars(\"abcd\", \"dddddddabce\")\nfalse\n>>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddddabc\")\nfalse\"\"\"\nfunction same_chars(s0::String, s1::String)::Bool\n return sort(collect(s0)) == sort(collect(s1))\nend\n"], ["\"\"\"Return n-th Fibonacci number.\n>>> fib(10)\n55\n>>> fib(1)\n1\n>>> fib(8)\n21\"\"\"\nfunction fib(n::Int64)::Int64\n if n == 1 || n == 2\n return 1\n else\n return fib(n-1) + fib(n-2)\n end\nend\n"], ["\"\"\" brackets is a string of \"<\" and \">\".\nreturn true if every opening bracket has a corresponding closing bracket.\n>>> correct_bracketing(\"<\")\nfalse\n>>> correct_bracketing(\"<>\")\ntrue\n>>> correct_bracketing(\"<<><>>\")\ntrue\n>>> correct_bracketing(\"><<>\")\nfalse\"\"\"\nfunction correct_bracketing(brackets::String)::Bool\n stack = []\n for bracket in brackets\n if bracket == '<'\n push!(stack, bracket)\n elseif bracket == '>'\n if isempty(stack)\n return false\n else\n pop!(stack)\n end\n end\n end\n return isempty(stack)\nend\n"], ["\"\"\"Return true is vector elements are monotonically increasing or decreasing.\n>>> monotonic([1, 2, 4, 20])\ntrue\n>>> monotonic([1, 20, 4, 10])\nfalse\n>>> monotonic([4, 1, 0, -10])\ntrue\"\"\"\nfunction monotonic(l::Vector{Int64})::Bool\n increasing = true\n decreasing = true\n for i in 1:length(l)-1\n if l[i] > l[i+1]\n increasing = false\n end\n if l[i] < l[i+1]\n decreasing = false\n end\n end\n return increasing || decreasing\nend\n"], ["\"\"\"Return sorted unique common elements for two vectors.\n>>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n[1, 5, 653]\n>>> common([5, 3, 2, 8], [3, 2])\n[2, 3]\"\"\"\nfunction common(l1::Vector{Int64}, l2::Vector{Int64})::Vector{Int64}\n return sort(unique(intersect(l1, l2)))\nend\n"], ["\"\"\"Return the largest prime factor of n. Assume n > 1 and is not a prime.\n>>> largest_prime_factor(13195)\n29\n>>> largest_prime_factor(2048)\n2\"\"\"\nfunction largest_prime_factor(n::Int64)::Int64\n i = 2\n while i * i <= n\n while n % i == 0\n n \ufffd= i\n end\n i += 1\n end\n return n\nend\n"], ["\"\"\" Insert a number 'delimeter' between every two consecutive elements of input vector `numbers'\n>>> intersperse([], 4)\n[]\n>>> intersperse([1, 2, 3], 4)\n[1, 4, 2, 4, 3]\"\"\"\nfunction intersperse(numbers::Vector{Int64}, delimeter::Int64)::Vector{Int64}\n result = Int64[]\n for i in 1:length(numbers)\n push!(result, numbers[i])\n if i != length(numbers)\n push!(result, delimeter)\n end\n end\n return result\nend\n"], ["\"\"\"sum_to_n is a function that sums numbers from 1 to n.\n>>> sum_to_n(30)\n465\n>>> sum_to_n(100)\n5050\n>>> sum_to_n(5)\n15\n>>> sum_to_n(10)\n55\n>>> sum_to_n(1)\n1\"\"\"\nfunction sum_to_n(n::Int64)::Int64\n return n*(n+1)\ufffd2\nend\n"], ["\"\"\" brackets is a string of \"(\" and \")\".\nreturn true if every opening bracket has a corresponding closing bracket.\n>>> correct_bracketing(\"(\")\nfalse\n>>> correct_bracketing(\"()\")\ntrue\n>>> correct_bracketing(\"(()())\")\ntrue\n>>> correct_bracketing(\")(()\")\nfalse\"\"\"\nfunction correct_bracketing(brackets::String)::Bool\n stack = []\n for bracket in brackets\n if bracket == '('\n push!(stack, bracket)\n elseif bracket == ')'\n if isempty(stack)\n return false\n else\n pop!(stack)\n end\n end\n end\n return isempty(stack)\nend\n"], ["\"\"\" xs represent coefficients of a polynomial.\nxs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n>>> derivative([3, 1, 2, 4, 5])\n[1, 4, 12, 20]\n>>> derivative([1, 2, 3])\n[2, 6]\"\"\"\nfunction derivative(xs::Vector{Int64})::Vector{Int64}\n n = length(xs)\n if n == 1\n return [0]\n end\n return [i*xs[i+1] for i in 1:n-1]\nend\n"], ["\"\"\"The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\nfibfib(0) == 0\nfibfib(1) == 0\nfibfib(2) == 1\nfibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\nPlease write a function to efficiently compute the n-th element of the fibfib number sequence.\n>>> fibfib(1)\n0\n>>> fibfib(5)\n4\n>>> fibfib(8)\n24\"\"\"\nfunction fibfib(n::Int64)::Int64\n if n == 0\n return 0\n elseif n == 1\n return 0\n elseif n == 2\n return 1\n else\n fibfib_sequence = zeros(Int64, n)\n fibfib_sequence[1] = 0\n fibfib_sequence[2] = 0\n fibfib_sequence[3] = 1\n for i in 4:n\n fibfib_sequence[i] = fibfib_sequence[i-1] + fibfib_sequence[i-2] + fibfib_sequence[i-3]\n end\n return fibfib_sequence[n]\n end\nend\n"], ["\"\"\"Write a function vowels_count which takes a string representing\na word as input and returns the number of vowels in the string.\nVowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\nvowel, but only when it is at the end of the given word.\nExample:\n>>> vowels_count(\"abcde\")\n2\n>>> vowels_count(\"ACEDY\")\n3\"\"\"\nfunction vowels_count(s::String)::Int64\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n count = 0\n for c in s\n if c in vowels\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"Circular shift the digits of the integer x, shift the digits right by shift\nand return the result as a string.\nIf shift > number of digits, return digits reversed.\n>>> circular_shift(12, 1)\n\"21\"\n>>> circular_shift(12, 2)\n\"12\"\"\"\"\nfunction circular_shift(x::Int64, shift::Int64)::String\n digits = string(x)\n n = length(digits)\n if shift > n\n return digits[end:-1:1]\n end\n shifted_digits = digits[n-shift+1:end] * digits[1:n-shift]\n return shifted_digits\nend\n"], ["\"\"\"Task\nWrite a function that takes a string as input and returns the sum of the upper characters only'\nASCII codes.\nExamples:\n>>> digitSum(\"\")\n0\n>>> digitSum(\"abAB\")\n131\n>>> digitSum(\"abcCd\")\n67\n>>> digitSum(\"helloE\")\n69\n>>> digitSum(\"woArBld\")\n131\n>>> digitSum(\"aAaaaXa\")\n153\"\"\"\nfunction digitSum(s::String)::Int64\n sum = 0\n for c in s\n if isuppercase(c)\n sum += Int(c)\n end\n end\n return sum\nend\n"], ["\"\"\"In this task, you will be given a string that represents a number of apples and oranges \nthat are distributed in a basket of fruit this basket contains \napples, oranges, and mango fruits. Given the string that represents the total number of \nthe oranges and apples and an integer that represent the total number of the fruits \nin the basket return the number of the mango fruits in the basket.\nfor examble:\n>>> fruit_distribution(\"5 apples and 6 oranges\", 19)\n8\n>>> fruit_distribution(\"0 apples and 1 oranges\", 3)\n2\n>>> fruit_distribution(\"2 apples and 3 oranges\", 100)\n95\n>>> fruit_distribution(\"100 apples and 1 oranges\", 120)\n19\"\"\"\nfunction fruit_distribution(s::String, n::Int64)::Int64\n # Split the string into two parts\n parts = split(s, \" and \")\n # Extract the number of apples and oranges\n apples = parse(Int64, split(parts[1])[1])\n oranges = parse(Int64, split(parts[2])[1])\n # Calculate the number of mango fruits\n mango = n - apples - oranges\n return mango\nend\n"], ["\"\"\"\"Given a vector representing a branch of a tree that has non-negative integer nodes\nyour task is to pluck one of the nodes and return it.\nThe plucked node should be the node with the smallest even value.\nIf multiple nodes with the same smallest even value are found return the node that has smallest index.\nThe plucked node should be returned in a vector, [ smalest_value, its index ],\nIf there are no even values or the given vector is empty, return [].\nExample 1:\n>>> pluck([4, 2, 3])\n[2, 1]\nExplanation: 2 has the smallest even value, and 2 has the smallest index.\nExample 2:\n>>> pluck([1, 2, 3])\n[2, 1]\nExplanation: 2 has the smallest even value, and 2 has the smallest index.\nExample 3:\n>>> pluck([])\n[]\nExample 4:\n>>> pluck([5, 0, 3, 0, 4, 2])\n[0, 1]\nExplanation: 0 is the smallest value, but there are two zeros,\n so we will choose the first zero, which has the smallest index.\nConstraints:\n * 1 <= nodes.length <= 10000\n * 0 <= node.value\"\"\"\nfunction pluck(arr::Vector{Int64})::Vector{Int64}\n even_arr = filter(x -> x % 2 == 0, arr)\n if length(even_arr) == 0\n return []\n end\n min_even = minimum(even_arr)\n min_index = findfirst(x -> x == min_even, arr)\n return [min_even, min_index]\nend\n"], ["\"\"\"You are given a non-empty vector of positive integers. Return the greatest integer that is greater than \nzero, and has a frequency greater than or equal to the value of the integer itself. \nThe frequency of an integer is the number of times it appears in the vector.\nIf no such a value exist, return -1.\nExamples:\n>>> search([4, 1, 2, 2, 3, 1])\n2\n>>> search([1, 2, 2, 3, 3, 3, 4, 4, 4])\n3\n>>> search([5, 5, 4, 4, 4])\n-1\"\"\"\nfunction search(lst::Vector{Int64})::Int64\n counts = Dict{Int64, Int64}()\n for num in lst\n counts[num] = get(counts, num, 0) + 1\n end\n for num in sort(unique(lst), rev=true)\n if num <= counts[num]\n return num\n end\n end\n return -1\nend\n"], ["\"\"\" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\nFor each of the group, output the deepest level of nesting of parentheses.\nE.g. (()()) has maximum two levels of nesting while ((())) has three.\n>>> parse_nested_parens(\"(()()) ((())) () ((())()())\")\n[2, 3, 1, 3]\"\"\"\nfunction parse_nested_parens(paren_string::String)::Vector{Int64}\n levels = []\n current_level = 0\n for char in paren_string\n if char == '('\n current_level += 1\n elseif char == ')'\n current_level -= 1\n end\n if current_level > length(levels)\n push!(levels, current_level)\n else\n levels[current_level] = current_level\n end\n end\n return levels\nend\n"], ["\"\"\"Given vector of integers, return vector in strange order.\nStrange sorting, is when you start with the minimum value,\nthen maximum of the remaining integers, then minimum and so on.\nExamples:\n>>> strange_sort_list([1, 2, 3, 4])\n[1, 4, 2, 3]\n>>> strange_sort_list([5, 5, 5, 5])\n[5, 5, 5, 5]\n>>> strange_sort_list([])\n[]\"\"\"\nfunction strange_sort_list(lst::Vector{Int64})::Vector{Int64}\n sorted_lst = sort(lst)\n result = []\n while length(sorted_lst) > 0\n pushfirst!(result, popfirst(sorted_lst))\n if length(sorted_lst) > 0\n pushfirst!(result, poplast(sorted_lst))\n end\n end\n return result\nend\n"], ["\"\"\"Given the lengths of the three sides of a triangle. Return the area of\nthe triangle rounded to 2 decimal points if the three sides form a valid triangle. \nOtherwise return -1\nThree sides make a valid triangle when the sum of any two sides is greater \nthan the third side.\nExample:\n>>> triangle_area(3, 4, 5)\n6.0\n>>> triangle_area(1, 2, 10)\n-1\"\"\"\nfunction triangle_area(a::Int64, b::Int64, c::Int64)::Float64\n if a + b > c && a + c > b && b + c > a\n s = (a + b + c) / 2\n area = sqrt(s * (s - a) * (s - b) * (s - c))\n return round(area, digits=2)\n else\n return -1\n end\nend\n"], ["\"\"\"Write a function that returns true if the object q will fly, and false otherwise.\nThe object q will fly if it's balanced (it is a palindromic vector) and the sum of its elements is less than or equal the maximum possible weight w.\nExample:\n>>> will_it_fly([1, 2], 5)\nfalse\n# 1+2 is less than the maximum possible weight, but it's unbalanced.\n>>> will_it_fly([3, 2, 3], 1)\nfalse\n# it's balanced, but 3+2+3 is more than the maximum possible weight.\n>>> will_it_fly([3, 2, 3], 9)\ntrue\n# 3+2+3 is less than the maximum possible weight, and it's balanced.\n>>> will_it_fly([3], 5)\ntrue\n# 3 is less than the maximum possible weight, and it's balanced.\"\"\"\nfunction will_it_fly(q::Vector{Int64}, w::Int64)::Bool\n if ispalindrome(q) && sum(q) <= w\n return true\n else\n return false\n end\nend"], ["\"\"\"Given a vector arr of integers, find the minimum number of elements that\nneed to be changed to make the vector palindromic. A palindromic vector is a vector that\nis read the same backwards and forwards. In one change, you can change one element to any other element.\nFor example:\n>>> smallest_change([1, 2, 3, 5, 4, 7, 9, 6])\n4\n>>> smallest_change([1, 2, 3, 4, 3, 2, 2])\n1\n>>> smallest_change([1, 2, 3, 2, 1])\n0\"\"\"\nfunction smallest_change(arr::Vector{Int64})::Int64\n n = length(arr)\n count = 0\n for i in 1:div(n, 2)\n if arr[i] != arr[n-i+1]\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"Write a function that accepts two vectors of strings and returns the vector that has \ntotal number of chars in the all strings of the vector less than the other vector.\nif the two vectors have the same number of chars, return the first vector.\nExamples\n>>> total_match([], [])\n[]\n>>> total_match([\"hi\", \"admin\"], [\"hI\", \"Hi\"])\n[\"hI\", \"Hi\"]\n>>> total_match([\"hi\", \"admin\"], [\"hi\", \"hi\", \"admin\", \"project\"])\n[\"hi\", \"admin\"]\n>>> total_match([\"hi\", \"admin\"], [\"hI\", \"hi\", \"hi\"])\n[\"hI\", \"hi\", \"hi\"]\n>>> total_match([\"4\"], [\"1\", \"2\", \"3\", \"4\", \"5\"])\n[\"4\"]\"\"\"\nfunction total_match(lst1::Vector{String}, lst2::Vector{String})::Vector{String}\n total1 = sum(length(s) for s in lst1)\n total2 = sum(length(s) for s in lst2)\n if total1 < total2\n return lst1\n elseif total1 > total2\n return lst2\n else\n return lst1\n end\nend\n"], ["\"\"\"Write a function that returns true if the given number is the multiplication of 3 prime numbers\nand false otherwise.\nKnowing that (a) is less then 100. \nExample:\n>>> is_multiply_prime(30)\ntrue\n30 = 2 * 3 * 5\"\"\"\nfunction is_multiply_prime(a::Int64)::Bool\n if a < 6\n return false\n end\n 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]\n for i in 1:length(primes)\n for j in i:length(primes)\n for k in j:length(primes)\n if primes[i] * primes[j] * primes[k] == a\n return true\n end\n end\n end\n end\n return false\nend\n"], ["\"\"\"Your task is to write a function that returns true if a number x is a simple\npower of n and false in other cases.\nx is a simple power of n if n**int=x\nFor example:\n>>> is_simple_power(1, 4)\ntrue\n>>> is_simple_power(2, 2)\ntrue\n>>> is_simple_power(8, 2)\ntrue\n>>> is_simple_power(3, 2)\nfalse\n>>> is_simple_power(3, 1)\nfalse\n>>> is_simple_power(5, 3)\nfalse\"\"\"\nfunction is_simple_power(x::Int64, n::Int64)::Bool\n if x == 1 && n == 1\n return true\n end\n if n == 1\n return false\n end\n for i in 2:x\n if n^i == x\n return true\n elseif n^i > x\n return false\n end\n end\n return false\nend\n"], ["\"\"\"Write a function that takes an integer a and returns true \nif this ingeger is a cube of some integer number.\nNote: you may assume the input is always valid.\nExamples:\n>>> iscube(1)\ntrue\n>>> iscube(2)\nfalse\n>>> iscube(-1)\ntrue\n>>> iscube(64)\ntrue\n>>> iscube(0)\ntrue\n>>> iscube(180)\nfalse\"\"\"\nfunction iscube(a::Int64)::Bool\n cube_root = round(Int64, cbrt(abs(a)))\n return cube_root^3 == a\nend\n"], ["\"\"\"You have been tasked to write a function that receives \na hexadecimal number as a string and counts the number of hexadecimal \ndigits that are primes (prime number, or a prime, is a natural number \ngreater than 1 that is not a product of two smaller natural numbers).\nHexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\nPrime numbers are 2, 3, 5, 7, 11, 13, 17,...\nSo you have to determine a number of the following digits: 2, 3, 5, 7, \nB (=decimal 11), D (=decimal 13).\nNote: you may assume the input is always correct or empty string, \nand symbols A,B,C,D,E,F are always uppercase.\nExamples:\n>>> hex_key(\"AB\")\n1\n>>> hex_key(\"1077E\")\n2\n>>> hex_key(\"ABED1A33\")\n4\n>>> hex_key(\"123456789ABCDEF0\")\n6\n>>> hex_key(\"2020\")\n2\"\"\"\nfunction hex_key(num::String)::Int64\n primes = Set([2, 3, 5, 7, 11, 13])\n count = 0\n for c in num\n if c in \"0123456789ABCDEF\"\n n = parse(Int64, string(c), base=16)\n if n in primes\n count += 1\n end\n end\n end\n return count\nend\n"], ["\"\"\"You will be given a number in decimal form and your task is to convert it to\nbinary format. The function should return a string, with each character representing a binary\nnumber. Each character in the string will be '0' or '1'.\nThere will be an extra couple of characters 'db' at the beginning and at the end of the string.\nThe extra characters are there to help with the format.\nExamples:\n>>> decimal_to_binary(15)\n\"db1111db\"\n>>> decimal_to_binary(32)\n\"db100000db\"\"\"\"\nfunction decimal_to_binary(decimal::Int64)::String\n binary = string(decimal, base=2)\n return \"db\" * binary * \"db\"\nend\n"], ["\"\"\" Filter an input vector of strings only for ones that contain given substring\n>>> filter_by_substring([], \"a\")\n[]\n>>> filter_by_substring([\"abc\", \"bacd\", \"cde\", \"array\"], \"a\")\n[\"abc\", \"bacd\", \"array\"]\"\"\"\nfunction filter_by_substring(strings::Vector{String}, substring::String)::Vector{String}\n return filter(s -> contains(s, substring), strings)\nend\n"], ["\"\"\"You are given a string s.\nYour task is to check if the string is hapjl or not.\nA string is hapjl if its length is at least 3 and every 3 consecutive letters are distinct\nFor example:\n>>> is_happy(\"a\")\nfalse\n>>> is_happy(\"aa\")\nfalse\n>>> is_happy(\"abcd\")\ntrue\n>>> is_happy(\"aabb\")\nfalse\n>>> is_happy(\"adb\")\ntrue\n>>> is_happy(\"xyy\")\nfalse\"\"\"\nfunction is_happy(s::String)::Bool\n n = length(s)\n if n < 3\n return false\n end\n for i in 1:n-2\n if s[i] == s[i+1] || s[i] == s[i+2] || s[i+1] == s[i+2]\n return false\n end\n end\n return true\nend\n"], ["\"\"\"It is the last week of the semester and the teacher has to give the grades\nto students. The teacher has been making her own algorithm for grading.\nThe only problem is, she has lost the code she used for grading.\nShe has given you a vector of GPAs for some students and you have to write \na function that can output a vector of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\nExample:\n>>> grade_equation([4.0, 3, 1.7, 2, 3.5])\n[\"A+\", \"B\", \"C-\", \"C\", \"A-\"]\"\"\"\nfunction numerical_letter_grade(grades::Vector{Float64})::Vector{String}\n letter_grades = String[]\n for grade in grades\n if grade == 4.0\n push!(letter_grades, \"A+\")\n elseif grade > 3.7\n push!(letter_grades, \"A\")\n elseif grade > 3.3\n push!(letter_grades, \"A-\")\n elseif grade > 3.0\n push!(letter_grades, \"B+\")\n elseif grade > 2.7\n push!(letter_grades, \"B\")\n elseif grade > 2.3\n push!(letter_grades, \"B-\")\n elseif grade > 2.0\n push!(letter_grades, \"C+\")\n elseif grade > 1.7\n push!(letter_grades, \"C\")\n elseif grade > 1.3\n push!(letter_grades, \"C-\")\n elseif grade > 1.0\n push!(letter_grades, \"D+\")\n elseif grade > 0.7\n push!(letter_grades, \"D\")\n elseif grade > 0.0\n push!(letter_grades, \"D-\")\n else\n push!(letter_grades, \"E\")\n end\n end\n return letter_grades\nend\n"], ["\"\"\"Write a function that takes a string and returns true if the string\nlength is a prime number or false otherwise\nExamples\n>>> prime_length(\"Hello\")\ntrue\n>>> prime_length(\"abcdcba\")\ntrue\n>>> prime_length(\"kittens\")\ntrue\n>>> prime_length(\"orange\")\nfalse\"\"\"\nfunction prime_length(string::String)::Bool\n length_string = length(string)\n if length_string < 2\n return false\n end\n for i in 2:sqrt(length_string)\n if length_string % i == 0\n return false\n end\n end\n return true\nend\n"], ["\"\"\"Given a positive integer n, return the count of the numbers of n-digit\npositive integers that start or end with 1.\"\"\"\nfunction starts_one_ends(n::Int64)::Int64\n if n == 1\n return 1\n else\n return 2 * (9^(n-2))\n end\nend\n"], ["\"\"\"Given a positive integer N, return the total sum of its digits in binary.\nExample\n>>> solve(1000)\n\"1\"\n>>> solve(150)\n\"110\"\n>>> solve(147)\n\"1100\"\nVariables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\nOutput:\n a string of binary number\"\"\"\nfunction solve(N::Int64)::String\n binary = bin(N)\n return sum(parse(Int, x) for x in binary[3:end])\nend\n"], ["\"\"\"Given a non-empty vector of integers lst. add the even elements that are at odd indices..\nExamples:\n>>> add([4, 2, 6, 7])\n2\"\"\"\nfunction add(lst::Vector{Int64})::Int64\n sum = 0\n for i in 1:2:length(lst)\n if lst[i] % 2 == 0\n sum += lst[i]\n end\n end\n return sum\nend\n"], ["\"\"\"Write a function that takes a string and returns an ordered version of it.\nOrdered version of string, is a string where all words (separated by space)\nare replaced by a new word where all the characters arranged in\nascending order based on ascii value.\nNote: You should keep the order of words and blank spaces in the sentence.\nFor example:\n>>> anti_shuffle(\"Hi\")\n\"Hi\"\n>>> anti_shuffle(\"hello\")\n\"ehllo\"\n>>> anti_shuffle(\"Hello World!!!\")\n\"Hello !!!Wdlor\"\"\"\"\nfunction anti_shuffle(s::String)::String\n words = split(s)\n ordered_words = [join(sort(collect(word))) for word in words]\n return join(ordered_words, \" \")\nend\n"], ["\"\"\"You are given a 2 dimensional data, as a nested vectors,\nwhich is similar to matrix, however, unlike matrices,\neach row may contain a different number of columns.\nGiven lst, and integer x, find integers x in the vector,\nand return vector of tuples, [(x1, y1), (x2, y2) ...] such that\neach tuple is a coordinate - (row, columns), starting with 0.\nSort coordinates initially by rows in ascending order.\nAlso, sort coordinates of the row by columns in descending order.\nExamples:\n>>> get_row([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1)\n[(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n>>> get_row([], 1)\n[]\n>>> get_row([[], [1], [1, 2, 3]], 3)\n[(2, 2)]\"\"\"\nfunction get_row(lst::Vector{Vector{Int64}}, x::Int64)::Vector{Tuple{Int64, Int64}}\n coords = Tuple{Int64, Int64}[]\n for (i, row) in enumerate(lst)\n for (j, val) in enumerate(row)\n if val == x\n push!(coords, (i-1, j-1))\n end\n end\n end\n sort(coords, by=x->(x[1], -x[2]))\nend\n"], ["\"\"\"Given a vector of non-negative integers, return a cojl of the given vector after sorting,\nyou will sort the given vector in ascending order if the sum( first index value, last index value) is odd,\nor sort it in descending order if the sum( first index value, last index value) is even.\nNote:\n* don't change the given vector.\nExamples:\n>>> sort_array([])\n[]\n>>> sort_array([5])\n[5]\n>>> sort_array([2, 4, 3, 0, 1, 5])\n[0, 1, 2, 3, 4, 5]\n>>> sort_array([2, 4, 3, 0, 1, 5, 6])\n[6, 5, 4, 3, 2, 1, 0]\"\"\"\nfunction sort_array(array::Vector{Int64})::Vector{Int64}\n if sum(array[begin], array[end]) % 2 == 0\n return sort(array, rev=true)\n else\n return sort(array)\n end\nend\n"], ["\"\"\"Create a function encrypt that takes a string as an argument and\nreturns a string encrypted with the alphabet being rotated. \nThe alphabet should be rotated in a manner such that the letters \nshift down by two multiplied to two places.\nFor example:\n>>> encrypt(\"hi\")\n\"lm\"\n>>> encrypt(\"asdfghjkl\")\n\"ewhjklnop\"\n>>> encrypt(\"gf\")\n\"kj\"\n>>> encrypt(\"et\")\n\"ix\"\"\"\"\nfunction encrypt(s::String)::String\n encrypted = \"\"\n for c in s\n if isletter(c)\n if isuppercase(c)\n encrypted *= Char(mod(Int(c) - 65 + 2*2, 26) + 65)\n else\n encrypted *= Char(mod(Int(c) - 97 + 2*2, 26) + 97)\n end\n else\n encrypted *= c\n end\n end\n return encrypted\nend\n"], ["\"\"\" For a given vector of integers, return a tuple consisting of a sum and a product of all the integers in a vector.\nEmpty sum should be equal to 0 and empty product should be equal to 1.\n>>> sum_product([])\n(0, 1)\n>>> sum_product([1, 2, 3, 4])\n(10, 24)\"\"\"\nfunction sum_product(numbers::Vector{Int64})::Tuple{Int64, Int64}\n if isempty(numbers)\n return (0, 1)\n else\n return (sum(numbers), prod(numbers))\n end\nend\n"], ["\"\"\"You are given a vector of integers.\nWrite a function next_smallest() that returns the 2nd smallest element of the vector.\nReturn nothing if there is no such element.\n>>> next_smallest([1, 2, 3, 4, 5])\n2\n>>> next_smallest([5, 1, 4, 3, 2])\n2\n>>> next_smallest([])\nnothing\n>>> next_smallest([1, 1])\nnothing\"\"\"\nfunction next_smallest(lst::Vector{Int64})::Union{Int64, Nothing}\n if length(lst) < 2\n return nothing\n end\n sorted_lst = sort(lst)\n return sorted_lst[2]\nend\n"], ["\"\"\"You'll be given a string of words, and your task is to count the number\nof boredoms. A boredom is a sentence that starts with the word \"I\".\nSentences are delimited by '.', '?' or '!'.\nFor example:\n>>> is_bored(\"Hello world\")\n0\n>>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n1\"\"\"\nfunction is_bored(S::String)::Int64\n count = 0\n sentences = split(S, r\"[.!?]\")\n for sentence in sentences\n if startswith(sentence, \"I \") || startswith(sentence, \"I.\") || startswith(sentence, \"I!\") || startswith(sentence, \"I?\")\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"Create a function that takes 3 numbers.\nReturns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\nReturns false in any other cases.\nExamples\n>>> any_int(5, 2, 7)\ntrue\n>>> any_int(3, 2, 2)\nfalse\n>>> any_int(3, -2, 1)\ntrue\n>>> any_int(3.6, -2.2, 2)\nfalse\"\"\"\nfunction any_int(x::Float64, y::Float64, z::Float64)::Bool\n return false\nend\n"], ["\"\"\"Write a function that takes a message, and encodes in such a \nway that it swaps case of all letters, replaces all vowels in \nthe message with the letter that appears 2 places ahead of that \nvowel in the english alphabet. \nAssume only letters. \nExamples:\n>>> encode(\"test\")\n\"TGST\"\n>>> encode(\"This is a message\")\n\"tHKS KS C MGSSCGG\"\"\"\"\nfunction encode(message::String)::String\n vowels = \"aeiou\"\n encoded_message = \"\"\n for letter in message\n if isletter(letter)\n if letter in vowels\n vowel_index = findfirst(vowels, letter)\n encoded_letter = vowels[(vowel_index + 2) % length(vowels)]\n encoded_message *= encoded_letter\n else\n encoded_message *= isuppercase(letter) ? lowercase(letter) : uppercase(letter)\n end\n else\n encoded_message *= letter\n end\n end\n return encoded_message\nend\n"], ["\"\"\"You are given a vector of integers.\nYou need to find the largest prime value and return the sum of its digits.\nExamples:\n>>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3])\n10\n>>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1])\n25\n>>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3])\n13\n>>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6])\n11\n>>> skjkasdkd([0, 81, 12, 3, 1, 21])\n3\n>>> skjkasdkd([0, 8, 1, 2, 1, 7])\n7\"\"\"\nfunction skjkasdkd(lst::Vector{Int64})::Int64\n primes = []\n for num in lst\n if isprime(num)\n push!(primes, num)\n end\n end\n if length(primes) == 0\n return 0\n end\n largest_prime = maximum(primes)\n return sum(digits(largest_prime))\nend\n"], ["\"\"\"Given a dictionary, return true if all keys are strings in lower \ncase or all keys are strings in upper case, else return false.\nThe function should return false is the given dictionary is empty.\nExamples:\n>>> check_dict_case(Dict(\"a\" => \"apple\", \"b\" => \"banana\"))\ntrue\n>>> check_dict_case(Dict(\"a\" => \"apple\", \"A\" => \"banana\", \"B\" => \"banana\"))\nfalse\n>>> check_dict_case(Dict(\"a\" => \"apple\", 8 => \"banana\", \"a\" => \"apple\"))\nfalse\n>>> check_dict_case(Dict(\"Name\" => \"John\", \"Age\" => \"36\", \"City\" => \"Houston\"))\nfalse\n>>> check_dict_case(Dict(\"STATE\" => \"NC\", \"ZIP\" => \"12345\"))\ntrue\"\"\"\nfunction check_dict_case(dict::Dict{String, String}>)::Bool\n if isempty(dict)\n return false\n end\n all_lower = all(islowercase(k) for k in keys(dict))\n all_upper = all(isuppercase(k) for k in keys(dict))\n return all_lower || all_upper\nend\n"], ["\"\"\"Implement a function that takes an non-negative integer and returns a vector of the first n\nintegers that are prime numbers and less than n.\nfor example:\n>>> count_up_to(5)\n[2, 3]\n>>> count_up_to(11)\n[2, 3, 5, 7]\n>>> count_up_to(0)\n[]\n>>> count_up_to(20)\n[2, 3, 5, 7, 11, 13, 17, 19]\n>>> count_up_to(1)\n[]\n>>> count_up_to(18)\n[2, 3, 5, 7, 11, 13, 17]\"\"\"\nfunction count_up_to(n::Int64)::Vector{Int64}\n primes = []\n for i in 2:n\n is_prime = true\n for j in 2:i-1\n if i % j == 0\n is_prime = false\n break\n end\n end\n if is_prime\n push!(primes, i)\n end\n end\n return primes\nend\n"], ["\"\"\"Complete the function that takes two integers and returns \nthe product of their unit digits.\nAssume the input is always valid.\nExamples:\n>>> multiply(148, 412)\n16\n>>> multiply(19, 28)\n72\n>>> multiply(2020, 1851)\n0\n>>> multiply(14, -15)\n20\"\"\"\nfunction multiply(a::Int64, b::Int64)::Int64\n return a % 10 * b % 10\nend\n"], ["\"\"\"Given a string s, count the number of uppercase vowels in even indices.\nFor example:\n>>> count_upper(\"aBCdEf\")\n1\n>>> count_upper(\"abcdefg\")\n0\n>>> count_upper(\"dBBE\")\n0\"\"\"\nfunction count_upper(s::String)::Int64\n count::Int64 = 0\n for i in 1:2:length(s)\n if isupper(s[i]) && s[i] in \"AEIOU\"\n count += 1\n end\n end\n return count\nend\n"], ["\"\"\"Create a function that takes a value (string) representing a number\nand returns the closest integer to it. If the number is equidistant\nfrom two integers, round it away from zero.\nExamples\n>>> closest_integer(\"10\")\n10\n>>> closest_integer(\"15.3\")\n15\nNote:\nRounding away from zero means that if the given number is equidistant\nfrom two integers, the one you should return is the one that is the\nfarthest from zero. For example closest_integer(\"14.5\") should\nreturn 15 and closest_integer(\"-14.5\") should return -15.\"\"\"\nfunction closest_integer(value::String)::Int64\n num = parse(Float64, value)\n if num >= 0\n return round(Int64, num + 0.5)\n else\n return round(Int64, num - 0.5)\n end\nend\n"], ["\"\"\" From a given vector of integers, generate a vector of rolling maximum element found until given moment\nin the sequence.\n>>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n[1, 2, 3, 3, 3, 4, 4]\"\"\"\nfunction rolling_max(numbers::Vector{Int64})::Vector{Int64}\n max_values = []\n for i in 1:length(numbers)\n if isempty(max_values)\n pushfirst!(max_values, numbers[i])\n else\n pushfirst!(max_values, max(numbers[i], max_values[1]))\n end\n end\n return reverse(max_values)\nend\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-js_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-js_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..646b2656dc6196794c3431c2f033f97334cb1f3e --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-js_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["//Check if in given array of numbers, are any two numbers closer to each other than\n// given threshold.\n// >>> has_close_elements([1.0, 2.0, 3.0], 0.5)\n// false\n// >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n// true\nfunction has_close_elements(numbers, threshold){\n for(let i = 0; i < numbers.length; i++){\n for(let j = i+1; j < numbers.length; j++){\n if(Math.abs(numbers[i] - numbers[j]) <= threshold){\n return true;\n }\n }\n }\n return false;\n}\n"], ["//Given a positive integer n, you have to make a pile of n levels of stones.\n// The first level has n stones.\n// The number of stones in the next level is:\n// - the next odd number if n is odd.\n// - the next even number if n is even.\n// Return the number of stones in each level in an array, where element at index\n// i represents the number of stones in the level (i+1).\n// Examples:\n// >>> make_a_pile(3)\n// [3, 5, 7]\nfunction make_a_pile(n){\n let stones = [n];\n let next = n % 2 === 0 ? n + 2 : n + 1;\n while (next <= n * 2) {\n stones.push(next);\n next += 2;\n }\n return stones;\n}\n"], ["//You will be given a string of words separated by commas or spaces. Your task is\n// to split the string into words and return an array of the words.\n// For example:\n// >>> words_string(\"Hi, my name is John\")\n// [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n// >>> words_string(\"One, two, three, four, five, six\")\n// [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\nfunction words_string(s){\n var words = s.split(/[ ,]+/);\n return words;\n}\n"], ["//This function takes two positive numbers x and y and returns the\n// biggest even integer number that is in the range [x, y] inclusive. If \n// there's no such number, then the function should return -1.\n// For example:\n// >>> choose_num(12, 15)\n// 14\n// >>> choose_num(13, 12)\n// -1\nfunction choose_num(x, y){\n for(let i = y; i >= x; i--){\n if(i % 2 === 0){\n return i;\n }\n }\n return -1;\n}\n"], ["//You are given two positive integers n and m, and your task is to compute the\n// average of the integers from n through m (including n and m). \n// Round the answer to the nearest integer and convert that to binary.\n// If n is greater than m, return -1.\n// Example:\n// >>> rounded_avg(1, 5)\n// \"0b11\"\n// >>> rounded_avg(7, 5)\n// -1\n// >>> rounded_avg(10, 20)\n// \"0b1111\"\n// >>> rounded_avg(20, 33)\n// \"0b11010\"\nfunction rounded_avg(n, m){\n if(n > m){\n return -1;\n }\n let sum = 0;\n for(let i = n; i <= m; i++){\n sum += i;\n }\n let avg = Math.round(sum / (m - n + 1));\n return (avg >>> 0).toString(2);\n}\n"], ["//Given an array of positive integers x. return a sorted array of all \n// elements that hasn't any even digit.\n// Note: Returned array should be sorted in increasing order.\n// For example:\n// >>> unique_digits([15, 33, 1422, 1])\n// [1, 15, 33]\n// >>> unique_digits([152, 323, 1422, 10])\n// []\nfunction unique_digits(x){\n let result = [];\n for(let i=0; i0){\n let digit = num%10;\n if(digit%2===0){\n hasEvenDigit = true;\n break;\n }\n num = Math.floor(num/10);\n }\n if(!hasEvenDigit){\n result.push(x[i]);\n }\n }\n result.sort(function(a, b){return a-b});\n return result;\n}\n"], ["//Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n// reverse the resulting array, and then replace each digit by its corresponding name from\n// \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n// For example:\n// >>> by_length([2, 1, 1, 4, 5, 8, 2, 3])\n// [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n// If the array is empty, return an empty array:\n// >>> by_length([])\n// []\n// If the array has any strange number ignore it:\n// >>> by_length([1, -1, 55])\n// [\"One\"]\nfunction by_length(arr){\n let nums = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"];\n let result = [];\n for(let i=0; i=1 && arr[i]<=9){\n result.push(nums[arr[i]-1]);\n }\n }\n return result.sort().reverse();\n}\n"], ["//Implement the function f that takes n as a parameter,\n// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even\n// or the sum of numbers from 1 to i otherwise.\n// i starts from 1.\n// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n// Example:\n// >>> f(5)\n// [1, 2, 6, 24, 15]\nfunction f(n){\n let arr = [];\n for(let i=1; i<=n; i++){\n if(i%2 === 0){\n let factorial = 1;\n for(let j=1; j<=i; j++){\n factorial *= j;\n }\n arr.push(factorial);\n } else {\n let sum = 0;\n for(let j=1; j<=i; j++){\n sum += j;\n }\n arr.push(sum);\n }\n }\n return arr;\n}\n"], ["//Given a positive integer n, return an array that has the number of even and odd\n// integer palindromes that fall within the range(1, n), inclusive.\n// Example 1:\n// >>> even_odd_palindrome(3)\n// [1, 2]\n// Explanation:\n// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n// Example 2:\n// >>> even_odd_palindrome(12)\n// [4, 6]\n// Explanation:\n// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n// Note:\n// 1. 1 <= n <= 10^3\n// 2. returned array has the number of even and odd integer palindromes respectively.\nfunction even_odd_palindrome(n){\n let even = 0;\n let odd = 0;\n for(let i=1; i<=n; i++){\n let str = i.toString();\n if(str === str.split('').reverse().join('')){\n if(i%2 === 0){\n even++;\n }else{\n odd++;\n }\n }\n }\n return [even, odd];\n}\n"], ["//Write a function count_nums which takes an array of integers and returns\n// the number of elements which has a sum of digits > 0.\n// If a number is negative, then its first signed digit will be negative:\n// e.g. -123 has signed digits -1, 2, and 3.\n// >>> count_nums([])\n// 0\n// >>> count_nums([-1, 11, -11])\n// 1\n// >>> count_nums([1, 1, 2])\n// 3\nfunction count_nums(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n let num = arr[i];\n let sum = 0;\n while(num !== 0){\n sum += num % 10;\n num = Math.floor(num / 10);\n }\n if(sum > 0){\n count++;\n }\n }\n return count;\n}\n"], ["//We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n// numbers in the array will be randomly ordered. Your task is to determine if\n// it is possible to get an array sorted in non-decreasing order by performing \n// the following operation on the given array:\n// You are allowed to perform right shift operation any number of times.\n// One right shift operation means shifting all elements of the array by one\n// position in the right direction. The last element of the array will be moved to\n// the starting position in the array i.e. 0th index. \n// If it is possible to obtain the sorted array by performing the above operation\n// then return true else return false.\n// If the given array is empty then return true.\n// Note: The given array is guaranteed to have unique elements.\n// For Example:\n// >>> move_one_ball([3, 4, 5, 1, 2])\n// true\n// Explanation: By performin 2 right shift operations, non-decreasing order can\n// be achieved for the given array.\n// >>> move_one_ball([3, 5, 4, 1, 2])\n// false\n// Explanation:It is not possible to get non-decreasing order for the given\n// array by performing any number of right shift operations.\nfunction move_one_ball(arr){\n if(arr.length === 0){\n return true;\n }\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] > arr[(i+1)%arr.length]){\n count++;\n }\n }\n return count <= 1;\n}\n"], ["//Find the shortest palindrome that begins with a supplied string.\n// Algorithm idea is simple:\n// - Find the longest postfix of supplied string that is a palindrome.\n// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n// >>> make_palindrome(\"\")\n// \"\"\n// >>> make_palindrome(\"cat\")\n// \"catac\"\n// >>> make_palindrome(\"cata\")\n// \"catac\"\nfunction make_palindrome(string){\n let reversed = string.split(\"\").reverse().join(\"\");\n let length = string.length;\n for(let i=0; i>> exchange([1, 2, 3, 4], [1, 2, 3, 4])\n// \"YES\"\n// >>> exchange([1, 2, 3, 4], [1, 5, 3, 4])\n// \"NO\"\n// It is assumed that the input arrays will be non-empty.\nfunction exchange(lst1, lst2){\n let count = 0;\n for(let i = 0; i < lst1.length; i++){\n if(lst1[i] % 2 !== 0){\n count++;\n }\n }\n for(let i = 0; i < lst2.length; i++){\n if(lst2[i] % 2 === 0){\n count--;\n }\n }\n if(count <= 0){\n return \"YES\";\n } else {\n return \"NO\";\n }\n}\n"], ["//Given a string representing a space separated lowercase letters, return an object\n// of the letter with the most repetition and containing the corresponding count.\n// If several letters have the same occurrence, return all of them.\n// Example:\n// >>> histogram(\"a b c\")\n// {\"a\": 1, \"b\": 1, \"c\": 1}\n// >>> histogram(\"a b b a\")\n// {\"a\": 2, \"b\": 2}\n// >>> histogram(\"a b c a b\")\n// {\"a\": 2, \"b\": 2}\n// >>> histogram(\"b b b b a\")\n// {\"b\": 4}\n// >>> histogram(\"\")\n// {}\nfunction histogram(test){\n let letters = test.split(\" \");\n let letterCount = {};\n let maxCount = 0;\n let result = {};\n\n for(let i = 0; i < letters.length; i++){\n if(letterCount[letters[i]]){\n letterCount[letters[i]]++;\n } else {\n letterCount[letters[i]] = 1;\n }\n if(letterCount[letters[i]] > maxCount){\n maxCount = letterCount[letters[i]];\n }\n }\n\n for(let letter in letterCount){\n if(letterCount[letter] === maxCount){\n result[letter] = maxCount;\n }\n }\n\n return result;\n}\n"], ["//Task\n// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n// then check if the result string is palindrome.\n// A string is called palindrome if it reads the same backward as forward.\n// You should return an array containing the result string and true/false for the check.\n// Example\n// >>> reverse_delete(\"abcde\", \"ae\")\n// [\"bcd\", false]\n// >>> reverse_delete(\"abcdef\", \"b\")\n// [\"acdef\", false]\n// >>> reverse_delete(\"abcdedcba\", \"ab\")\n// [\"cdedc\", true]\nfunction reverse_delete(s, c){\n // Delete all characters in s that are equal to any character in c\n let result = s.split('').filter(char => !c.includes(char)).join('');\n // Check if the result string is palindrome\n let isPalindrome = result === result.split('').reverse().join('');\n // Return an array containing the result string and true/false for the check\n return [result, isPalindrome];\n}\n"], ["//Given an array of strings, where each string consists of only digits, return an array.\n// Each element i of the output should be \"the number of odd elements in the\n// string i of the input.\" where all the i's should be replaced by the number\n// of odd digits in the i'th string of the input.\n// >>> odd_count([\"1234567\"])\n// [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n// >>> odd_count([\"3\", \"11111111\"])\n// [\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\nfunction odd_count(lst){\n let result = [];\n for(let i = 0; i < lst.length; i++){\n let count = 0;\n for(let j = 0; j < lst[i].length; j++){\n if(lst[i][j] % 2 !== 0){\n count++;\n }\n }\n result.push(\"the number of odd elements \" + count + \"n the str\" + count + \"ng \" + count + \" of the \" + count + \"nput.\");\n }\n return result;\n}\n"], ["//Given an array of integers nums, find the minimum sum of any non-empty sub-array\n// of nums.\n// Example\n// >>> minSubArraySum([2, 3, 4, 1, 2, 4])\n// 1\n// >>> minSubArraySum([-1, -2, -3])\n// -6\nfunction minSubArraySum(nums){\n let minSum = nums[0];\n let currSum = nums[0];\n \n for(let i = 1; i < nums.length; i++){\n currSum = Math.min(nums[i], currSum + nums[i]);\n minSum = Math.min(minSum, currSum);\n }\n \n return minSum;\n}\n"], ["//You are given a rectangular grid of wells. Each row represents a single well,\n// and each 1 in a row represents a single unit of water.\n// Each well has a corresponding bucket that can be used to extract water from it, \n// and all buckets have the same capacity.\n// Your task is to use the buckets to empty the wells.\n// Output the number of times you need to lower the buckets.\n// Example 1:\n// >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)\n// 6\n// Example 2:\n// >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)\n// 5\n// Example 3:\n// >>> max_fill([[0, 0, 0], [0, 0, 0]], 5)\n// 0\n// Constraints:\n// * all wells have the same length\n// * 1 <= grid.length <= 10^2\n// * 1 <= grid[:,1].length <= 10^2\n// * grid[i][j] -> 0 | 1\n// * 1 <= capacity <= 10\nfunction max_fill(grid, capacity){\n let count = 0;\n let bucket = 0;\n for(let i = 0; i < grid.length; i++){\n for(let j = 0; j < grid[i].length; j++){\n if(grid[i][j] === 1){\n if(bucket < capacity){\n bucket++;\n }\n else{\n count++;\n bucket = 1;\n }\n }\n }\n }\n return count;\n}\n"], ["//In this Kata, you have to sort an array of non-negative integers according to\n// number of ones in their binary representation in ascending order.\n// For similar number of ones, sort based on decimal value.\n// It must be implemented like this:\n// >>> sort_array([1, 5, 2, 3, 4])\n// [1, 2, 3, 4, 5]\n// >>> sort_array([-2, -3, -4, -5, -6])\n// [-6, -5, -4, -3, -2]\n// >>> sort_array([1, 0, 2, 3, 4])\n// [0, 1, 2, 3, 4]\nfunction sort_array(arr){\n return arr.sort((a, b) => {\n let onesA = a.toString(2).split('').filter(x => x === '1').length;\n let onesB = b.toString(2).split('').filter(x => x === '1').length;\n if (onesA === onesB) {\n return a - b;\n } else {\n return onesA - onesB;\n }\n });\n}\n"], ["//Given a string s and a natural number n, you have been tasked to implement \n// a function that returns an array of all words from string s that contain exactly \n// n consonants, in order these words appear in the string s.\n// If the string s is empty then the function should return an empty array.\n// Note: you may assume the input string contains only letters and spaces.\n// Examples:\n// >>> select_words(\"Mary had a little lamb\", 4)\n// [\"little\"]\n// >>> select_words(\"Mary had a little lamb\", 3)\n// [\"Mary\", \"lamb\"]\n// >>> select_words(\"simple white space\", 2)\n// []\n// >>> select_words(\"Hello world\", 4)\n// [\"world\"]\n// >>> select_words(\"Uncle sam\", 3)\n// [\"Uncle\"]\nfunction select_words(s, n){\n if(s.length === 0){\n return [];\n }\n let words = s.split(\" \");\n let result = [];\n for(let i = 0; i < words.length; i++){\n let count = 0;\n for(let j = 0; j < words[i].length; j++){\n if(words[i][j].match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/)){\n count++;\n }\n }\n if(count === n){\n result.push(words[i]);\n }\n }\n return result;\n}\n"], ["//You are given a word. Your task is to find the closest vowel that stands between \n// two consonants from the right side of the word (case sensitive).\n// Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n// find any vowel met the above condition. \n// You may assume that the given string contains English letter only.\n// Example:\n// >>> get_closest_vowel(\"yogurt\")\n// \"u\"\n// >>> get_closest_vowel(\"FULL\")\n// \"U\"\n// >>> get_closest_vowel(\"quick\")\n// \"\"\n// >>> get_closest_vowel(\"ab\")\n// \"\"\nfunction get_closest_vowel(word){\n let vowels = ['a', 'e', 'i', 'o', 'u'];\n let consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];\n let closest_vowel = '';\n let distance = Infinity;\n for(let i=0; i>> match_parens([\"()(\", \")\"])\n// \"Yes\"\n// >>> match_parens([\")\", \")\"])\n// \"No\"\nfunction match_parens(lst){\n let str = lst.join(\"\");\n let stack = [];\n for(let i = 0; i < str.length; i++){\n if(str[i] === '('){\n stack.push('(');\n } else if(str[i] === ')'){\n if(stack.length === 0){\n return \"No\";\n } else {\n stack.pop();\n }\n }\n }\n if(stack.length === 0){\n return \"Yes\";\n } else {\n return \"No\";\n }\n}\n"], ["//Input are two strings a and b consisting only of 1s and 0s.\n// Perform binary XOR on these inputs and return result also as a string.\n// >>> string_xor(\"010\", \"110\")\n// \"100\"\nfunction string_xor(a, b){\n let result = \"\";\n for(let i=0; i>> maximum([-3, -4, 5], 3)\n// [-4, -3, 5]\n// Example 2:\n// >>> maximum([4, -4, 4], 2)\n// [4, 4]\n// Example 3:\n// >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)\n// [2]\n// Note:\n// 1. The length of the array will be in the range of [1, 1000].\n// 2. The elements in the array will be in the range of [-1000, 1000].\n// 3. 0 <= k <= len(arr)\nfunction maximum(arr, k){\n arr.sort(function(a, b){return b-a}); //sort the array in descending order\n return arr.slice(0, k); //return the first k elements of the sorted array\n}\n"], ["//Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.\n// Examples\n// >>> solution([5, 8, 7, 1])\n// 12\n// >>> solution([3, 3, 3, 3, 3])\n// 9\n// >>> solution([30, 13, 24, 321])\n// 0\nfunction solution(lst){\n let sum = 0;\n for(let i = 0; i < lst.length; i+=2){\n if(lst[i] % 2 !== 0){\n sum += lst[i];\n }\n }\n return sum;\n}\n"], ["//Given a non-empty array of integers arr and an integer k, return\n// the sum of the elements with at most two digits from the first k elements of arr.\n// Example:\n// >>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)\n// 24\n// Constraints:\n// 1. 1 <= len(arr) <= 100\n// 2. 1 <= k <= len(arr)\nfunction add_elements(arr, k){\n let sum = 0;\n for(let i=0; i>> get_odd_collatz(5)\n// [1, 5]\nfunction get_odd_collatz(n){\n let collatz_sequence = [n];\n while(n != 1){\n if(n % 2 == 0){\n n = n / 2;\n } else {\n n = 3 * n + 1;\n }\n collatz_sequence.push(n);\n }\n let odd_collatz_sequence = collatz_sequence.filter(num => num % 2 != 0);\n return odd_collatz_sequence.sort((a, b) => a - b);\n}\n"], ["//You have to write a function which validates a given date string and\n// returns true if the date is valid otherwise false.\n// The date is valid if all of the following rules are satisfied:\n// 1. The date string is not empty.\n// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n// 3. The months should not be less than 1 or higher than 12.\n// 4. The date should be in the format: mm-dd-yyyy\n// >>> valid_date(\"03-11-2000\")\n// true\n// >>> valid_date(\"15-01-2012\")\n// false\n// >>> valid_date(\"04-0-2040\")\n// false\n// >>> valid_date(\"06-04-2020\")\n// true\n// >>> valid_date(\"06/04/2020\")\n// false\nfunction valid_date(date){\n if(date.length === 0){\n return false;\n }\n let dateArr = date.split(\"-\");\n let month = parseInt(dateArr[0]);\n let day = parseInt(dateArr[1]);\n let year = parseInt(dateArr[2]);\n if(isNaN(month) || isNaN(day) || isNaN(year)){\n return false;\n }\n if(month < 1 || month > 12){\n return false;\n }\n if(day < 1 || day > 31){\n return false;\n }\n if(month === 2 && day > 29){\n return false;\n }\n if((month === 4 || month === 6 || month === 9 || month === 11) && day > 30){\n return false;\n }\n return true;\n}\n"], ["//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you\n// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n// Examples\n// >>> split_words(\"Hello world!\")\n// [\"Hello\", \"world!\"]\n// >>> split_words(\"Hello,world!\")\n// [\"Hello\", \"world!\"]\n// >>> split_words(\"abcdef\")\n// 3\nfunction split_words(txt){\n if(txt.includes(\" \")){\n return txt.split(\" \");\n }\n else if(txt.includes(\",\")){\n return txt.split(\",\");\n }\n else{\n let count = 0;\n for(let i=0; i= 'a' && txt[i] <= 'z' && txt[i].charCodeAt(0) % 2 !== 0){\n count++;\n }\n }\n return count;\n }\n}\n"], ["//Given an array of numbers, return whether or not they are sorted\n// in ascending order. If array has more than 1 duplicate of the same\n// number, return false. Assume no negative numbers and only integers.\n// Examples\n// >>> is_sorted([5])\n// true\n// >>> is_sorted([1, 2, 3, 4, 5])\n// true\n// >>> is_sorted([1, 3, 2, 4, 5])\n// false\n// >>> is_sorted([1, 2, 3, 4, 5, 6])\n// true\n// >>> is_sorted([1, 2, 3, 4, 5, 6, 7])\n// true\n// >>> is_sorted([1, 3, 2, 4, 5, 6, 7])\n// false\n// >>> is_sorted([1, 2, 2, 3, 3, 4])\n// true\n// >>> is_sorted([1, 2, 2, 2, 3, 4])\n// false\nfunction is_sorted(lst){\n for(let i = 0; i < lst.length - 1; i++){\n if(lst[i] >= lst[i+1]){\n return false;\n }\n }\n return true;\n}\n"], ["//You are given two intervals,\n// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n// The given intervals are closed which means that the interval (start, end)\n// includes both start and end.\n// For each given interval, it is assumed that its start is less or equal its end.\n// Your task is to determine whether the length of intersection of these two \n// intervals is a prime number.\n// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n// which its length is 1, which not a prime number.\n// If the length of the intersection is a prime number, return \"YES\",\n// otherwise, return \"NO\".\n// If the two intervals don't intersect, return \"NO\".\n// [input/output] samples:\n// >>> intersection([1, 2], [2, 3])\n// \"NO\"\n// >>> intersection([-1, 1], [0, 4])\n// \"NO\"\n// >>> intersection([-3, -1], [-5, 5])\n// \"YES\"\nfunction intersection(interval1, interval2){\n let start = Math.max(interval1[0], interval2[0]);\n let end = Math.min(interval1[1], interval2[1]);\n let length = end - start;\n if(length < 0){\n return \"NO\";\n }\n if(length === 1){\n return \"NO\";\n }\n for(let i = 2; i < length; i++){\n if(length % i === 0){\n return \"NO\";\n }\n }\n return \"YES\";\n}\n"], ["//You are given an array arr of integers and you need to return\n// sum of magnitudes of integers multiplied by product of all signs\n// of each number in the array, represented by 1, -1 or 0.\n// Note: return undefined for empty arr.\n// Example:\n// >>> prod_signs([1, 2, 2, -4])\n// 9\n// >>> prod_signs([0, 1])\n// 0\n// >>> prod_signs([])\n// undefined\nfunction prod_signs(arr){\n if(arr.length === 0){\n return undefined;\n }\n let sum = 0;\n let product = 1;\n for(let i = 0; i < arr.length; i++){\n sum += Math.abs(arr[i]);\n product *= Math.sign(arr[i]);\n }\n return sum * product;\n}\n"], ["//Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n// each cell of the grid contains a value. Every integer in the range [1, N * N]\n// inclusive appears exactly once on the cells of the grid.\n// You have to find the minimum path of length k in the grid. You can start\n// from any cell, and in each step you can move to any of the neighbor cells,\n// in other words, you can go to cells which share an edge with you current\n// cell.\n// Please note that a path of length k means visiting exactly k cells (not\n// necessarily distinct).\n// You CANNOT go off the grid.\n// A path A (of length k) is considered less than a path B (of length k) if\n// after making the ordered arrays of the values on the cells that A and B go\n// through (let's call them lst_A and lst_B), lst_A is lexicographically less\n// than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n// lst_A[j] = lst_B[j].\n// It is guaranteed that the answer is unique.\n// Return an ordered array of the values on the cells that the minimum path go through.\n// Examples: \n// >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)\n// [1, 2, 1]\n// >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)\n// [1]\nfunction minPath(grid, k){\n let n = grid.length;\n let dp = new Array(n).fill(0).map(() => new Array(n).fill(0));\n let minPath = new Array(k).fill(0);\n let minVal = Number.MAX_SAFE_INTEGER;\n\n for(let i = 0; i < n; i++){\n for(let j = 0; j < n; j++){\n dp[i][j] = grid[i][j];\n }\n }\n\n for(let len = 1; len <= k; len++){\n for(let i = 0; i < n; i++){\n for(let j = 0; j < n; j++){\n let minNeighbor = Number.MAX_SAFE_INTEGER;\n for(let x = Math.max(0, i - 1); x <= Math.min(n - 1, i + 1); x++){\n for(let y = Math.max(0, j - 1); y <= Math.min(n - 1, j + 1); y++){\n if(x != i || y != j){\n minNeighbor = Math.min(minNeighbor, dp[x][y]);\n }\n }\n }\n dp[i][j] += minNeighbor;\n if(len == k && dp[i][j] < minVal){\n minVal = dp[i][j];\n minPath[len - 1] = grid[i][j];\n }\n }\n }\n }\n\n return minPath;\n}\n"], ["//Out of array of strings, return the longest one. Return the first one in case of multiple\n// strings of the same length. Return undefined in case the input array is empty.\n// >>> longest([])\n// undefined\n// >>> longest([\"a\", \"b\", \"c\"])\n// \"a\"\n// >>> longest([\"a\", \"bb\", \"ccc\"])\n// \"ccc\"\nfunction longest(strings){\n if(strings.length === 0){\n return undefined;\n }\n let longestString = strings[0];\n for(let i = 1; i < strings.length; i++){\n if(strings[i].length > longestString.length){\n longestString = strings[i];\n }\n }\n return longestString;\n}\n"], ["//Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n// the last couple centuries. However, what people don't know is Tribonacci sequence.\n// Tribonacci sequence is defined by the recurrence:\n// tri(1) = 3\n// tri(n) = 1 + n / 2, if n is even.\n// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n// For example:\n// tri(2) = 1 + (2 / 2) = 2\n// tri(4) = 3\n// tri(3) = tri(2) + tri(1) + tri(4)\n// = 2 + 3 + 3 = 8 \n// You are given a non-negative integer number n, you have to a return an array of the \n// first n + 1 numbers of the Tribonacci sequence.\n// Examples:\n// >>> tri(3)\n// [1, 3, 2, 8]\nfunction tri(n){\n let arr = [1, 3];\n for(let i = 2; i <= n; i++){\n if(i % 2 === 0){\n arr.push(1 + i / 2);\n } else {\n arr.push(arr[i-2] + arr[i-1] + arr[i]);\n }\n }\n return arr;\n}\n"], ["//Given a positive integer n, return the product of the odd digits.\n// Return 0 if all digits are even.\n// For example:\n// >>> digits(1)\n// 1\n// >>> digits(4)\n// 0\n// >>> digits(235)\n// 15\nfunction digits(n){\n let product = 1;\n while(n > 0){\n let digit = n % 10;\n if(digit % 2 !== 0){\n product *= digit;\n }\n n = Math.floor(n / 10);\n }\n return product;\n}\n"], ["//Create a function that takes a string as input which contains only square brackets.\n// The function should return true if and only if there is a valid subsequence of brackets \n// where at least one bracket in the subsequence is nested.\n// >>> is_nested(\"[[]]\")\n// true\n// >>> is_nested(\"[]]]]]]][[[[[]\")\n// false\n// >>> is_nested(\"[][]\")\n// false\n// >>> is_nested(\"[]\")\n// false\n// >>> is_nested(\"[[][]]\")\n// true\n// >>> is_nested(\"[[]][[\")\n// true\nfunction is_nested(string){\n let stack = [];\n for(let i=0; i 0;\n}\n"], ["//You are given an array of numbers.\n// You need to return the sum of squared numbers in the given array,\n// round each element in the array to the upper int(Ceiling) first.\n// Examples:\n// >>> lst([1.0, 2.0, 3.0])\n// 14\n// >>> lst([1.0, 4.0, 9.0])\n// 98\n// >>> lst([1.0, 3.0, 5.0, 7.0])\n// 84\n// >>> lst([1.4, 4.2, 0.0])\n// 29\n// >>> lst([-2.4, 1.0, 1.0])\n// 6\nfunction sum_squares(lst){\n let sum = 0;\n for(let i=0; i>> check_if_last_char_is_a_letter(\"apple pie\")\n// false\n// >>> check_if_last_char_is_a_letter(\"apple pi e\")\n// true\n// >>> check_if_last_char_is_a_letter(\"apple pi e \")\n// false\n// >>> check_if_last_char_is_a_letter(\"\")\n// false\nfunction check_if_last_char_is_a_letter(txt){\n //Check if the string is empty\n if(txt.length === 0){\n return false;\n }\n //Get the last character of the string\n let lastChar = txt.charAt(txt.length - 1);\n //Check if the last character is an alphabetical character\n if(/[a-zA-Z]/.test(lastChar)){\n //Check if the last character is a part of a word\n if(txt.charAt(txt.length - 2) === \" \"){\n return false;\n }\n return true;\n }\n return false;\n}\n"], ["//Create a function which returns the largest index of an element which\n// is not greater than or equal to the element immediately preceding it. If\n// no such element exists then return -1. The given array will not contain\n// duplicate values.\n// Examples:\n// >>> can_arrange([1, 2, 4, 3, 5])\n// 3\n// >>> can_arrange([1, 2, 3])\n// -1\nfunction can_arrange(arr){\n for(let i=1; i>> largest_smallest_integers([2, 4, 1, 3, 5, 7])\n// [undefined, 1]\n// >>> largest_smallest_integers([])\n// [undefined, undefined]\n// >>> largest_smallest_integers([0])\n// [undefined, undefined]\nfunction largest_smallest_integers(lst){\n let negatives = lst.filter(num => num < 0);\n let positives = lst.filter(num => num > 0);\n let largest_negative = Math.max(...negatives);\n let smallest_positive = Math.min(...positives);\n if(negatives.length === 0 && positives.length === 0){\n return [undefined, undefined];\n }\n else if(negatives.length === 0){\n return [undefined, smallest_positive];\n }\n else if(positives.length === 0){\n return [largest_negative, undefined];\n }\n else{\n return [largest_negative, smallest_positive];\n }\n}\n"], ["//Create a function that takes integers, floats, or strings representing\n// real numbers, and returns the larger variable in its given variable type.\n// Return undefined if the values are equal.\n// Note: If a real number is represented as a string, the floating point might be . or ,\n// >>> compare_one(1, 2.5)\n// 2.5\n// >>> compare_one(1, \"2,3\")\n// \"2,3\"\n// >>> compare_one(\"5,1\", \"6\")\n// \"6\"\n// >>> compare_one(\"1\", 1)\n// undefined\nfunction compare_one(a, b){\n if(typeof a === 'string'){\n a = parseFloat(a.replace(',', '.'));\n }\n if(typeof b === 'string'){\n b = parseFloat(b.replace(',', '.'));\n }\n if(a > b){\n return a;\n } else if(b > a){\n return b;\n } else {\n return undefined;\n }\n}\n"], ["//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n// Example\n// >>> is_equal_to_sum_even(4)\n// false\n// >>> is_equal_to_sum_even(6)\n// false\n// >>> is_equal_to_sum_even(8)\n// true\nfunction is_equal_to_sum_even(n){\n if(n % 4 !== 0){\n return false;\n }\n else{\n return true;\n }\n}\n"], ["//The Brazilian factorial is defined as:\n// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n// where n > 0\n// For example:\n// >>> special_factorial(4)\n// 288\n// The function will receive an integer as input and should return the special\n// factorial of this integer.\nfunction special_factorial(n){\n let result = 1;\n for(let i=1; i<=n; i++){\n result *= i!;\n }\n return result;\n}\n"], ["//Return a greatest common divisor of two integers a and b\n// >>> greatest_common_divisor(3, 5)\n// 1\n// >>> greatest_common_divisor(25, 15)\n// 5\nfunction greatest_common_divisor(a, b){\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n"], ["//Given a string text, replace all spaces in it with underscores, \n// and if a string has more than 2 consecutive spaces, \n// then replace all consecutive spaces with - \n// >>> fix_spaces(\" Example\")\n// \"Example\"\n// >>> fix_spaces(\" Example 1\")\n// \"Example_1\"\n// >>> fix_spaces(\" Example 2\")\n// \"_Example_2\"\n// >>> fix_spaces(\" Example 3\")\n// \"_Example-3\"\nfunction fix_spaces(text){\n // Replace all spaces with underscores\n text = text.replace(/ /g, '_');\n \n // Replace all consecutive spaces with -\n text = text.replace(/_+/g, '-');\n \n return text;\n}\n"], ["//Create a function which takes a string representing a file's name, and returns\n// 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n// A file's name is considered to be valid if and only if all the following conditions \n// are met:\n// - There should not be more than three digits ('0'-'9') in the file's name.\n// - The file's name contains exactly one dot '.'\n// - The substring before the dot should not be empty, and it starts with a letter from \n// the latin alphapet ('a'-'z' and 'A'-'Z').\n// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n// Examples:\n// >>> file_name_check(\"example.txt\")\n// \"Yes\"\n// >>> file_name_check(\"1example.dll\")\n// \"No\"\nfunction file_name_check(file_name){\n //Check if there are more than three digits in the file's name\n if(file_name.match(/\\d/g).length > 3){\n return \"No\";\n }\n //Check if the file's name contains exactly one dot\n if(file_name.split('.').length !== 2){\n return \"No\";\n }\n //Check if the substring before the dot is not empty and starts with a letter\n if(!file_name.split('.')[0].match(/^[a-zA-Z]/)){\n return \"No\";\n }\n //Check if the substring after the dot is one of the allowed extensions\n if(!['txt', 'exe', 'dll'].includes(file_name.split('.')[1])){\n return \"No\";\n }\n //If all conditions are met, return 'Yes'\n return \"Yes\";\n}\n"], ["//\"\n// This function will take an array of integers. For all entries in the array, the function shall square the integer entry if its index is a \n// multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n// change the entries in the array whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n// Examples:\n// >>> lst\n// [1, 2, 3]\n// >>> lst\n// []\n// >>> lst\n// [-1, -5, 2, -1, -5]\nfunction sum_squares(lst){\n let sum = 0;\n for(let i=0; i>> words_in_sentence(\"This is a test\")\n// \"is\"\n// Example 2:\n// >>> words_in_sentence(\"lets go for swimming\")\n// \"go for\"\n// Constraints:\n// * 1 <= len(sentence) <= 100\n// * sentence contains only letters\nfunction words_in_sentence(sentence){\n let words = sentence.split(\" \");\n let primeWords = [];\n for(let i=0; i/ where both numerator and denominator are positive whole numbers.\n// You can assume that x, and n are valid fractions, and do not have zero as denominator.\n// >>> simplify(\"1/5\", \"5/1\")\n// true\n// >>> simplify(\"1/6\", \"2/1\")\n// false\n// >>> simplify(\"7/10\", \"10/2\")\n// false\nfunction simplify(x, n){\n let xArr = x.split('/');\n let nArr = n.split('/');\n let xNum = parseInt(xArr[0]);\n let xDen = parseInt(xArr[1]);\n let nNum = parseInt(nArr[0]);\n let nDen = parseInt(nArr[1]);\n let result = (xNum * nNum) / (xDen * nDen);\n return Number.isInteger(result);\n}\n"], ["//Write a function which sorts the given array of integers\n// in ascending order according to the sum of their digits.\n// Note: if there are several items with similar sum of their digits,\n// order them based on their index in original array.\n// For example:\n// >>> order_by_points([1, 11, -1, -11, -12])\n// [-1, -11, 1, -12, 11]\n// >>> order_by_points([])\n// []\nfunction order_by_points(nums){\n // Helper function to calculate the sum of digits of a number\n function sum_digits(num){\n return Math.abs(num).toString().split('').reduce((a, b) => parseInt(a) + parseInt(b), 0);\n }\n\n // Sort the array based on the sum of digits and index\n return nums.sort((a, b) => {\n const sum_a = sum_digits(a);\n const sum_b = sum_digits(b);\n if (sum_a === sum_b) {\n return nums.indexOf(a) - nums.indexOf(b);\n } else {\n return sum_a - sum_b;\n }\n });\n}\n"], ["//Write a function that takes an array of numbers as input and returns \n// the number of elements in the array that are greater than 10 and both \n// first and last digits of a number are odd (1, 3, 5, 7, 9).\n// For example:\n// >>> specialFilter([15, -73, 14, -15])\n// 1\n// >>> specialFilter([33, -2, -3, 45, 21, 109])\n// 2\nfunction specialFilter(nums){\n let count = 0;\n for(let i = 0; i < nums.length; i++){\n let num = nums[i];\n if(num > 10 && num % 2 !== 0 && Math.floor(num / 10) % 2 !== 0){\n count++;\n }\n }\n return count;\n}\n"], ["//You are given a positive integer n. You have to create an integer array a of length n.\n// For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n// and a[i] + a[j] + a[k] is a multiple of 3.\n// Example :\n// >>> get_max_triples(5)\n// 1\n// Explanation: \n// a = [1, 3, 7, 13, 21]\n// The only valid triple is (1, 7, 13).\nfunction get_max_triples(n){\n let count = 0;\n for(let i=1; i<=n; i++){\n for(let j=i+1; j<=n; j++){\n for(let k=j+1; k<=n; k++){\n if((i*i - i + 1 + j*j - j + 1 + k*k - k + 1) % 3 === 0){\n count++;\n }\n }\n }\n }\n return count;\n}\n"], ["//There are eight planets in our solar system: the closerst to the Sun \n// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n// Uranus, Neptune.\n// Write a function that takes two planet names as strings planet1 and planet2. \n// The function should return an array containing all planets whose orbits are \n// located between the orbit of planet1 and the orbit of planet2, sorted by \n// the proximity to the sun. \n// The function should return an empty array if planet1 or planet2\n// are not correct planet names. \n// Examples\n// >>> bf(\"Jupiter\", \"Neptune\")\n// [\"Saturn\", \"Uranus\"]\n// >>> bf(\"Earth\", \"Mercury\")\n// \"Venus\"\n// >>> bf(\"Mercury\", \"Uranus\")\n// [\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\"]\nfunction bf(planet1, planet2){\n const planets = [\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\"];\n const index1 = planets.indexOf(planet1);\n const index2 = planets.indexOf(planet2);\n if(index1 === -1 || index2 === -1){\n return [];\n }\n const start = Math.min(index1, index2);\n const end = Math.max(index1, index2);\n return planets.slice(start + 1, end);\n}\n"], ["//Write a function that accepts an array of strings as a parameter,\n// deletes the strings that have odd lengths from it,\n// and returns the resulted array with a sorted order,\n// The array is always an array of strings and never an array of numbers,\n// and it may contain duplicates.\n// The order of the array should be ascending by length of each word, and you\n// should return the array sorted by that rule.\n// If two words have the same length, sort the array alphabetically.\n// The function should return an array of strings in sorted order.\n// You may assume that all words will have the same length.\n// For example:\n// >>> list_sort([\"aa\", \"a\", \"aaa\"])\n// [\"aa\"]\n// >>> list_sort([\"ab\", \"a\", \"aaa\", \"cd\"])\n// [\"ab\", \"cd\"]\nfunction sorted_list_sum(lst){\n let even_lst = lst.filter(word => word.length % 2 === 0);\n even_lst.sort((a, b) => a.length - b.length || a.localeCompare(b));\n return even_lst;\n}\n"], ["//Return array of all prefixes from shortest to longest of the input string\n// >>> all_prefixes(\"abc\")\n// [\"a\", \"ab\", \"abc\"]\nfunction all_prefixes(string){\n let prefixes = [];\n for(let i=1; i<=string.length; i++){\n prefixes.push(string.substring(0,i));\n }\n return prefixes;\n}\n"], ["//A simple program which should return the value of x if n is \n// a prime number and should return the value of y otherwise.\n// Examples:\n// >>> x_or_y(7, 34, 12)\n// 34\n// >>> x_or_y(15, 8, 5)\n// 5\nfunction x_or_y(n, x, y){\n for(let i = 2; i < n; i++){\n if(n % i === 0){\n return y;\n }\n }\n return x;\n}\n"], ["//Given an array of numbers, return the sum of squares of the numbers\n// in the array that are odd. Ignore numbers that are negative or not integers.\n// >>> double_the_difference([1, 3, 2, 0])\n// 10\n// >>> double_the_difference([-1, -2, 0])\n// 0\n// >>> double_the_difference([9, -2])\n// 81\n// >>> double_the_difference([0])\n// 0\n// If the input array is empty, return 0.\nfunction double_the_difference(lst){\n let sum = 0;\n for(let i=0; i>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])\n// [0, 0, 0, 0, 3, 3]\n// >>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2])\n// [4, 4, 1, 0, 0, 6]\nfunction compare(game, guess){\n let diff = [];\n for(let i=0; i>> Strongest_Extension(\"my_class\", [\"AA\", \"Be\", \"CC\"])\n// \"my_class.AA\"\nfunction Strongest_Extension(class_name, extensions){\n let strongest_extension = \"\";\n let strongest_strength = -Infinity;\n for(let i = 0; i < extensions.length; i++){\n let extension = extensions[i];\n let cap_count = 0;\n let sm_count = 0;\n for(let j = 0; j < extension.length; j++){\n if(extension[j] >= 'A' && extension[j] <= 'Z'){\n cap_count++;\n } else if(extension[j] >= 'a' && extension[j] <= 'z'){\n sm_count++;\n }\n }\n let strength = cap_count - sm_count;\n if(strength > strongest_strength){\n strongest_strength = strength;\n strongest_extension = extension;\n }\n }\n return class_name + \".\" + strongest_extension;\n}\n"], ["//You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n// >>> cycpattern_check(\"abcd\", \"abd\")\n// false\n// >>> cycpattern_check(\"hello\", \"ell\")\n// true\n// >>> cycpattern_check(\"whassup\", \"psus\")\n// false\n// >>> cycpattern_check(\"abab\", \"baa\")\n// true\n// >>> cycpattern_check(\"efef\", \"eeff\")\n// false\n// >>> cycpattern_check(\"himenss\", \"simen\")\n// true\nfunction cycpattern_check(a, b){\n for(let i=0; i>> even_odd_count(-12)\n// [1, 1]\n// >>> even_odd_count(123)\n// [1, 2]\nfunction even_odd_count(num){\n let evenCount = 0;\n let oddCount = 0;\n let numStr = Math.abs(num).toString();\n for(let i = 0; i < numStr.length; i++){\n let digit = parseInt(numStr[i]);\n if(digit % 2 === 0){\n evenCount++;\n } else {\n oddCount++;\n }\n }\n return [evenCount, oddCount];\n}\n"], ["//Given a positive integer, obtain its roman numeral equivalent as a string,\n// and return it in lowercase.\n// Restrictions: 1 <= num <= 1000\n// Examples:\n// >>> int_to_mini_roman(19)\n// \"xix\"\n// >>> int_to_mini_roman(152)\n// \"clii\"\n// >>> int_to_mini_roman(426)\n// \"cdxxvi\"\nfunction int_to_mini_roman(number){\n let roman = \"\";\n let roman_numerals = {\n M: 1000,\n CM: 900,\n D: 500,\n CD: 400,\n C: 100,\n XC: 90,\n L: 50,\n XL: 40,\n X: 10,\n IX: 9,\n V: 5,\n IV: 4,\n I: 1\n };\n for (let key in roman_numerals) {\n while (number >= roman_numerals[key]) {\n roman += key;\n number -= roman_numerals[key];\n }\n }\n return roman.toLowerCase();\n}\n"], ["//Given the lengths of the three sides of a triangle. Return true if the three\n// sides form a right-angled triangle, false otherwise.\n// A right-angled triangle is a triangle in which one angle is right angle or \n// 90 degree.\n// Example:\n// >>> right_angle_triangle(3, 4, 5)\n// true\n// >>> right_angle_triangle(1, 2, 3)\n// false\nfunction right_angle_triangle(a, b, c){\n var sides = [a, b, c].sort(function(a, b){return a - b});\n return (Math.pow(sides[0], 2) + Math.pow(sides[1], 2) === Math.pow(sides[2], 2));\n}\n"], ["//Write a function that accepts an array of strings.\n// The array contains different words. Return the word with maximum number\n// of unique characters. If multiple strings have maximum number of unique\n// characters, return the one which comes first in lexicographical order.\n// >>> find_max([\"name\", \"of\", \"string\"])\n// \"string\"\n// >>> find_max([\"name\", \"enam\", \"game\"])\n// \"enam\"\n// >>> find_max([\"aaaaaaa\", \"bb\", \"cc\"])\n// \"aaaaaaa\"\nfunction find_max(words){\n let max_word = \"\";\n let max_unique_chars = 0;\n for(let i=0; i max_unique_chars){\n max_unique_chars = unique_chars.size;\n max_word = words[i];\n }\n else if(unique_chars.size === max_unique_chars && words[i] < max_word){\n max_word = words[i];\n }\n }\n return max_word;\n}\n"], ["//You're a hungry rabbit, and you already have eaten a certain number of carrots,\n// but now you need to eat more carrots to complete the day's meals.\n// you should return an array of [ total number of eaten carrots after your meals,\n// the number of carrots left after your meals ]\n// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n// Example:\n// >>> eat(5, 6, 10)\n// [11, 4]\n// >>> eat(4, 8, 9)\n// [12, 1]\n// >>> eat(1, 10, 10)\n// [11, 0]\n// >>> eat(2, 11, 5)\n// [7, 0]\n// Variables:\n// @number : integer\n// the number of carrots that you have eaten.\n// @need : integer\n// the number of carrots that you need to eat.\n// @remaining : integer\n// the number of remaining carrots thet exist in stock\n// Constrain:\n// * 0 <= number <= 1000\n// * 0 <= need <= 1000\n// * 0 <= remaining <= 1000\n// Have fun :)\nfunction eat(number, need, remaining){\n let total = number + need;\n let left = remaining - need;\n if(left < 0){\n left = 0;\n }\n return [total, left];\n}\n"], ["//Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n// >>> string_sequence(0)\n// \"0\"\n// >>> string_sequence(5)\n// \"0 1 2 3 4 5\"\nfunction string_sequence(n){\n let sequence = \"\";\n for(let i=0; i<=n; i++){\n sequence += i + \" \";\n }\n return sequence.trim();\n}\n"], ["//Given two arrays operator, and operand. The first array has basic algebra operations, and \n// the second array is an array of integers. Use the two given arrays to build the algebric \n// expression and return the evaluation of this expression.\n// The basic algebra operations:\n// Addition ( + ) \n// Subtraction ( - ) \n// Multiplication ( * ) \n// Floor division ( // ) \n// Exponentiation ( ** ) \n// Example:\n// operator['+', '*', '-']\n// array = [2, 3, 4, 5]\n// result = 2 + 3 * 4 - 5\n// => result = 9\n// Note:\n// The length of operator array is equal to the length of operand array minus one.\n// Operand is an array of of non-negative integers.\n// Operator array has at least one operator, and operand array has at least two operands.\nfunction do_algebra(operator, operand){\n let result = operand[0];\n for(let i=1; i>> solve(\"1234\")\n// \"4321\"\n// >>> solve(\"ab\")\n// \"AB\"\n// >>> solve(\"#a@C\")\n// \"#A@c\"\nfunction solve(s){\n let result = \"\";\n let hasLetter = false;\n for(let i = 0; i < s.length; i++){\n if(s[i].match(/[a-z]/i)){\n hasLetter = true;\n if(s[i] === s[i].toUpperCase()){\n result += s[i].toLowerCase();\n } else {\n result += s[i].toUpperCase();\n }\n } else {\n result += s[i];\n }\n }\n if(!hasLetter){\n result = result.split(\"\").reverse().join(\"\");\n }\n return result;\n}\n"], ["//Given a string 'text', return its md5 hash equivalent string.\n// If 'text' is an empty string, return undefined.\n// >>> string_to_md5(\"Hello world\")\n// \"3e25960a79dbc69b674cd4ec67a72c62\"\nfunction string_to_md5(text){\n if(text === \"\"){\n return undefined;\n }\n var md5 = require('md5');\n return md5(text);\n}\n"], ["//Given two positive integers a and b, return the even digits between a\n// and b, in ascending order.\n// For example:\n// >>> generate_integers(2, 8)\n// [2, 4, 6, 8]\n// >>> generate_integers(8, 2)\n// [2, 4, 6, 8]\n// >>> generate_integers(10, 14)\n// []\nfunction generate_integers(a, b){\n let start = Math.min(a, b);\n let end = Math.max(a, b);\n let result = [];\n for(let i = start; i <= end; i++){\n if(i % 2 === 0){\n result.push(i);\n }\n }\n return result;\n}\n"], ["//Given a string, find out how many distinct characters (regardless of case) does it consist of\n// >>> count_distinct_characters(\"xyzXYZ\")\n// 3\n// >>> count_distinct_characters(\"Jerry\")\n// 4\nfunction count_distinct_characters(string){\n let distinctChars = new Set(string.toLowerCase());\n return distinctChars.size;\n}\n"], ["//Input to this function is a string representing musical notes in a special ASCII format.\n// Your task is to parse this string and return array of integers corresponding to how many beats does each\n// not last.\n// Here is a legend:\n// 'o' - whole note, lasts four beats\n// 'o|' - half note, lasts two beats\n// '.|' - quater note, lasts one beat\n// >>> parse_music(\"o o| .| o| o| .| .| .| .| o o\")\n// [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\nfunction parse_music(music_string){\n let notes = music_string.split(' ');\n let beats = [];\n for(let i=0; i>> how_many_times(\"\", \"a\")\n// 0\n// >>> how_many_times(\"aaa\", \"a\")\n// 3\n// >>> how_many_times(\"aaaa\", \"aa\")\n// 3\nfunction how_many_times(string, substring){\n let count = 0;\n let index = 0;\n while(index < string.length){\n if(string.slice(index, index + substring.length) === substring){\n count++;\n index += substring.length;\n } else {\n index++;\n }\n }\n return count;\n}\n"], ["//Input is a space-delimited string of numberals from 'zero' to 'nine'.\n// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n// Return the string with numbers sorted from smallest to largest\n// >>> sort_numbers(\"three one five\")\n// \"one three five\"\nfunction sort_numbers(numbers){\n const nums = {\n zero: 0,\n one: 1,\n two: 2,\n three: 3,\n four: 4,\n five: 5,\n six: 6,\n seven: 7,\n eight: 8,\n nine: 9\n };\n const arr = numbers.split(' ');\n arr.sort((a, b) => nums[a] - nums[b]);\n return arr.join(' ');\n}\n"], ["//Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n// separate those group into separate strings and return the array of those.\n// Separate groups are balanced (each open brace is properly closed) and not nested within each other\n// Ignore any spaces in the input string.\n// >>> separate_paren_groups(\"( ) (( )) (( )( ))\")\n// [\"()\", \"(())\", \"(()())\"]\nfunction separate_paren_groups(paren_string){\n let groups = [];\n let current_group = \"\";\n let open_count = 0;\n\n for (let i = 0; i < paren_string.length; i++) {\n let char = paren_string[i];\n if (char === \"(\") {\n open_count++;\n } else if (char === \")\") {\n open_count--;\n }\n current_group += char;\n if (open_count === 0) {\n groups.push(current_group);\n current_group = \"\";\n }\n }\n\n return groups;\n}\n"], ["//From a supplied array of numbers (of length at least two) select and return two that are the closest to each\n// other and return them in order (smaller number, larger number).\n// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n// [2.0, 2.2]\n// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n// [2.0, 2.0]\nfunction find_closest_elements(numbers){\n numbers.sort((a, b) => a - b);\n let closest = [numbers[0], numbers[1]];\n let minDiff = Math.abs(numbers[0] - numbers[1]);\n for(let i = 1; i < numbers.length - 1; i++){\n let diff = Math.abs(numbers[i] - numbers[i+1]);\n if(diff < minDiff){\n minDiff = diff;\n closest = [numbers[i], numbers[i+1]];\n }\n }\n return closest;\n}\n"], ["//Given array of numbers (of at least two elements), apply a linear transform to that array,\n// such that the smallest number will become 0 and the largest will become 1\n// >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n// [0.0, 0.25, 0.5, 0.75, 1.0]\nfunction rescale_to_unit(numbers){\n let min = Math.min(...numbers);\n let max = Math.max(...numbers);\n let range = max - min;\n return numbers.map(num => (num - min) / range);\n}\n"], ["//Filter given array of any jsthon values only for integers\n// >>> filter_integers([\"a\", 3.14, 5])\n// [5]\n// >>> filter_integers([1, 2, 3, \"abc\", {}, []])\n// [1, 2, 3]\nfunction filter_integers(values){\n return values.filter(function(value){\n return Number.isInteger(value);\n });\n}\n"], ["//Return length of given string\n// >>> strlen(\"\")\n// 0\n// >>> strlen(\"abc\")\n// 3\nfunction strlen(string){\n return string.length;\n}\n"], ["//For a given number n, find the largest number that divides n evenly, smaller than n\n// >>> largest_divisor(15)\n// 5\nfunction largest_divisor(n){\n for(let i=n-1; i>0; i--){\n if(n%i===0){\n return i;\n }\n }\n}\n"], ["//Return array of prime factors of given integer in the order from smallest to largest.\n// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.\n// Input number should be equal to the product of all factors\n// >>> factorize(8)\n// [2, 2, 2]\n// >>> factorize(25)\n// [5, 5]\n// >>> factorize(70)\n// [2, 5, 7]\nfunction factorize(n){\n var factors = [];\n var divisor = 2;\n while(n > 1){\n while(n % divisor === 0){\n factors.push(divisor);\n n /= divisor;\n }\n divisor++;\n }\n return factors;\n}\n"], ["//From an array of integers, remove all elements that occur more than once.\n// Keep order of elements left the same as in the input.\n// >>> remove_duplicates([1, 2, 3, 2, 4])\n// [1, 3, 4]\nfunction remove_duplicates(numbers){\n let uniqueNumbers = [];\n numbers.forEach(number => {\n if (!uniqueNumbers.includes(number)) {\n uniqueNumbers.push(number);\n }\n });\n return uniqueNumbers;\n}\n"], ["//For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n// >>> flip_case(\"Hello\")\n// \"hELLO\"\nfunction flip_case(string){\n let flippedString = \"\";\n for(let i = 0; i < string.length; i++){\n if(string[i] === string[i].toUpperCase()){\n flippedString += string[i].toLowerCase();\n } else {\n flippedString += string[i].toUpperCase();\n }\n }\n return flippedString;\n}\n"], ["//Concatenate array of strings into a single string\n// >>> concatenate([])\n// \"\"\n// >>> concatenate([\"a\", \"b\", \"c\"])\n// \"abc\"\nfunction concatenate(strings){\n return strings.join(\"\");\n}\n"], ["//Filter an input array of strings only for ones that start with a given prefix.\n// >>> filter_by_prefix([], \"a\")\n// []\n// >>> filter_by_prefix([\"abc\", \"bcd\", \"cde\", \"array\"], \"a\")\n// [\"abc\", \"array\"]\nfunction filter_by_prefix(strings, prefix){\n return strings.filter(function(string){\n return string.startsWith(prefix);\n });\n}\n"], ["//Given a positive floating point number, it can be decomposed into\n// and integer part (largest integer smaller than given number) and decimals\n// (leftover part always smaller than 1).\n// Return the decimal part of the number.\n// >>> truncate_number(3.5)\n// 0.5\nfunction truncate_number(number){\n var integer_part = Math.floor(number);\n var decimal_part = number - integer_part;\n return decimal_part;\n}\n"], ["//Return only positive numbers in the array.\n// >>> get_positive([-1, 2, -4, 5, 6])\n// [2, 5, 6]\n// >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n// [5, 3, 2, 3, 9, 123, 1]\nfunction get_positive(l){\n return l.filter(function(x){\n return x > 0;\n });\n}\n"], ["//Return true if a given number is prime, and false otherwise.\n// >>> is_prime(6)\n// false\n// >>> is_prime(101)\n// true\n// >>> is_prime(11)\n// true\n// >>> is_prime(13441)\n// true\n// >>> is_prime(61)\n// true\n// >>> is_prime(4)\n// false\n// >>> is_prime(1)\n// false\nfunction is_prime(n){\n if(n < 2) return false;\n for(let i = 2; i <= Math.sqrt(n); i++){\n if(n % i === 0) return false;\n }\n return true;\n}\n"], ["//This function takes an array l and returns an array l' such that\n// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n// to the values of the corresponding indicies of l, but sorted.\n// >>> sort_third([1, 2, 3])\n// [1, 2, 3]\n// >>> sort_third([5, 6, 3, 4, 8, 9, 2])\n// [2, 6, 3, 4, 8, 9, 5]\nfunction sort_third(l){\n let l_prime = [];\n let third_values = [];\n for(let i=0; i>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n// [0, 2, 3, 5, 9, 123]\nfunction unique(l){\n return l.filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b);\n}\n"], ["//Return maximum element in the array.\n// >>> max_element([1, 2, 3])\n// 3\n// >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n// 123\nfunction max_element(l){\n return Math.max(...l);\n}\n"], ["//Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n// >>> fizz_buzz(50)\n// 0\n// >>> fizz_buzz(78)\n// 2\n// >>> fizz_buzz(79)\n// 3\nfunction fizz_buzz(n){\n let count = 0;\n for(let i = 1; i < n; i++){\n if(i % 11 === 0 || i % 13 === 0){\n let str = i.toString();\n let num = str.split('').filter(x => x === '7').length;\n count += num;\n }\n }\n return count;\n}\n"], ["//This function takes an array l and returns an array l' such that\n// l' is identical to l in the odd indicies, while its values at the even indicies are equal\n// to the values of the even indicies of l, but sorted.\n// >>> sort_even([1, 2, 3])\n// [1, 2, 3]\n// >>> sort_even([5, 6, 3, 4])\n// [3, 6, 5, 4]\nfunction sort_even(l){\n let even_values = l.filter((value, index) => index % 2 === 0).sort((a, b) => a - b);\n let result = [];\n for(let i = 0; i < l.length; i++){\n if(i % 2 === 0){\n result.push(even_values.shift());\n } else {\n result.push(l[i]);\n }\n }\n return result;\n}\n"], ["//prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n// >>> prime_fib(1)\n// 2\n// >>> prime_fib(2)\n// 3\n// >>> prime_fib(3)\n// 5\n// >>> prime_fib(4)\n// 13\n// >>> prime_fib(5)\n// 89\nfunction prime_fib(n){\n let fib = [0, 1];\n let i = 2;\n while (fib.length < n + 1) {\n fib[i] = fib[i - 1] + fib[i - 2];\n i++;\n }\n let prime = fib.filter(num => {\n for (let i = 2; i < num; i++) {\n if (num % i === 0) return false;\n }\n return num > 1;\n });\n return prime[n - 1];\n}\n"], ["//You're given an array of deposit and withdrawal operations on a bank account that starts with\n// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n// at that point function should return true. Otherwise it should return false.\n// >>> below_zero([1, 2, 3])\n// false\n// >>> below_zero([1, 2, -4, 5])\n// true\nfunction below_zero(operations){\n let balance = 0;\n for(let i=0; i>> triples_sum_to_zero([1, 3, 5, 0])\n// false\n// >>> triples_sum_to_zero([1, 3, -2, 1])\n// true\n// >>> triples_sum_to_zero([1, 2, 3, 7])\n// false\n// >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\n// true\n// >>> triples_sum_to_zero([1])\n// false\nfunction triples_sum_to_zero(l){\n for(let i=0; i>> incr_list([1, 2, 3])\n// [2, 3, 4]\n// >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n// [6, 4, 6, 3, 4, 4, 10, 1, 124]\nfunction incr_list(l){\n return l.map(x => x+1);\n}\n"], ["//pairs_sum_to_zero takes an array of integers as an input.\n// it returns true if there are two distinct elements in the array that\n// sum to zero, and false otherwise.\n// >>> pairs_sum_to_zero([1, 3, 5, 0])\n// false\n// >>> pairs_sum_to_zero([1, 3, -2, 1])\n// false\n// >>> pairs_sum_to_zero([1, 2, 3, 7])\n// false\n// >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\n// true\n// >>> pairs_sum_to_zero([1])\n// false\nfunction pairs_sum_to_zero(l){\n for(let i=0; i>> change_base(8, 3)\n// \"22\"\n// >>> change_base(8, 2)\n// \"1000\"\n// >>> change_base(7, 2)\n// \"111\"\nfunction change_base(x, base){\n return x.toString(base);\n}\n"], ["//Given length of a side and high return area for a triangle.\n// >>> triangle_area(5, 3)\n// 7.5\nfunction triangle_area(a, h){\n return (a * h) / 2;\n}\n"], ["//The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n// fib4(0) -> 0\n// fib4(1) -> 0\n// fib4(2) -> 2\n// fib4(3) -> 0\n// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n// >>> fib4(5)\n// 4\n// >>> fib4(6)\n// 8\n// >>> fib4(7)\n// 14\nfunction fib4(n){\n if(n < 4){\n return n === 3 ? 2 : 0;\n }\n let a = 0, b = 0, c = 2, d = 0;\n for(let i = 4; i <= n; i++){\n let temp = a + b + c + d;\n a = b;\n b = c;\n c = d;\n d = temp;\n }\n return d;\n}\n"], ["//Return median of elements in the array l.\n// >>> median([3, 1, 2, 4, 5])\n// 3\n// >>> median([-10, 4, 6, 1000, 10, 20])\n// 15.0\nfunction median(l){\n l.sort(function(a, b){return a - b});\n var len = l.length;\n if(len % 2 === 0){\n return (l[len/2 - 1] + l[len/2]) / 2;\n } else {\n return l[Math.floor(len/2)];\n }\n}\n"], ["//Checks if given string is a palindrome\n// >>> is_palindrome(\"\")\n// true\n// >>> is_palindrome(\"aba\")\n// true\n// >>> is_palindrome(\"aaaaa\")\n// true\n// >>> is_palindrome(\"zbcd\")\n// false\nfunction is_palindrome(text){\n var reversedText = text.split(\"\").reverse().join(\"\");\n return text === reversedText;\n}\n"], ["//Return 2^n modulo p (be aware of numerics).\n// >>> modp(3, 5)\n// 3\n// >>> modp(1101, 101)\n// 2\n// >>> modp(0, 101)\n// 1\n// >>> modp(3, 11)\n// 8\n// >>> modp(100, 101)\n// 1\nfunction modp(n, p){\n return Math.pow(2, n) % p;\n}\n"], ["//For a given array of input numbers, calculate Mean Absolute Deviation\n// around the mean of this dataset.\n// Mean Absolute Deviation is the average absolute difference between each\n// element and a centerpoint (mean in this case):\n// MAD = average | x - x_mean |\n// >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n// 1.0\nfunction mean_absolute_deviation(numbers){\n //Calculate the mean of the input numbers\n let mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;\n \n //Calculate the absolute difference between each element and the mean\n let absolute_differences = numbers.map(number => Math.abs(number - mean));\n \n //Calculate the mean of the absolute differences\n let mad = absolute_differences.reduce((a, b) => a + b, 0) / absolute_differences.length;\n \n return mad;\n}\n"], ["//remove_vowels is a function that takes string and returns string without vowels.\n// >>> remove_vowels(\"\")\n// \"\"\n// >>> remove_vowels(\"abcdef\")\n// \"bcdf\"\n// >>> remove_vowels(\"aaaaa\")\n// \"\"\n// >>> remove_vowels(\"aaBAA\")\n// \"B\"\n// >>> remove_vowels(\"zbcd\")\n// \"zbcd\"\nfunction remove_vowels(text){\n return text.replace(/[aeiouAEIOU]/g, \"\");\n}\n"], ["//Return true if all numbers in the array l are below threshold t.\n// >>> below_threshold([1, 2, 4, 10], 100)\n// true\n// >>> below_threshold([1, 20, 4, 10], 5)\n// false\nfunction below_threshold(l, t){\n for(let i=0; i= t){\n return false;\n }\n }\n return true;\n}\n"], ["//Add two numbers x and y\n// >>> add(2, 3)\n// 5\n// >>> add(5, 7)\n// 12\nfunction add(x, y){\n return x + y;\n}\n"], ["//Check if two words have the same characters.\n// >>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddeddabc\")\n// true\n// >>> same_chars(\"abcd\", \"dddddddabc\")\n// true\n// >>> same_chars(\"dddddddabc\", \"abcd\")\n// true\n// >>> same_chars(\"eabcd\", \"dddddddabc\")\n// false\n// >>> same_chars(\"abcd\", \"dddddddabce\")\n// false\n// >>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddddabc\")\n// false\nfunction same_chars(s0, s1){\n let s0_chars = s0.split('').sort().join('');\n let s1_chars = s1.split('').sort().join('');\n return s0_chars === s1_chars;\n}\n"], ["//Return n-th Fibonacci number.\n// >>> fib(10)\n// 55\n// >>> fib(1)\n// 1\n// >>> fib(8)\n// 21\nfunction fib(n){\n if (n <= 1) {\n return n;\n }\n let a = 0;\n let b = 1;\n for (let i = 2; i <= n; i++) {\n let c = a + b;\n a = b;\n b = c;\n }\n return b;\n}\n"], ["//brackets is a string of \"<\" and \">\".\n// return true if every opening bracket has a corresponding closing bracket.\n// >>> correct_bracketing(\"<\")\n// false\n// >>> correct_bracketing(\"<>\")\n// true\n// >>> correct_bracketing(\"<<><>>\")\n// true\n// >>> correct_bracketing(\"><<>\")\n// false\nfunction correct_bracketing(brackets){\n let stack = [];\n for(let i=0; i\"){\n if(stack.length === 0){\n return false;\n }\n stack.pop();\n }\n }\n return stack.length === 0;\n}\n"], ["//Return true is array elements are monotonically increasing or decreasing.\n// >>> monotonic([1, 2, 4, 20])\n// true\n// >>> monotonic([1, 20, 4, 10])\n// false\n// >>> monotonic([4, 1, 0, -10])\n// true\nfunction monotonic(l){\n let increasing = true;\n let decreasing = true;\n for(let i=0; i l[i+1]){\n increasing = false;\n }\n if(l[i] < l[i+1]){\n decreasing = false;\n }\n }\n return increasing || decreasing;\n}\n"], ["//Return sorted unique common elements for two arrays.\n// >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n// [1, 5, 653]\n// >>> common([5, 3, 2, 8], [3, 2])\n// [2, 3]\nfunction common(l1, l2){\n let set1 = new Set(l1);\n let set2 = new Set(l2);\n let result = [];\n for(let item of set1){\n if(set2.has(item)){\n result.push(item);\n }\n }\n return result.sort((a, b) => a - b);\n}\n"], ["//Return the largest prime factor of n. Assume n > 1 and is not a prime.\n// >>> largest_prime_factor(13195)\n// 29\n// >>> largest_prime_factor(2048)\n// 2\nfunction largest_prime_factor(n){\n let i = 2;\n while (i <= n) {\n if (n % i === 0) {\n n /= i;\n } else {\n i++;\n }\n }\n return i;\n}\n"], ["//Insert a number 'delimeter' between every two consecutive elements of input array `numbers'\n// >>> intersperse([], 4)\n// []\n// >>> intersperse([1, 2, 3], 4)\n// [1, 4, 2, 4, 3]\nfunction intersperse(numbers, delimeter){\n return numbers.reduce((acc, curr, index) => {\n if(index !== 0){\n acc.push(delimeter);\n }\n acc.push(curr);\n return acc;\n }, []);\n}\n"], ["//sum_to_n is a function that sums numbers from 1 to n.\n// >>> sum_to_n(30)\n// 465\n// >>> sum_to_n(100)\n// 5050\n// >>> sum_to_n(5)\n// 15\n// >>> sum_to_n(10)\n// 55\n// >>> sum_to_n(1)\n// 1\nfunction sum_to_n(n){\n return (n * (n + 1)) / 2;\n}\n"], ["//brackets is a string of \"(\" and \")\".\n// return true if every opening bracket has a corresponding closing bracket.\n// >>> correct_bracketing(\"(\")\n// false\n// >>> correct_bracketing(\"()\")\n// true\n// >>> correct_bracketing(\"(()())\")\n// true\n// >>> correct_bracketing(\")(()\")\n// false\nfunction correct_bracketing(brackets){\n let stack = [];\n for(let i = 0; i < brackets.length; i++){\n if(brackets[i] === \"(\"){\n stack.push(\"(\");\n } else if(brackets[i] === \")\"){\n if(stack.length === 0){\n return false;\n } else {\n stack.pop();\n }\n }\n }\n return stack.length === 0;\n}\n"], ["//xs represent coefficients of a polynomial.\n// xs[0] + xs[1] * x + xs[2] * x^2 + ....\n// Return derivative of this polynomial in the same form.\n// >>> derivative([3, 1, 2, 4, 5])\n// [1, 4, 12, 20]\n// >>> derivative([1, 2, 3])\n// [2, 6]\nfunction derivative(xs){\n let result = [];\n for(let i = 1; i < xs.length; i++){\n result.push(i * xs[i]);\n }\n return result;\n}\n"], ["//The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n// fibfib(0) == 0\n// fibfib(1) == 0\n// fibfib(2) == 1\n// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n// Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n// >>> fibfib(1)\n// 0\n// >>> fibfib(5)\n// 4\n// >>> fibfib(8)\n// 24\nfunction fibfib(n){\n if(n === 0 || n === 1){\n return 0;\n }\n if(n === 2){\n return 1;\n }\n let a = 0;\n let b = 0;\n let c = 1;\n for(let i = 3; i <= n; i++){\n let temp = a + b + c;\n a = b;\n b = c;\n c = temp;\n }\n return c;\n}\n"], ["//Write a function vowels_count which takes a string representing\n// a word as input and returns the number of vowels in the string.\n// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n// vowel, but only when it is at the end of the given word.\n// Example:\n// >>> vowels_count(\"abcde\")\n// 2\n// >>> vowels_count(\"ACEDY\")\n// 3\nfunction vowels_count(s){\n let count = 0;\n for(let i = 0; i < s.length; i++){\n if(s[i].match(/[aeiouy]/i)){\n count++;\n }\n }\n return count;\n}\n"], ["//Circular shift the digits of the integer x, shift the digits right by shift\n// and return the result as a string.\n// If shift > number of digits, return digits reversed.\n// >>> circular_shift(12, 1)\n// \"21\"\n// >>> circular_shift(12, 2)\n// \"12\"\nfunction circular_shift(x, shift){\n let digits = x.toString().split('');\n if(shift > digits.length){\n digits.reverse();\n } else {\n for(let i = 0; i < shift; i++){\n digits.unshift(digits.pop());\n }\n }\n return digits.join('');\n}\n"], ["//Task\n// Write a function that takes a string as input and returns the sum of the upper characters only'\n// ASCII codes.\n// Examples:\n// >>> digitSum(\"\")\n// 0\n// >>> digitSum(\"abAB\")\n// 131\n// >>> digitSum(\"abcCd\")\n// 67\n// >>> digitSum(\"helloE\")\n// 69\n// >>> digitSum(\"woArBld\")\n// 131\n// >>> digitSum(\"aAaaaXa\")\n// 153\nfunction digitSum(s){\n let sum = 0;\n for(let i=0; i>> fruit_distribution(\"5 apples and 6 oranges\", 19)\n// 8\n// >>> fruit_distribution(\"0 apples and 1 oranges\", 3)\n// 2\n// >>> fruit_distribution(\"2 apples and 3 oranges\", 100)\n// 95\n// >>> fruit_distribution(\"100 apples and 1 oranges\", 120)\n// 19\nfunction fruit_distribution(s, n){\n let arr = s.split(\" and \");\n let apples = parseInt(arr[0].split(\" \")[0]);\n let oranges = parseInt(arr[1].split(\" \")[0]);\n let mangoes = n - (apples + oranges);\n return mangoes;\n}\n"], ["//\"Given an array representing a branch of a tree that has non-negative integer nodes\n// your task is to pluck one of the nodes and return it.\n// The plucked node should be the node with the smallest even value.\n// If multiple nodes with the same smallest even value are found return the node that has smallest index.\n// The plucked node should be returned in an array, [ smalest_value, its index ],\n// If there are no even values or the given array is empty, return [].\n// Example 1:\n// >>> pluck([4, 2, 3])\n// [2, 1]\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 2:\n// >>> pluck([1, 2, 3])\n// [2, 1]\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 3:\n// >>> pluck([])\n// []\n// Example 4:\n// >>> pluck([5, 0, 3, 0, 4, 2])\n// [0, 1]\n// Explanation: 0 is the smallest value, but there are two zeros,\n// so we will choose the first zero, which has the smallest index.\n// Constraints:\n// * 1 <= nodes.length <= 10000\n// * 0 <= node.value\nfunction pluck(arr){\n let smallestEven = Infinity;\n let smallestIndex = -1;\n for(let i=0; i>> search([4, 1, 2, 2, 3, 1])\n// 2\n// >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4])\n// 3\n// >>> search([5, 5, 4, 4, 4])\n// -1\nfunction search(lst){\n let freq = {};\n for(let i=0; i max && freq[key] >= parseInt(key)){\n max = parseInt(key);\n }\n }\n return max;\n}\n"], ["//Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n// For each of the group, output the deepest level of nesting of parentheses.\n// E.g. (()()) has maximum two levels of nesting while ((())) has three.\n// >>> parse_nested_parens(\"(()()) ((())) () ((())()())\")\n// [2, 3, 1, 3]\nfunction parse_nested_parens(paren_string){\n let groups = paren_string.split(\" \");\n let max_depths = [];\n for(let i=0; i max_depth){\n max_depth = depth;\n }\n }\n else if(groups[i][j] == \")\"){\n depth--;\n }\n }\n max_depths.push(max_depth);\n }\n return max_depths;\n}\n"], ["//Given array of integers, return array in strange order.\n// Strange sorting, is when you start with the minimum value,\n// then maximum of the remaining integers, then minimum and so on.\n// Examples:\n// >>> strange_sort_list([1, 2, 3, 4])\n// [1, 4, 2, 3]\n// >>> strange_sort_list([5, 5, 5, 5])\n// [5, 5, 5, 5]\n// >>> strange_sort_list([])\n// []\nfunction strange_sort_list(lst){\n let sorted = lst.sort((a, b) => a - b);\n let result = [];\n while(sorted.length > 0){\n result.push(sorted.shift());\n if(sorted.length > 0){\n result.push(sorted.pop());\n }\n }\n return result;\n}\n"], ["//Given the lengths of the three sides of a triangle. Return the area of\n// the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n// Otherwise return -1\n// Three sides make a valid triangle when the sum of any two sides is greater \n// than the third side.\n// Example:\n// >>> triangle_area(3, 4, 5)\n// 6.0\n// >>> triangle_area(1, 2, 10)\n// -1\nfunction triangle_area(a, b, c){\n if(a + b > c && b + c > a && c + a > b){\n let s = (a + b + c) / 2;\n let area = Math.sqrt(s * (s - a) * (s - b) * (s - c));\n return area.toFixed(2);\n }\n else{\n return -1;\n }\n}\n"], ["//Write a function that returns true if the object q will fly, and false otherwise.\n// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.\n// Example:\n// >>> will_it_fly([1, 2], 5)\n// false\n// # 1+2 is less than the maximum possible weight, but it's unbalanced.\n// >>> will_it_fly([3, 2, 3], 1)\n// false\n// # it's balanced, but 3+2+3 is more than the maximum possible weight.\n// >>> will_it_fly([3, 2, 3], 9)\n// true\n// # 3+2+3 is less than the maximum possible weight, and it's balanced.\n// >>> will_it_fly([3], 5)\n// true\n// # 3 is less than the maximum possible weight, and it's balanced.\nfunction will_it_fly(q, w){\n let sum = 0;\n for(let i = 0; i < q.length; i++){\n sum += q[i];\n }\n if(sum <= w && isPalindrome(q)){\n return true;\n }\n return false;\n}\n"], ["//Given an array arr of integers, find the minimum number of elements that\n// need to be changed to make the array palindromic. A palindromic array is an array that\n// is read the same backwards and forwards. In one change, you can change one element to any other element.\n// For example:\n// >>> smallest_change([1, 2, 3, 5, 4, 7, 9, 6])\n// 4\n// >>> smallest_change([1, 2, 3, 4, 3, 2, 2])\n// 1\n// >>> smallest_change([1, 2, 3, 2, 1])\n// 0\nfunction smallest_change(arr){\n let count = 0;\n let start = 0;\n let end = arr.length - 1;\n while(start < end){\n if(arr[start] !== arr[end]){\n count++;\n }\n start++;\n end--;\n }\n return count;\n}\n"], ["//Write a function that accepts two arrays of strings and returns the array that has \n// total number of chars in the all strings of the array less than the other array.\n// if the two arrays have the same number of chars, return the first array.\n// Examples\n// >>> total_match([], [])\n// []\n// >>> total_match([\"hi\", \"admin\"], [\"hI\", \"Hi\"])\n// [\"hI\", \"Hi\"]\n// >>> total_match([\"hi\", \"admin\"], [\"hi\", \"hi\", \"admin\", \"project\"])\n// [\"hi\", \"admin\"]\n// >>> total_match([\"hi\", \"admin\"], [\"hI\", \"hi\", \"hi\"])\n// [\"hI\", \"hi\", \"hi\"]\n// >>> total_match([\"4\"], [\"1\", \"2\", \"3\", \"4\", \"5\"])\n// [\"4\"]\nfunction total_match(lst1, lst2){\n let total1 = 0;\n let total2 = 0;\n for(let i=0; i total2){\n return lst2;\n }\n else{\n return lst1;\n }\n}\n"], ["//Write a function that returns true if the given number is the multiplication of 3 prime numbers\n// and false otherwise.\n// Knowing that (a) is less then 100. \n// Example:\n// >>> is_multiply_prime(30)\n// true\n// 30 = 2 * 3 * 5\nfunction is_multiply_prime(a){\n let 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];\n let count = 0;\n for(let i = 0; i < primes.length; i++){\n if(a % primes[i] === 0){\n count++;\n a /= primes[i];\n i--;\n }\n }\n return count === 3;\n}\n"], ["//Your task is to write a function that returns true if a number x is a simple\n// power of n and false in other cases.\n// x is a simple power of n if n**int=x\n// For example:\n// >>> is_simple_power(1, 4)\n// true\n// >>> is_simple_power(2, 2)\n// true\n// >>> is_simple_power(8, 2)\n// true\n// >>> is_simple_power(3, 2)\n// false\n// >>> is_simple_power(3, 1)\n// false\n// >>> is_simple_power(5, 3)\n// false\nfunction is_simple_power(x, n){\n if(x === 1 && n !== 1){\n return true;\n }\n let power = 1;\n while(power < x){\n power *= n;\n }\n return power === x;\n}\n"], ["//Write a function that takes an integer a and returns true \n// if this ingeger is a cube of some integer number.\n// Note: you may assume the input is always valid.\n// Examples:\n// >>> iscube(1)\n// true\n// >>> iscube(2)\n// false\n// >>> iscube(-1)\n// true\n// >>> iscube(64)\n// true\n// >>> iscube(0)\n// true\n// >>> iscube(180)\n// false\nfunction iscube(a){\n return Number.isInteger(Math.pow(a, 1/3));\n}\n"], ["//You have been tasked to write a function that receives \n// a hexadecimal number as a string and counts the number of hexadecimal \n// digits that are primes (prime number, or a prime, is a natural number \n// greater than 1 that is not a product of two smaller natural numbers).\n// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n// So you have to determine a number of the following digits: 2, 3, 5, 7, \n// B (=decimal 11), D (=decimal 13).\n// Note: you may assume the input is always correct or empty string, \n// and symbols A,B,C,D,E,F are always uppercase.\n// Examples:\n// >>> hex_key(\"AB\")\n// 1\n// >>> hex_key(\"1077E\")\n// 2\n// >>> hex_key(\"ABED1A33\")\n// 4\n// >>> hex_key(\"123456789ABCDEF0\")\n// 6\n// >>> hex_key(\"2020\")\n// 2\nfunction hex_key(num){\n let count = 0;\n const primes = ['2', '3', '5', '7', 'B', 'D'];\n for(let i = 0; i < num.length; i++){\n if(primes.includes(num[i])){\n count++;\n }\n }\n return count;\n}\n"], ["//You will be given a number in decimal form and your task is to convert it to\n// binary format. The function should return a string, with each character representing a binary\n// number. Each character in the string will be '0' or '1'.\n// There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n// The extra characters are there to help with the format.\n// Examples:\n// >>> decimal_to_binary(15)\n// \"db1111db\"\n// >>> decimal_to_binary(32)\n// \"db100000db\"\nfunction decimal_to_binary(decimal){\n let binary = \"db\" + (decimal >>> 0).toString(2) + \"db\";\n return binary;\n}\n"], ["//Filter an input array of strings only for ones that contain given substring\n// >>> filter_by_substring([], \"a\")\n// []\n// >>> filter_by_substring([\"abc\", \"bacd\", \"cde\", \"array\"], \"a\")\n// [\"abc\", \"bacd\", \"array\"]\nfunction filter_by_substring(strings, substring){\n return strings.filter(function(string){\n return string.includes(substring);\n });\n}\n"], ["//You are given a string s.\n// Your task is to check if the string is hapjs or not.\n// A string is hapjs if its length is at least 3 and every 3 consecutive letters are distinct\n// For example:\n// >>> is_happy(\"a\")\n// false\n// >>> is_happy(\"aa\")\n// false\n// >>> is_happy(\"abcd\")\n// true\n// >>> is_happy(\"aabb\")\n// false\n// >>> is_happy(\"adb\")\n// true\n// >>> is_happy(\"xyy\")\n// false\nfunction is_happy(s){\n if(s.length < 3){\n return false;\n }\n for(let i=0; i 3.7 A \n// > 3.3 A- \n// > 3.0 B+\n// > 2.7 B \n// > 2.3 B-\n// > 2.0 C+\n// > 1.7 C\n// > 1.3 C-\n// > 1.0 D+ \n// > 0.7 D \n// > 0.0 D-\n// 0.0 E\n// Example:\n// >>> grade_equation([4.0, 3, 1.7, 2, 3.5])\n// [\"A+\", \"B\", \"C-\", \"C\", \"A-\"]\nfunction numerical_letter_grade(grades){\n let letter_grades = [];\n for(let i = 0; i < grades.length; i++){\n if(grades[i] == 4.0){\n letter_grades.push(\"A+\");\n }\n else if(grades[i] > 3.7){\n letter_grades.push(\"A\");\n }\n else if(grades[i] > 3.3){\n letter_grades.push(\"A-\");\n }\n else if(grades[i] > 3.0){\n letter_grades.push(\"B+\");\n }\n else if(grades[i] > 2.7){\n letter_grades.push(\"B\");\n }\n else if(grades[i] > 2.3){\n letter_grades.push(\"B-\");\n }\n else if(grades[i] > 2.0){\n letter_grades.push(\"C+\");\n }\n else if(grades[i] > 1.7){\n letter_grades.push(\"C\");\n }\n else if(grades[i] > 1.3){\n letter_grades.push(\"C-\");\n }\n else if(grades[i] > 1.0){\n letter_grades.push(\"D+\");\n }\n else if(grades[i] > 0.7){\n letter_grades.push(\"D\");\n }\n else if(grades[i] > 0.0){\n letter_grades.push(\"D-\");\n }\n else{\n letter_grades.push(\"E\");\n }\n }\n return letter_grades;\n}\n"], ["//Write a function that takes a string and returns true if the string\n// length is a prime number or false otherwise\n// Examples\n// >>> prime_length(\"Hello\")\n// true\n// >>> prime_length(\"abcdcba\")\n// true\n// >>> prime_length(\"kittens\")\n// true\n// >>> prime_length(\"orange\")\n// false\nfunction prime_length(string){\n let length = string.length;\n if(length < 2){\n return false;\n }\n for(let i = 2; i < length; i++){\n if(length % i === 0){\n return false;\n }\n }\n return true;\n}\n"], ["//Given a positive integer n, return the count of the numbers of n-digit\n// positive integers that start or end with 1.\nfunction starts_one_ends(n){\n let count = 0;\n for(let i=1; i<=n; i++){\n if(i===1){\n count++;\n }\n else{\n count += Math.pow(2, i-2);\n }\n }\n return count;\n}\n"], ["//Given a positive integer N, return the total sum of its digits in binary.\n// Example\n// >>> solve(1000)\n// \"1\"\n// >>> solve(150)\n// \"110\"\n// >>> solve(147)\n// \"1100\"\n// Variables:\n// @N integer\n// Constraints: 0 \u2264 N \u2264 10000.\n// Output:\n// a string of binary number\nfunction solve(N){\n let sum = 0;\n while(N > 0){\n sum += N % 10;\n N = Math.floor(N / 10);\n }\n return sum.toString(2);\n}\n"], ["//Given a non-empty array of integers lst. add the even elements that are at odd indices..\n// Examples:\n// >>> add([4, 2, 6, 7])\n// 2\nfunction add(lst){\n let sum = 0;\n for(let i=1; i>> anti_shuffle(\"Hi\")\n// \"Hi\"\n// >>> anti_shuffle(\"hello\")\n// \"ehllo\"\n// >>> anti_shuffle(\"Hello World!!!\")\n// \"Hello !!!Wdlor\"\nfunction anti_shuffle(s){\n let words = s.split(\" \");\n let result = \"\";\n for(let i=0; i>> get_row([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1)\n// [[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]]\n// >>> get_row([], 1)\n// []\n// >>> get_row([[], [1], [1, 2, 3]], 3)\n// [[2, 2]]\nfunction get_row(lst, x){\n let result = [];\n for(let i = 0; i < lst.length; i++){\n for(let j = 0; j < lst[i].length; j++){\n if(lst[i][j] === x){\n result.push([i, j]);\n }\n }\n }\n result.sort((a, b) => {\n if(a[0] === b[0]){\n return b[1] - a[1];\n }\n return a[0] - b[0];\n });\n return result;\n}\n"], ["//Given an array of non-negative integers, return a cojs of the given array after sorting,\n// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n// or sort it in descending order if the sum( first index value, last index value) is even.\n// Note:\n// * don't change the given array.\n// Examples:\n// >>> sort_array([])\n// []\n// >>> sort_array([5])\n// [5]\n// >>> sort_array([2, 4, 3, 0, 1, 5])\n// [0, 1, 2, 3, 4, 5]\n// >>> sort_array([2, 4, 3, 0, 1, 5, 6])\n// [6, 5, 4, 3, 2, 1, 0]\nfunction sort_array(array){\n let sum = array[0] + array[array.length - 1];\n let sortedArray = [...array];\n if(sum % 2 === 0){\n sortedArray.sort((a, b) => b - a);\n } else {\n sortedArray.sort((a, b) => a - b);\n }\n return sortedArray;\n}\n"], ["//Create a function encrypt that takes a string as an argument and\n// returns a string encrypted with the alphabet being rotated. \n// The alphabet should be rotated in a manner such that the letters \n// shift down by two multiplied to two places.\n// For example:\n// >>> encrypt(\"hi\")\n// \"lm\"\n// >>> encrypt(\"asdfghjkl\")\n// \"ewhjklnop\"\n// >>> encrypt(\"gf\")\n// \"kj\"\n// >>> encrypt(\"et\")\n// \"ix\"\nfunction encrypt(s){\n let encrypted = \"\";\n for(let i=0; i= 97 && charCode <= 122){\n charCode = ((charCode - 97 + 2*2) % 26) + 97;\n }\n encrypted += String.fromCharCode(charCode);\n }\n return encrypted;\n}\n"], ["//For a given array of integers, return an array consisting of a sum and a product of all the integers in an array.\n// Empty sum should be equal to 0 and empty product should be equal to 1.\n// >>> sum_product([])\n// [0, 1]\n// >>> sum_product([1, 2, 3, 4])\n// [10, 24]\nfunction sum_product(numbers){\n let sum = 0;\n let product = 1;\n for(let i = 0; i < numbers.length; i++){\n sum += numbers[i];\n product *= numbers[i];\n }\n return [sum, product];\n}\n"], ["//You are given an array of integers.\n// Write a function next_smallest() that returns the 2nd smallest element of the array.\n// Return undefined if there is no such element.\n// >>> next_smallest([1, 2, 3, 4, 5])\n// 2\n// >>> next_smallest([5, 1, 4, 3, 2])\n// 2\n// >>> next_smallest([])\n// undefined\n// >>> next_smallest([1, 1])\n// undefined\nfunction next_smallest(lst){\n let smallest = lst[0];\n let second_smallest = Infinity;\n for(let i=1; i>> is_bored(\"Hello world\")\n// 0\n// >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n// 1\nfunction is_bored(S){\n let count = 0;\n let sentences = S.split(/[.!?]/);\n for(let i=0; i>> any_int(5, 2, 7)\n// true\n// >>> any_int(3, 2, 2)\n// false\n// >>> any_int(3, -2, 1)\n// true\n// >>> any_int(3.6, -2.2, 2)\n// false\nfunction any_int(x, y, z){\n //Check if all numbers are integers\n if(Number.isInteger(x) && Number.isInteger(y) && Number.isInteger(z)){\n //Check if one of the numbers is equal to the sum of the other two\n if(x === y + z || y === x + z || z === x + y){\n return true;\n }\n }\n return false;\n}\n"], ["//Write a function that takes a message, and encodes in such a \n// way that it swaps case of all letters, replaces all vowels in \n// the message with the letter that appears 2 places ahead of that \n// vowel in the english alphabet. \n// Assume only letters. \n// Examples:\n// >>> encode(\"test\")\n// \"TGST\"\n// >>> encode(\"This is a message\")\n// \"tHKS KS C MGSSCGG\"\nfunction encode(message){\n let encodedMessage = \"\";\n for(let i = 0; i < message.length; i++){\n let char = message[i];\n if(char.match(/[a-zA-Z]/)){\n if(char === char.toUpperCase()){\n char = char.toLowerCase();\n } else {\n char = char.toUpperCase();\n }\n if(char.match(/[aeiou]/)){\n let vowelIndex = \"aeiou\".indexOf(char);\n let nextVowelIndex = (vowelIndex + 2) % 5;\n char = \"aeiou\".charAt(nextVowelIndex);\n }\n }\n encodedMessage += char;\n }\n return encodedMessage;\n}\n"], ["//You are given an array of integers.\n// You need to find the largest prime value and return the sum of its digits.\n// Examples:\n// >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3])\n// 10\n// >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1])\n// 25\n// >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3])\n// 13\n// >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6])\n// 11\n// >>> skjkasdkd([0, 81, 12, 3, 1, 21])\n// 3\n// >>> skjkasdkd([0, 8, 1, 2, 1, 7])\n// 7\nfunction skjkasdkd(lst){\n let maxPrime = 0;\n for(let i = 0; i < lst.length; i++){\n if(isPrime(lst[i]) && lst[i] > maxPrime){\n maxPrime = lst[i];\n }\n }\n let sum = 0;\n while(maxPrime > 0){\n sum += maxPrime % 10;\n maxPrime = Math.floor(maxPrime / 10);\n }\n return sum;\n}\n"], ["//Given an object, return true if all keys are strings in lower \n// case or all keys are strings in upper case, else return false.\n// The function should return false is the given object is empty.\n// Examples:\n// >>> check_dict_case({\"a\": \"apple\", \"b\": \"banana\"})\n// true\n// >>> check_dict_case({\"a\": \"apple\", \"A\": \"banana\", \"B\": \"banana\"})\n// false\n// >>> check_dict_case({\"a\": \"apple\", 8: \"banana\", \"a\": \"apple\"})\n// false\n// >>> check_dict_case({\"Name\": \"John\", \"Age\": \"36\", \"City\": \"Houston\"})\n// false\n// >>> check_dict_case({\"STATE\": \"NC\", \"ZIP\": \"12345\"})\n// true\nfunction check_dict_case(dict){\n if(Object.keys(dict).length === 0){\n return false;\n }\n let all_lower = true;\n let all_upper = true;\n for(let key in dict){\n if(typeof key !== 'string'){\n return false;\n }\n if(key !== key.toLowerCase()){\n all_lower = false;\n }\n if(key !== key.toUpperCase()){\n all_upper = false;\n }\n }\n return all_lower || all_upper;\n}\n"], ["//Implement a function that takes an non-negative integer and returns an array of the first n\n// integers that are prime numbers and less than n.\n// for example:\n// >>> count_up_to(5)\n// [2, 3]\n// >>> count_up_to(11)\n// [2, 3, 5, 7]\n// >>> count_up_to(0)\n// []\n// >>> count_up_to(20)\n// [2, 3, 5, 7, 11, 13, 17, 19]\n// >>> count_up_to(1)\n// []\n// >>> count_up_to(18)\n// [2, 3, 5, 7, 11, 13, 17]\nfunction count_up_to(n){\n let primes = [];\n for(let i = 2; i < n; i++){\n let isPrime = true;\n for(let j = 2; j < i; j++){\n if(i % j === 0){\n isPrime = false;\n break;\n }\n }\n if(isPrime){\n primes.push(i);\n }\n }\n return primes;\n}\n"], ["//Complete the function that takes two integers and returns \n// the product of their unit digits.\n// Assume the input is always valid.\n// Examples:\n// >>> multiply(148, 412)\n// 16\n// >>> multiply(19, 28)\n// 72\n// >>> multiply(2020, 1851)\n// 0\n// >>> multiply(14, -15)\n// 20\nfunction multiply(a, b){\n let unitDigitA = Math.abs(a) % 10;\n let unitDigitB = Math.abs(b) % 10;\n return unitDigitA * unitDigitB;\n}\n"], ["//Given a string s, count the number of uppercase vowels in even indices.\n// For example:\n// >>> count_upper(\"aBCdEf\")\n// 1\n// >>> count_upper(\"abcdefg\")\n// 0\n// >>> count_upper(\"dBBE\")\n// 0\nfunction count_upper(s){\n let count = 0;\n for(let i = 0; i < s.length; i+=2){\n if(i % 2 === 0 && 'AEIOU'.includes(s[i].toUpperCase())){\n count++;\n }\n }\n return count;\n}\n"], ["//Create a function that takes a value (string) representing a number\n// and returns the closest integer to it. If the number is equidistant\n// from two integers, round it away from zero.\n// Examples\n// >>> closest_integer(\"10\")\n// 10\n// >>> closest_integer(\"15.3\")\n// 15\n// Note:\n// Rounding away from zero means that if the given number is equidistant\n// from two integers, the one you should return is the one that is the\n// farthest from zero. For example closest_integer(\"14.5\") should\n// return 15 and closest_integer(\"-14.5\") should return -15.\nfunction closest_integer(value){\n //Convert the string to a number\n var num = parseFloat(value);\n \n //Round the number to the nearest integer\n var rounded = Math.round(num);\n \n //If the number is equidistant from two integers, round it away from zero\n if(Math.abs(rounded - num) === 0.5){\n if(num > 0){\n rounded = Math.ceil(num);\n } else {\n rounded = Math.floor(num);\n }\n }\n \n //Return the closest integer\n return rounded;\n}\n"], ["//From a given array of integers, generate an array of rolling maximum element found until given moment\n// in the sequence.\n// >>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n// [1, 2, 3, 3, 3, 4, 4]\nfunction rolling_max(numbers){\n let max = numbers[0];\n let result = [];\n for(let i = 0; i < numbers.length; i++){\n if(numbers[i] > max){\n max = numbers[i];\n }\n result.push(max);\n }\n return result;\n}\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-lua_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-lua_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..384bbc64d3cfb7940596b6b9441db0b3b925eb2e --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-lua_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["-- Check if in given table of numbers, are any two numbers closer to each other than\n-- given threshold.\n-- >>> has_close_elements({1.0, 2.0, 3.0}, 0.5)\n-- false\n-- >>> has_close_elements({1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3)\n-- true\nlocal function has_close_elements(numbers, threshold)\n for i = 1, #numbers do\n for j = i + 1, #numbers do\n if math.abs(numbers[i] - numbers[j]) <= threshold then\n return true\n end\n end\n end\n return false\nend"], ["-- Given a positive integer n, you have to make a pile of n levels of stones.\n-- The first level has n stones.\n-- The number of stones in the next level is:\n-- - the next odd number if n is odd.\n-- - the next even number if n is even.\n-- Return the number of stones in each level in a table, where element at index\n-- i represents the number of stones in the level (i+1).\n-- Examples:\n-- >>> make_a_pile(3)\n-- {3, 5, 7}\nlocal function make_a_pile(n)\n local stones = {}\n local next_num = n % 2 == 0 and n + 1 or n + 2\n for i = 1, n do\n table.insert(stones, next_num)\n next_num = next_num + 2\n end\n return stones\nend\n"], ["-- You will be given a string of words separated by commas or spaces. Your task is\n-- to split the string into words and return a table of the words.\n-- For example:\n-- >>> words_string('Hi, my name is John')\n-- {'Hi', 'my', 'name', 'is', 'John'}\n-- >>> words_string('One, two, three, four, five, six')\n-- {'One', 'two', 'three', 'four', 'five', 'six'}\nlocal function words_string(s)\n local words = {}\n for word in s:gmatch(\"%S+\") do\n table.insert(words, word)\n end\n return words\nend\n"], ["-- This function takes two positive numbers x and y and returns the\n-- biggest even integer number that is in the range [x, y] inclusive. If \n-- there's no such number, then the function should return -1.\n-- For example:\n-- >>> choose_num(12, 15)\n-- 14\n-- >>> choose_num(13, 12)\n-- -1\nlocal function choose_num(x, y)\n local num = y\n while num >= x do\n if num % 2 == 0 then\n return num\n end\n num = num - 1\n end\n return -1\nend"], ["-- You are given two positive integers n and m, and your task is to compute the\n-- average of the integers from n through m (including n and m). \n-- Round the answer to the nearest integer and convert that to binary.\n-- If n is greater than m, return -1.\n-- Example:\n-- >>> rounded_avg(1, 5)\n-- '0b11'\n-- >>> rounded_avg(7, 5)\n-- -1\n-- >>> rounded_avg(10, 20)\n-- '0b1111'\n-- >>> rounded_avg(20, 33)\n-- '0b11010'\nlocal function rounded_avg(n, m)\n if n > m then\n return -1\n end\n local sum = 0\n for i = n, m do\n sum = sum + i\n end\n local avg = math.floor((sum / (m - n + 1)) + 0.5)\n return string.format(\"0b%b\", avg)\nend\n"], ["-- Given a table of positive integers x. return a sorted table of all \n-- elements that hasn't any even digit.\n-- Note: Returned table should be sorted in increasing order.\n-- For example:\n-- >>> unique_digits({15, 33, 1422, 1})\n-- {1, 15, 33}\n-- >>> unique_digits({152, 323, 1422, 10})\n-- {}\nlocal function unique_digits(x)\n local result = {}\n for _, num in ipairs(x) do\n local has_even_digit = false\n for digit in string.gmatch(tostring(num), \"%d\") do\n if tonumber(digit) % 2 == 0 then\n has_even_digit = true\n break\n end\n end\n if not has_even_digit then\n table.insert(result, num)\n end\n end\n table.sort(result)\n return result\nend"], ["-- Given a table of integers, sort the integers that are between 1 and 9 inclusive,\n-- reverse the resulting table, and then replace each digit by its corresponding name from\n-- \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n-- For example:\n-- >>> by_length({2, 1, 1, 4, 5, 8, 2, 3})\n-- {'Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One'}\n-- If the table is empty, return an empty table:\n-- >>> by_length({})\n-- {}\n-- If the table has any strange number ignore it:\n-- >>> by_length({1, -1, 55})\n-- {'One'}\nlocal function by_length(arr)\n local names = {\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"}\n local filtered = {}\n for i, v in ipairs(arr) do\n if v >= 1 and v <= 9 then\n table.insert(filtered, v)\n end\n end\n table.sort(filtered)\n local reversed = {}\n for i = #filtered, 1, -1 do\n table.insert(reversed, names[filtered[i]])\n end\n return reversed\nend\n"], ["-- Implement the function f that takes n as a parameter,\n-- and returns a table of size n, such that the value of the element at index i is the factorial of i if i is even\n-- or the sum of numbers from 1 to i otherwise.\n-- i starts from 1.\n-- the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n-- Example:\n-- >>> f(5)\n-- {1, 2, 6, 24, 15}\nlocal function f(n)\n local t = {}\n for i = 1, n do\n if i % 2 == 0 then\n local fact = 1\n for j = 1, i do\n fact = fact * j\n end\n t[i] = fact\n else\n local sum = 0\n for j = 1, i do\n sum = sum + j\n end\n t[i] = sum\n end\n end\n return t\nend"], ["-- Given a positive integer n, return a table that has the number of even and odd\n-- integer palindromes that fall within the range(1, n), inclusive.\n-- Example 1:\n-- >>> even_odd_palindrome(3)\n-- {1, 2}\n-- Explanation:\n-- Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n-- Example 2:\n-- >>> even_odd_palindrome(12)\n-- {4, 6}\n-- Explanation:\n-- Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n-- Note:\n-- 1. 1 <= n <= 10^3\n-- 2. returned table has the number of even and odd integer palindromes respectively.\nlocal function even_odd_palindrome(n)\n local even_count = 0\n local odd_count = 0\n for i = 1, n do\n local str = tostring(i)\n if str == string.reverse(str) then\n if i % 2 == 0 then\n even_count = even_count + 1\n else\n odd_count = odd_count + 1\n end\n end\n end\n return {even_count, odd_count}\nend\n"], ["-- Write a function count_nums which takes a table of integers and returns\n-- the number of elements which has a sum of digits > 0.\n-- If a number is negative, then its first signed digit will be negative:\n-- e.g. -123 has signed digits -1, 2, and 3.\n-- >>> count_nums({})\n-- 0\n-- >>> count_nums({-1, 11, -11})\n-- 1\n-- >>> count_nums({1, 1, 2})\n-- 3\nlocal function count_nums(arr)\n local count = 0\n for _, num in ipairs(arr) do\n local sum = 0\n local num_str = tostring(num)\n for _, digit in ipairs(num_str:gmatch(\".\")) do\n sum = sum + tonumber(digit)\n end\n if sum > 0 then\n count = count + 1\n end\n end\n return count\nend"], ["-- We have a table 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n-- numbers in the table will be randomly ordered. Your task is to determine if\n-- it is possible to get a table sorted in non-decreasing order by performing \n-- the following operation on the given table:\n-- You are allowed to perform right shift operation any number of times.\n-- One right shift operation means shifting all elements of the table by one\n-- position in the right direction. The last element of the table will be moved to\n-- the starting position in the table i.e. 0th index. \n-- If it is possible to obtain the sorted table by performing the above operation\n-- then return true else return false.\n-- If the given table is empty then return true.\n-- Note: The given table is guaranteed to have unique elements.\n-- For Example:\n-- >>> move_one_ball({3, 4, 5, 1, 2})\n-- true\n-- Explanation: By performin 2 right shift operations, non-decreasing order can\n-- be achieved for the given table.\n-- >>> move_one_ball({3, 5, 4, 1, 2})\n-- false\n-- Explanation:It is not possible to get non-decreasing order for the given\n-- table by performing any number of right shift operations.\nlocal function move_one_ball(arr)\n local n = #arr\n if n == 0 then\n return true\n end\n local sorted = true\n for i = 1, n do\n if arr[i] > arr[(i % n) + 1] then\n sorted = false\n break\n end\n end\n return sorted\nend\n"], ["-- Find the shortest palindrome that begins with a supplied string.\n-- Algorithm idea is simple:\n-- - Find the longest postfix of supplied string that is a palindrome.\n-- - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n-- >>> make_palindrome('')\n-- ''\n-- >>> make_palindrome('cat')\n-- 'catac'\n-- >>> make_palindrome('cata')\n-- 'catac'\nlocal function make_palindrome(string)\n local reversed = string:reverse()\n local length = string.len(string)\n for i = 1, length do\n if string:sub(i) == reversed:sub(1, length - i + 1) then\n return string .. reversed:sub(length - i + 2)\n end\n end\n return string .. reversed\nend"], ["-- In this problem, you will implement a function that takes two tables of numbers,\n-- and determines whether it is possible to perform an exchange of elements\n-- between them to make lst1 a table of only even numbers.\n-- There is no limit on the number of exchanged elements between lst1 and lst2.\n-- If it is possible to exchange elements between the lst1 and lst2 to make\n-- all the elements of lst1 to be even, return \"YES\".\n-- Otherwise, return \"NO\".\n-- For example:\n-- >>> exchange({1, 2, 3, 4}, {1, 2, 3, 4})\n-- 'YES'\n-- >>> exchange({1, 2, 3, 4}, {1, 5, 3, 4})\n-- 'NO'\n-- It is assumed that the input tables will be non-empty.\nlocal function exchange(lst1, lst2)\n local even_count = 0\n local odd_count = 0\n for _, num in ipairs(lst1) do\n if num % 2 == 0 then\n even_count = even_count + 1\n else\n odd_count = odd_count + 1\n end\n end\n for _, num in ipairs(lst2) do\n if num % 2 == 0 then\n even_count = even_count + 1\n else\n odd_count = odd_count + 1\n end\n end\n if odd_count > even_count then\n return \"NO\"\n else\n return \"YES\"\n end\nend\n"], ["-- Given a string representing a space separated lowercase letters, return a table\n-- of the letter with the most repetition and containing the corresponding count.\n-- If several letters have the same occurrence, return all of them.\n-- Example:\n-- >>> histogram('a b c')\n-- {['a'] = 1, ['b'] = 1, ['c'] = 1}\n-- >>> histogram('a b b a')\n-- {['a'] = 2, ['b'] = 2}\n-- >>> histogram('a b c a b')\n-- {['a'] = 2, ['b'] = 2}\n-- >>> histogram('b b b b a')\n-- {['b'] = 4}\n-- >>> histogram('')\n-- {}\nlocal function histogram(test)\n local letters = {}\n local max_count = 0\n local result = {}"], ["-- Task\n-- We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n-- then check if the result string is palindrome.\n-- A string is called palindrome if it reads the same backward as forward.\n-- You should return a table containing the result string and true/false for the check.\n-- Example\n-- >>> reverse_delete('abcde', 'ae')\n-- {'bcd', false}\n-- >>> reverse_delete('abcdef', 'b')\n-- {'acdef', false}\n-- >>> reverse_delete('abcdedcba', 'ab')\n-- {'cdedc', true}\nlocal function reverse_delete(s, c)\n local result = ''\n for i = 1, #s do\n local char = s:sub(i, i)\n if not c:find(char) then\n result = result .. char\n end\n end\n local is_palindrome = result == result:reverse()\n return {result, is_palindrome}\nend\n"], ["-- Given a table of strings, where each string consists of only digits, return a table.\n-- Each element i of the output should be \"the number of odd elements in the\n-- string i of the input.\" where all the i's should be replaced by the number\n-- of odd digits in the i'th string of the input.\n-- >>> odd_count({'1234567'})\n-- {'the number of odd elements 4n the str4ng 4 of the 4nput.'}\n-- >>> odd_count({'3', '11111111'})\n-- {'the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.'}\nlocal function odd_count(lst)\n local result = {}\n for i, str in ipairs(lst) do\n local count = 0\n for j = 1, #str do\n if tonumber(str:sub(j, j)) % 2 == 1 then\n count = count + 1\n end\n end\n table.insert(result, 'the number of odd elements ' .. count .. 'n the str' .. count .. 'ng ' .. count .. ' of the ' .. count .. 'nput.')\n end\n return result\nend"], ["-- Given a table of integers nums, find the minimum sum of any non-empty sub-table\n-- of nums.\n-- Example\n-- >>> minSubArraySum({2, 3, 4, 1, 2, 4})\n-- 1\n-- >>> minSubArraySum({-1, -2, -3})\n-- -6\nlocal function minSubArraySum(nums)\n local minSum = nums[1]\n local currSum = 0\n for i = 1, #nums do\n currSum = math.min(currSum + nums[i], nums[i])\n minSum = math.min(minSum, currSum)\n end\n return minSum\nend"], ["-- You are given a rectangular grid of wells. Each row represents a single well,\n-- and each 1 in a row represents a single unit of water.\n-- Each well has a corresponding bucket that can be used to extract water from it, \n-- and all buckets have the same capacity.\n-- Your task is to use the buckets to empty the wells.\n-- Output the number of times you need to lower the buckets.\n-- Example 1:\n-- >>> max_fill({{0, 0, 1, 0}, {0, 1, 0, 0}, {1, 1, 1, 1}}, 1)\n-- 6\n-- Example 2:\n-- >>> max_fill({{0, 0, 1, 1}, {0, 0, 0, 0}, {1, 1, 1, 1}, {0, 1, 1, 1}}, 2)\n-- 5\n-- Example 3:\n-- >>> max_fill({{0, 0, 0}, {0, 0, 0}}, 5)\n-- 0\n-- Constraints:\n-- * all wells have the same length\n-- * 1 <= grid.length <= 10^2\n-- * 1 <= grid[:,1].length <= 10^2\n-- * grid[i][j] -> 0 | 1\n-- * 1 <= capacity <= 10\nlocal function max_fill(grid, capacity)\n local num_rows = #grid\n local num_cols = #grid[1]\n local num_buckets = 0\n local num_wells = 0\n local num_empty_wells = 0\n local num_full_buckets = 0\n local num_empty_buckets = 0\n local num_wells_per_bucket = capacity\n local num_buckets_needed = 0"], ["-- In this Kata, you have to sort a table of non-negative integers according to\n-- number of ones in their binary representation in ascending order.\n-- For similar number of ones, sort based on decimal value.\n-- It must be implemented like this:\n-- >>> sort_array({1, 5, 2, 3, 4})\n-- {1, 2, 3, 4, 5}\n-- >>> sort_array({-2, -3, -4, -5, -6})\n-- {-6, -5, -4, -3, -2}\n-- >>> sort_array({1, 0, 2, 3, 4})\n-- {0, 1, 2, 3, 4}\nlocal function sort_array(arr)\n table.sort(arr, function(a, b)\n local a_ones = string.gsub(string.format(\"%b\", a), \"0\", \"\")\n local b_ones = string.gsub(string.format(\"%b\", b), \"0\", \"\")\n if #a_ones == #b_ones then\n return a < b\n else\n return #a_ones < #b_ones\n end\n end)\n return arr\nend\n"], ["-- Given a string s and a natural number n, you have been tasked to implement \n-- a function that returns a table of all words from string s that contain exactly \n-- n consonants, in order these words appear in the string s.\n-- If the string s is empty then the function should return an empty table.\n-- Note: you may assume the input string contains only letters and spaces.\n-- Examples:\n-- >>> select_words('Mary had a little lamb', 4)\n-- {'little'}\n-- >>> select_words('Mary had a little lamb', 3)\n-- {'Mary', 'lamb'}\n-- >>> select_words('simple white space', 2)\n-- {}\n-- >>> select_words('Hello world', 4)\n-- {'world'}\n-- >>> select_words('Uncle sam', 3)\n-- {'Uncle'}\nlocal function select_words(s, n)\n local words = {}\n local consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'\n for word in s:gmatch('%S+') do\n local count = 0\n for i = 1, #word do\n if consonants:find(word:sub(i, i)) then\n count = count + 1\n end\n end\n if count == n then\n table.insert(words, word)\n end\n end\n return words\nend\n"], ["-- You are given a word. Your task is to find the closest vowel that stands between \n-- two consonants from the right side of the word (case sensitive).\n-- Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n-- find any vowel met the above condition. \n-- You may assume that the given string contains English letter only.\n-- Example:\n-- >>> get_closest_vowel('yogurt')\n-- 'u'\n-- >>> get_closest_vowel('FULL')\n-- 'U'\n-- >>> get_closest_vowel('quick')\n-- ''\n-- >>> get_closest_vowel('ab')\n-- ''\nlocal function get_closest_vowel(word)\n local vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n local consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'}\n local closest_vowel = ''\n local distance = #word\n for i = #word, 3, -1 do\n local char = word:sub(i, i)\n if table.contains(consonants, word:sub(i-1, i-1)) and table.contains(consonants, word:sub(i-2, i-2)) then\n for j = i-1, 1, -1 do\n local char2 = word:sub(j, j)\n if table.contains(vowels, char2) then\n local new_distance = i - j\n if new_distance < distance then\n distance = new_distance\n closest_vowel = char2\n end\n break\n end\n end\n end\n end\n return closest_vowel\nend\n"], ["-- You are given a table of two strings, both strings consist of open\n-- parentheses '(' or close parentheses ')' only.\n-- Your job is to check if it is possible to concatenate the two strings in\n-- some order, that the resulting string will be good.\n-- A string S is considered to be good if and only if all parentheses in S\n-- are balanced. For example: the string '(())()' is good, while the string\n-- '())' is not.\n-- Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n-- Examples:\n-- >>> match_parens({'()(', ')'})\n-- 'Yes'\n-- >>> match_parens({')', ')'})\n-- 'No'\nlocal function match_parens(lst)\n local s = lst[1] .. lst[2]\n local stack = {}\n for i = 1, #s do\n local c = s:sub(i, i)\n if c == '(' then\n table.insert(stack, c)\n else\n if #stack == 0 then\n return 'No'\n end\n table.remove(stack)\n end\n end\n if #stack == 0 then\n return 'Yes'\n else\n return 'No'\n end\nend\n"], ["-- Input are two strings a and b consisting only of 1s and 0s.\n-- Perform binary XOR on these inputs and return result also as a string.\n-- >>> string_xor('010', '110')\n-- '100'\nlocal function string_xor(a, b)\n local result = ''\n for i = 1, #a do\n if a:sub(i, i) == b:sub(i, i) then\n result = result .. '0'\n else\n result = result .. '1'\n end\n end\n return result\nend"], ["-- Given a table arr of integers and a positive integer k, return a sorted table \n-- of length k with the maximum k numbers in arr.\n-- Example 1:\n-- >>> maximum({-3, -4, 5}, 3)\n-- {-4, -3, 5}\n-- Example 2:\n-- >>> maximum({4, -4, 4}, 2)\n-- {4, 4}\n-- Example 3:\n-- >>> maximum({-3, 2, 1, 2, -1, -2, 1}, 1)\n-- {2}\n-- Note:\n-- 1. The length of the table will be in the range of [1, 1000].\n-- 2. The elements in the table will be in the range of [-1000, 1000].\n-- 3. 0 <= k <= len(arr)\nlocal function maximum(arr, k)\n table.sort(arr, function(a, b) return a > b end)\n return table.sub(arr, 1, k)\nend\n"], ["-- Given a non-empty table of integers, return the sum of all of the odd elements that are in even positions.\n-- Examples\n-- >>> solution({5, 8, 7, 1})\n-- 12\n-- >>> solution({3, 3, 3, 3, 3})\n-- 9\n-- >>> solution({30, 13, 24, 321})\n-- 0\nlocal function solution(lst)\n local sum = 0\n for i = 1, #lst, 2 do\n if lst[i] % 2 == 1 then\n sum = sum + lst[i]\n end\n end\n return sum\nend\n"], ["-- Given a non-empty table of integers arr and an integer k, return\n-- the sum of the elements with at most two digits from the first k elements of arr.\n-- Example:\n-- >>> add_elements({111, 21, 3, 4000, 5, 6, 7, 8, 9}, 4)\n-- 24\n-- Constraints:\n-- 1. 1 <= len(arr) <= 100\n-- 2. 1 <= k <= len(arr)\nlocal function add_elements(arr, k)\n local sum = 0\n for i = 1, k do\n local num = arr[i]\n if num < 100 then\n sum = sum + num\n end\n end\n return sum\nend\n"], ["-- Given a positive integer n, return a sorted table that has the odd numbers in collatz sequence.\n-- The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n-- as follows: start with any positive integer n. Then each term is obtained from the \n-- previous term as follows: if the previous term is even, the next term is one half of \n-- the previous term. If the previous term is odd, the next term is 3 times the previous\n-- term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n-- Note: \n-- 1. Collatz(1) is [1].\n-- 2. returned table sorted in increasing order.\n-- For example:\n-- get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n-- >>> get_odd_collatz(5)\n-- {1, 5}\nlocal function get_odd_collatz(n)\n local collatz = {}\n while n ~= 1 do\n if n % 2 == 0 then\n n = n / 2\n else\n n = 3 * n + 1\n end\n if n % 2 == 1 then\n table.insert(collatz, n)\n end\n end\n table.sort(collatz)\n return collatz\nend"], ["-- You have to write a function which validates a given date string and\n-- returns true if the date is valid otherwise false.\n-- The date is valid if all of the following rules are satisfied:\n-- 1. The date string is not empty.\n-- 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n-- 3. The months should not be less than 1 or higher than 12.\n-- 4. The date should be in the format: mm-dd-yyyy\n-- >>> valid_date('03-11-2000')\n-- true\n-- >>> valid_date('15-01-2012')\n-- false\n-- >>> valid_date('04-0-2040')\n-- false\n-- >>> valid_date('06-04-2020')\n-- true\n-- >>> valid_date('06/04/2020')\n-- false\nlocal function valid_date(date)\n -- Check if the date string is not empty\n if date == '' then\n return false\n end"], ["-- Given a string of words, return a table of words split on whitespace, if no whitespaces exists in the text you\n-- should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n-- alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n-- Examples\n-- >>> split_words('Hello world!')\n-- {'Hello', 'world!'}\n-- >>> split_words('Hello,world!')\n-- {'Hello', 'world!'}\n-- >>> split_words('abcdef')\n-- 3\nlocal function split_words(txt)\n local words = {}\n local i = 1\n local j = 1\n while j <= #txt do\n if txt:sub(j, j) == ' ' then\n table.insert(words, txt:sub(i, j-1))\n i = j+1\n elseif txt:sub(j, j) == ',' then\n table.insert(words, txt:sub(i, j-1))\n i = j+1\n end\n j = j+1\n end\n table.insert(words, txt:sub(i))\n if #words == 1 then\n local count = 0\n for k = 1, #txt do\n local c = txt:sub(k, k)\n if c >= 'a' and c <= 'z' and (c:byte() - 97) % 2 == 0 then\n count = count + 1\n end\n end\n return count\n else\n return words\n end\nend\n"], ["-- Given a table of numbers, return whether or not they are sorted\n-- in ascending order. If table has more than 1 duplicate of the same\n-- number, return false. Assume no negative numbers and only integers.\n-- Examples\n-- >>> is_sorted({5})\n-- true\n-- >>> is_sorted({1, 2, 3, 4, 5})\n-- true\n-- >>> is_sorted({1, 3, 2, 4, 5})\n-- false\n-- >>> is_sorted({1, 2, 3, 4, 5, 6})\n-- true\n-- >>> is_sorted({1, 2, 3, 4, 5, 6, 7})\n-- true\n-- >>> is_sorted({1, 3, 2, 4, 5, 6, 7})\n-- false\n-- >>> is_sorted({1, 2, 2, 3, 3, 4})\n-- true\n-- >>> is_sorted({1, 2, 2, 2, 3, 4})\n-- false\nlocal function is_sorted(lst)\n local prev = lst[1]\n for i = 2, #lst do\n if lst[i] < prev then\n return false\n elseif lst[i] == prev then\n return false\n end\n prev = lst[i]\n end\n return true\nend\n"], ["-- You are given two intervals,\n-- where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n-- The given intervals are closed which means that the interval (start, end)\n-- includes both start and end.\n-- For each given interval, it is assumed that its start is less or equal its end.\n-- Your task is to determine whether the length of intersection of these two \n-- intervals is a prime number.\n-- Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n-- which its length is 1, which not a prime number.\n-- If the length of the intersection is a prime number, return \"YES\",\n-- otherwise, return \"NO\".\n-- If the two intervals don't intersect, return \"NO\".\n-- [input/output] samples:\n-- >>> intersection({1, 2}, {2, 3})\n-- 'NO'\n-- >>> intersection({-1, 1}, {0, 4})\n-- 'NO'\n-- >>> intersection({-3, -1}, {-5, 5})\n-- 'YES'\nlocal function intersection(interval1, interval2)\n local start1, end1 = interval1[1], interval1[2]\n local start2, end2 = interval2[1], interval2[2]\n local intersection_start = math.max(start1, start2)\n local intersection_end = math.min(end1, end2)\n local intersection_length = intersection_end - intersection_start + 1\n if intersection_length <= 0 then\n return \"NO\"\n end\n if intersection_length == 1 then\n return \"NO\"\n end\n for i = 2, math.floor(math.sqrt(intersection_length)) do\n if intersection_length % i == 0 then\n return \"NO\"\n end\n end\n return \"YES\"\nend\n"], ["-- You are given a table arr of integers and you need to return\n-- sum of magnitudes of integers multiplied by product of all signs\n-- of each number in the table, represented by 1, -1 or 0.\n-- Note: return nil for empty arr.\n-- Example:\n-- >>> prod_signs({1, 2, 2, -4})\n-- 9\n-- >>> prod_signs({0, 1})\n-- 0\n-- >>> prod_signs({})\n-- None\nlocal function prod_signs(arr)\n if #arr == 0 then\n return nil\n end\n local sum = 0\n local product = 1\n for i = 1, #arr do\n sum = sum + math.abs(arr[i])\n if arr[i] < 0 then\n product = product * -1\n elseif arr[i] == 0 then\n product = 0\n end\n end\n return sum * product\nend\n"], ["-- Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n-- each cell of the grid contains a value. Every integer in the range [1, N * N]\n-- inclusive appears exactly once on the cells of the grid.\n-- You have to find the minimum path of length k in the grid. You can start\n-- from any cell, and in each step you can move to any of the neighbor cells,\n-- in other words, you can go to cells which share an edge with you current\n-- cell.\n-- Please note that a path of length k means visiting exactly k cells (not\n-- necessarily distinct).\n-- You CANNOT go off the grid.\n-- A path A (of length k) is considered less than a path B (of length k) if\n-- after making the ordered tables of the values on the cells that A and B go\n-- through (let's call them lst_A and lst_B), lst_A is lexicographically less\n-- than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n-- such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n-- lst_A[j] = lst_B[j].\n-- It is guaranteed that the answer is unique.\n-- Return an ordered table of the values on the cells that the minimum path go through.\n-- Examples: \n-- >>> minPath({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 3)\n-- {1, 2, 1}\n-- >>> minPath({{5, 9, 3}, {4, 1, 6}, {7, 8, 2}}, 1)\n-- {1}\nlocal function minPath(grid, k)\n local n = #grid\n local dp = {}\n for i = 1, n do\n dp[i] = {}\n for j = 1, n do\n dp[i][j] = {}\n for l = 1, k do\n dp[i][j][l] = {}\n end\n end\n end\n for i = 1, n do\n for j = 1, n do\n dp[i][j][1][1] = grid[i][j]\n end\n end\n for l = 2, k do\n for i = 1, n do\n for j = 1, n do\n for x = i - 1, i + 1 do\n for y = j - 1, j + 1 do\n if x >= 1 and x <= n and y >= 1 and y <= n then\n for p = 1, l - 1 do\n for q = 1, #dp[x][y][p] do\n local path = {}\n for r = 1, #dp[i][j][p] do\n path[r] = dp[i][j][p][r]\n end\n for r = 1, #dp[x][y][p] do\n path[#path + 1] = dp[x][y][p][r]\n end\n if #path == l then\n local found = false\n for r = 1, #dp[i][j][l] do\n if #dp[i][j][l][r] == l and dp[i][j][l][r][1] < path[1] then\n found = true\n break\n end\n end\n if not found then\n dp[i][j][l][#dp[i][j][l] + 1] = path\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n local minPath = {}\n for i = 1, n do\n for j = 1, n do\n for l = 1, k do\n for p = 1, #dp[i][j][l] do\n local path = dp[i][j][l][p]\n if #path == k then\n if #minPath == 0 then\n minPath = path\n else\n local found = false\n for q = 1, #minPath do\n if minPath[q] < path[q] then\n found = true\n break\n elseif minPath[q] > path[q] then\n break\n end\n end\n if not found then\n minPath = path\n end\n end\n end\n end\n end\n end\n end\n return minPath\nend\n"], ["-- Out of table of strings, return the longest one. Return the first one in case of multiple\n-- strings of the same length. Return nil in case the input table is empty.\n-- >>> longest({})\n-- None\n-- >>> longest({'a', 'b', 'c'})\n-- 'a'\n-- >>> longest({'a', 'bb', 'ccc'})\n-- 'ccc'\nlocal function longest(strings)\n local longest_string = nil\n local longest_length = 0\n for _, string in ipairs(strings) do\n local length = string.len(string)\n if length > longest_length then\n longest_string = string\n longest_length = length\n end\n end\n return longest_string\nend"], ["-- Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n-- the last couple centuries. However, what people don't know is Tribonacci sequence.\n-- Tribonacci sequence is defined by the recurrence:\n-- tri(1) = 3\n-- tri(n) = 1 + n / 2, if n is even.\n-- tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n-- For example:\n-- tri(2) = 1 + (2 / 2) = 2\n-- tri(4) = 3\n-- tri(3) = tri(2) + tri(1) + tri(4)\n-- = 2 + 3 + 3 = 8 \n-- You are given a non-negative integer number n, you have to a return a table of the \n-- first n + 1 numbers of the Tribonacci sequence.\n-- Examples:\n-- >>> tri(3)\n-- {1, 3, 2, 8}\nlocal function tri(n)\n local result = {}\n for i = 1, n + 1 do\n if i == 1 then\n result[i] = 3\n elseif i % 2 == 0 then\n result[i] = 1 + i / 2\n else\n result[i] = result[i - 1] + result[i - 2] + result[i + 1]\n end\n end\n return result\nend"], ["-- Given a positive integer n, return the product of the odd digits.\n-- Return 0 if all digits are even.\n-- For example:\n-- >>> digits(1)\n-- 1\n-- >>> digits(4)\n-- 0\n-- >>> digits(235)\n-- 15\nlocal function digits(n)\n local product = 1\n while n > 0 do\n local digit = n % 10\n if digit % 2 == 1 then\n product = product * digit\n end\n n = (n - digit) / 10\n end\n if product == 1 then\n return 0\n else\n return product\n end\nend\n"], ["-- Create a function that takes a string as input which contains only square brackets.\n-- The function should return true if and only if there is a valid subsequence of brackets \n-- where at least one bracket in the subsequence is nested.\n-- >>> is_nested('[[]]')\n-- true\n-- >>> is_nested('[]]]]]]][[[[[]')\n-- false\n-- >>> is_nested('[][]')\n-- false\n-- >>> is_nested('[]')\n-- false\n-- >>> is_nested('[[][]]')\n-- true\n-- >>> is_nested('[[]][[')\n-- true\nlocal function is_nested(string)\n local stack = {}\n for i = 1, #string do\n local c = string:sub(i, i)\n if c == \"[\" then\n table.insert(stack, c)\n elseif c == \"]\" then\n if #stack > 0 then\n table.remove(stack)\n else\n return false\n end\n end\n end\n return #stack > 0\nend"], ["-- You are given a table of numbers.\n-- You need to return the sum of squared numbers in the given table,\n-- round each element in the table to the upper int(Ceiling) first.\n-- Examples:\n-- >>> lst({1.0, 2.0, 3.0})\n-- 14\n-- >>> lst({1.0, 4.0, 9.0})\n-- 98\n-- >>> lst({1.0, 3.0, 5.0, 7.0})\n-- 84\n-- >>> lst({1.4, 4.2, 0.0})\n-- 29\n-- >>> lst({-2.4, 1.0, 1.0})\n-- 6\nlocal function sum_squares(lst)\n local sum = 0\n for _, num in ipairs(lst) do\n local ceil_num = math.ceil(num)\n sum = sum + ceil_num * ceil_num\n end\n return sum\nend"], ["-- Create a function that returns true if the last character\n-- of a given string is an alphabetical character and is not\n-- a part of a word, and false otherwise.\n-- Note: \"word\" is a group of characters separated by space.\n-- Examples:\n-- >>> check_if_last_char_is_a_letter('apple pie')\n-- false\n-- >>> check_if_last_char_is_a_letter('apple pi e')\n-- true\n-- >>> check_if_last_char_is_a_letter('apple pi e ')\n-- false\n-- >>> check_if_last_char_is_a_letter('')\n-- false\nlocal function check_if_last_char_is_a_letter(txt)\n local last_char = txt:sub(-1)\n local last_word = txt:match('%S+$')\n if last_char:match('%a') and last_word:match('%a$') then\n return true\n else\n return false\n end\nend\n"], ["-- Create a function which returns the largest index of an element which\n-- is not greater than or equal to the element immediately preceding it. If\n-- no such element exists then return -1. The given table will not contain\n-- duplicate values.\n-- Examples:\n-- >>> can_arrange({1, 2, 4, 3, 5})\n-- 3\n-- >>> can_arrange({1, 2, 3})\n-- -1\nlocal function can_arrange(arr)\n local max_index = -1\n for i = 2, #arr do\n if arr[i] < arr[i-1] then\n max_index = i - 1\n end\n end\n return max_index\nend"], ["-- Create a function that returns a table (a, b), where 'a' is\n-- the largest of negative integers, and 'b' is the smallest\n-- of positive integers in a table.\n-- If there is no negative or positive integers, return them as nil.\n-- Examples:\n-- >>> largest_smallest_integers({2, 4, 1, 3, 5, 7})\n-- {None, 1}\n-- >>> largest_smallest_integers({})\n-- {None, None}\n-- >>> largest_smallest_integers({0})\n-- {None, None}\nlocal function largest_smallest_integers(lst)\n local largest_negative = nil\n local smallest_positive = nil\n for _, num in ipairs(lst) do\n if num < 0 and (largest_negative == nil or num > largest_negative) then\n largest_negative = num\n elseif num > 0 and (smallest_positive == nil or num < smallest_positive) then\n smallest_positive = num\n end\n end\n return {largest_negative, smallest_positive}\nend"], ["-- Create a function that takes integers, floats, or strings representing\n-- real numbers, and returns the larger variable in its given variable type.\n-- Return nil if the values are equal.\n-- Note: If a real number is represented as a string, the floating point might be . or ,\n-- >>> compare_one(1, 2.5)\n-- 2.5\n-- >>> compare_one(1, '2,3')\n-- '2,3'\n-- >>> compare_one('5,1', '6')\n-- '6'\n-- >>> compare_one('1', 1)\n-- None\nlocal function compare_one(a, b)\n -- Convert strings to numbers if necessary\n if type(a) == 'string' then\n a = tonumber(string.gsub(a, ',', '.'))\n end\n if type(b) == 'string' then\n b = tonumber(string.gsub(b, ',', '.'))\n end\n -- Compare the values\n if a > b then\n return a\n elseif b > a then\n return b\n else\n return nil\n end\nend\n"], ["-- Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n-- Example\n-- >>> is_equal_to_sum_even(4)\n-- false\n-- >>> is_equal_to_sum_even(6)\n-- false\n-- >>> is_equal_to_sum_even(8)\n-- true\nlocal function is_equal_to_sum_even(n)\n if n % 2 ~= 0 then\n return false\n end\n local sum = 0\n for i = 1, n/2 do\n sum = sum + i*2\n end\n return sum == n\nend"], ["-- The Brazilian factorial is defined as:\n-- brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n-- where n > 0\n-- For example:\n-- >>> special_factorial(4)\n-- 288\n-- The function will receive an integer as input and should return the special\n-- factorial of this integer.\nlocal function special_factorial(n)\n local result = 1\n for i = n, 1, -1 do\n result = result * i\n end\n return result\nend"], ["-- Return a greatest common divisor of two integers a and b\n-- >>> greatest_common_divisor(3, 5)\n-- 1\n-- >>> greatest_common_divisor(25, 15)\n-- 5\nlocal function greatest_common_divisor(a, b)\n while b ~= 0 do\n local temp = b\n b = a % b\n a = temp\n end\n return a\nend"], ["-- Given a string text, replace all spaces in it with underscores, \n-- and if a string has more than 2 consecutive spaces, \n-- then replace all consecutive spaces with - \n-- >>> fix_spaces(' Example')\n-- 'Example'\n-- >>> fix_spaces(' Example 1')\n-- 'Example_1'\n-- >>> fix_spaces(' Example 2')\n-- '_Example_2'\n-- >>> fix_spaces(' Example 3')\n-- '_Example-3'\nlocal function fix_spaces(text)\n local new_text = string.gsub(text, \" \", \"_\")\n new_text = string.gsub(new_text, \"__+\", \"-\")\n return new_text\nend"], ["-- Create a function which takes a string representing a file's name, and returns\n-- 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n-- A file's name is considered to be valid if and only if all the following conditions \n-- are met:\n-- - There should not be more than three digits ('0'-'9') in the file's name.\n-- - The file's name contains exactly one dot '.'\n-- - The substring before the dot should not be empty, and it starts with a letter from \n-- the latin alphapet ('a'-'z' and 'A'-'Z').\n-- - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n-- Examples:\n-- >>> file_name_check('example.txt')\n-- 'Yes'\n-- >>> file_name_check('1example.dll')\n-- 'No'\nlocal function file_name_check(file_name)\n -- Check if there are more than three digits in the file's name\n if string.match(file_name, '%d%d%d%d') then\n return 'No'\n end"], ["-- \"\n-- This function will take a table of integers. For all entries in the table, the function shall square the integer entry if its index is a \n-- multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n-- change the entries in the table whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n-- Examples:\n-- >>> lst\n-- {1, 2, 3}\n-- >>> lst\n-- {}\n-- >>> lst\n-- {-1, -5, 2, -1, -5}\nlocal function sum_squares(lst)\n local sum = 0\n for i, num in ipairs(lst) do\n if i % 3 == 0 then\n sum = sum + num^2\n elseif i % 4 == 0 then\n sum = sum + num^3\n else\n sum = sum + num\n end\n end\n return sum\nend\n"], ["-- You are given a string representing a sentence,\n-- the sentence contains some words separated by a space,\n-- and you have to return a string that contains the words from the original sentence,\n-- whose lengths are prime numbers,\n-- the order of the words in the new string should be the same as the original one.\n-- Example 1:\n-- >>> words_in_sentence('This is a test')\n-- 'is'\n-- Example 2:\n-- >>> words_in_sentence('lets go for swimming')\n-- 'go for'\n-- Constraints:\n-- * 1 <= len(sentence) <= 100\n-- * sentence contains only letters\nlocal function words_in_sentence(sentence)\n local words = {}\n for word in sentence:gmatch(\"%S+\") do\n if is_prime(#word) then\n table.insert(words, word)\n end\n end\n return table.concat(words, \" \")\nend"], ["-- Your task is to implement a function that will simplify the expression\n-- x * n. The function returns true if x * n evaluates to a whole number and false\n-- otherwise. Both x and n, are string representation of a fraction, and have the following format,\n-- / where both numerator and denominator are positive whole numbers.\n-- You can assume that x, and n are valid fractions, and do not have zero as denominator.\n-- >>> simplify('1/5', '5/1')\n-- true\n-- >>> simplify('1/6', '2/1')\n-- false\n-- >>> simplify('7/10', '10/2')\n-- false\nlocal function simplify(x, n)\n local x_num, x_den = x:match(\"(%d+)/(%d+)\")\n local n_num, n_den = n:match(\"(%d+)/(%d+)\")\n local result = (x_num * n_num) / (x_den * n_den)\n return result == math.floor(result)\nend"], ["-- Write a function which sorts the given table of integers\n-- in ascending order according to the sum of their digits.\n-- Note: if there are several items with similar sum of their digits,\n-- order them based on their index in original table.\n-- For example:\n-- >>> order_by_points({1, 11, -1, -11, -12})\n-- {-1, -11, 1, -12, 11}\n-- >>> order_by_points({})\n-- {}\nlocal function order_by_points(nums)\n local function sum_digits(num)\n local sum = 0\n while num > 0 do\n sum = sum + num % 10\n num = math.floor(num / 10)\n end\n return sum\n end\n table.sort(nums, function(a, b)\n local sum_a = sum_digits(math.abs(a))\n local sum_b = sum_digits(math.abs(b))\n if sum_a == sum_b then\n return a < b\n else\n return sum_a < sum_b\n end\n end)\n return nums\nend"], ["-- Write a function that takes a table of numbers as input and returns \n-- the number of elements in the table that are greater than 10 and both \n-- first and last digits of a number are odd (1, 3, 5, 7, 9).\n-- For example:\n-- >>> specialFilter({15, -73, 14, -15})\n-- 1\n-- >>> specialFilter({33, -2, -3, 45, 21, 109})\n-- 2\nlocal function specialFilter(nums)\n local count = 0\n for _, num in ipairs(nums) do\n local firstDigit = math.abs(num) % 10\n local lastDigit = math.abs(num) % 10\n while math.abs(num) > 9 do\n num = math.floor(math.abs(num) / 10)\n lastDigit = math.abs(num) % 10\n end\n if num > 10 and firstDigit % 2 == 1 and lastDigit % 2 == 1 then\n count = count + 1\n end\n end\n return count\nend"], ["-- You are given a positive integer n. You have to create an integer table a of length n.\n-- For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n-- Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n-- and a[i] + a[j] + a[k] is a multiple of 3.\n-- Example :\n-- >>> get_max_triples(5)\n-- 1\n-- Explanation: \n-- a = [1, 3, 7, 13, 21]\n-- The only valid triple is (1, 7, 13).\nlocal function get_max_triples(n)\n local a = {}\n for i = 1, n do\n a[i] = i * i - i + 1\n end\n local count = 0\n for i = 1, n - 2 do\n for j = i + 1, n - 1 do\n for k = j + 1, n do\n if (a[i] + a[j] + a[k]) % 3 == 0 then\n count = count + 1\n end\n end\n end\n end\n return count\nend"], ["-- There are eight planets in our solar system: the closerst to the Sun \n-- is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n-- Uranus, Neptune.\n-- Write a function that takes two planet names as strings planet1 and planet2. \n-- The function should return a table containing all planets whose orbits are \n-- located between the orbit of planet1 and the orbit of planet2, sorted by \n-- the proximity to the sun. \n-- The function should return an empty table if planet1 or planet2\n-- are not correct planet names. \n-- Examples\n-- >>> bf('Jupiter', 'Neptune')\n-- {'Saturn', 'Uranus'}\n-- >>> bf('Earth', 'Mercury')\n-- 'Venus'\n-- >>> bf('Mercury', 'Uranus')\n-- {'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'}\nlocal function bf(planet1, planet2)\n local planets = {'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'}\n local index1 = table.indexof(planets, planet1)\n local index2 = table.indexof(planets, planet2)\n if index1 == nil or index2 == nil then\n return {}\n end\n local result = {}\n for i = index1 + 1, index2 - 1 do\n table.insert(result, planets[i])\n end\n return result\nend"], ["-- Write a function that accepts a table of strings as a parameter,\n-- deletes the strings that have odd lengths from it,\n-- and returns the resulted table with a sorted order,\n-- The table is always a table of strings and never a table of numbers,\n-- and it may contain duplicates.\n-- The order of the table should be ascending by length of each word, and you\n-- should return the table sorted by that rule.\n-- If two words have the same length, sort the table alphabetically.\n-- The function should return a table of strings in sorted order.\n-- You may assume that all words will have the same length.\n-- For example:\n-- >>> list_sort({'aa', 'a', 'aaa'})\n-- {'aa'}\n-- >>> list_sort({'ab', 'a', 'aaa', 'cd'})\n-- {'ab', 'cd'}\nlocal function sorted_list_sum(lst)\n local result = {}\n for _, word in ipairs(lst) do\n if #word % 2 == 0 then\n table.insert(result, word)\n end\n end\n table.sort(result, function(a, b)\n if #a == #b then\n return a < b\n else\n return #a < #b\n end\n end)\n return result\nend"], ["-- Return table of all prefixes from shortest to longest of the input string\n-- >>> all_prefixes('abc')\n-- {'a', 'ab', 'abc'}\nlocal function all_prefixes(string)\n local prefixes = {}\n for i = 1, #string do\n table.insert(prefixes, string:sub(1, i))\n end\n return prefixes\nend"], ["-- A simple program which should return the value of x if n is \n-- a prime number and should return the value of y otherwise.\n-- Examples:\n-- >>> x_or_y(7, 34, 12)\n-- 34\n-- >>> x_or_y(15, 8, 5)\n-- 5\nlocal function x_or_y(n, x, y)\n local function is_prime(n)\n if n <= 1 then\n return false\n end\n for i = 2, math.sqrt(n) do\n if n % i == 0 then\n return false\n end\n end\n return true\n end\n if is_prime(n) then\n return x\n else\n return y\n end\nend"], ["-- Given a table of numbers, return the sum of squares of the numbers\n-- in the table that are odd. Ignore numbers that are negative or not integers.\n-- >>> double_the_difference({1, 3, 2, 0})\n-- 10\n-- >>> double_the_difference({-1, -2, 0})\n-- 0\n-- >>> double_the_difference({9, -2})\n-- 81\n-- >>> double_the_difference({0})\n-- 0\n-- If the input table is empty, return 0.\nlocal function double_the_difference(lst)\n local sum = 0\n for _, num in ipairs(lst) do\n if type(num) == \"number\" and num == math.floor(num) and num % 2 == 1 then\n sum = sum + num * num\n end\n end\n return sum\nend\n"], ["-- I think we all remember that feeling when the result of some long-awaited\n-- event is finally known. The feelings and thoughts you have at that moment are\n-- definitely worth noting down and comparing.\n-- Your task is to determine if a person correctly guessed the results of a number of matches.\n-- You are given two tables of scores and guesses of equal length, where each index shows a match. \n-- Return a table of the same length denoting how far off each guess was. If they have guessed correctly,\n-- the value is 0, and if not, the value is the absolute difference between the guess and the score.\n-- example:\n-- >>> compare({1, 2, 3, 4, 5, 1}, {1, 2, 3, 4, 2, -2})\n-- {0, 0, 0, 0, 3, 3}\n-- >>> compare({0, 5, 0, 0, 0, 4}, {4, 1, 1, 0, 0, -2})\n-- {4, 4, 1, 0, 0, 6}\nlocal function compare(game, guess)\n local diff = {}\n for i = 1, #game do\n if game[i] == guess[i] then\n diff[i] = 0\n else\n diff[i] = math.abs(game[i] - guess[i])\n end\n end\n return diff\nend\n"], ["-- You will be given the name of a class (a string) and a table of extensions.\n-- The extensions are to be used to load additional classes to the class. The\n-- strength of the extension is as follows: Let CAP be the number of the uppercase\n-- letters in the extension's name, and let SM be the number of lowercase letters \n-- in the extension's name, the strength is given by the fraction CAP - SM. \n-- You should find the strongest extension and return a string in this \n-- format: ClassName.StrongestExtensionName.\n-- If there are two or more extensions with the same strength, you should\n-- choose the one that comes first in the table.\n-- For example, if you are given \"Slices\" as the class and a table of the\n-- extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n-- return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n-- (its strength is -1).\n-- Example:\n-- >>> Strongest_Extension('my_class', {'AA', 'Be', 'CC'})\n-- 'my_class.AA'\nlocal function Strongest_Extension(class_name, extensions)\n local strongest_extension = ''\n local strongest_strength = -1\n for i, extension in ipairs(extensions) do\n local cap_count = 0\n local sm_count = 0\n for j = 1, #extension do\n local char = string.sub(extension, j, j)\n if char == string.upper(char) then\n cap_count = cap_count + 1\n else\n sm_count = sm_count + 1\n end\n end\n local strength = cap_count - sm_count\n if strength > strongest_strength then\n strongest_extension = extension\n strongest_strength = strength\n end\n end\n return class_name .. '.' .. strongest_extension\nend\n"], ["-- You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n-- >>> cycpattern_check('abcd', 'abd')\n-- false\n-- >>> cycpattern_check('hello', 'ell')\n-- true\n-- >>> cycpattern_check('whassup', 'psus')\n-- false\n-- >>> cycpattern_check('abab', 'baa')\n-- true\n-- >>> cycpattern_check('efef', 'eeff')\n-- false\n-- >>> cycpattern_check('himenss', 'simen')\n-- true\nlocal function cycpattern_check(a, b)\n local n = #a\n local m = #b\n if m > n then return false end\n local s = a .. a\n for i = 1, n do\n if s:sub(i, i + m - 1) == b then\n return true\n end\n end\n return false\nend\n"], ["-- Given an integer. return a table that has the number of even and odd digits respectively.\n-- Example:\n-- >>> even_odd_count(-12)\n-- {1, 1}\n-- >>> even_odd_count(123)\n-- {1, 2}\nlocal function even_odd_count(num)\n local even_count = 0\n local odd_count = 0\n local abs_num = math.abs(num)\n while abs_num > 0 do\n local digit = abs_num % 10\n if digit % 2 == 0 then\n even_count = even_count + 1\n else\n odd_count = odd_count + 1\n end\n abs_num = math.floor(abs_num / 10)\n end\n return {even_count, odd_count}\nend"], ["-- Given a positive integer, obtain its roman numeral equivalent as a string,\n-- and return it in lowercase.\n-- Restrictions: 1 <= num <= 1000\n-- Examples:\n-- >>> int_to_mini_roman(19)\n-- 'xix'\n-- >>> int_to_mini_roman(152)\n-- 'clii'\n-- >>> int_to_mini_roman(426)\n-- 'cdxxvi'\nlocal function int_to_mini_roman(number)\n local roman_numerals = {\n {1000, \"m\"},\n {900, \"cm\"},\n {500, \"d\"},\n {400, \"cd\"},\n {100, \"c\"},\n {90, \"xc\"},\n {50, \"l\"},\n {40, \"xl\"},\n {10, \"x\"},\n {9, \"ix\"},\n {5, \"v\"},\n {4, \"iv\"},\n {1, \"i\"}\n }\n local result = \"\"\n for _, pair in ipairs(roman_numerals) do\n while number >= pair[1] do\n result = result .. pair[2]\n number = number - pair[1]\n end\n end\n return result:lower()\nend"], ["-- Given the lengths of the three sides of a triangle. Return true if the three\n-- sides form a right-angled triangle, false otherwise.\n-- A right-angled triangle is a triangle in which one angle is right angle or \n-- 90 degree.\n-- Example:\n-- >>> right_angle_triangle(3, 4, 5)\n-- true\n-- >>> right_angle_triangle(1, 2, 3)\n-- false\nlocal function right_angle_triangle(a, b, c)\n local sides = {a, b, c}\n table.sort(sides)\n return sides[1]^2 + sides[2]^2 == sides[3]^2\nend"], ["-- Write a function that accepts a table of strings.\n-- The table contains different words. Return the word with maximum number\n-- of unique characters. If multiple strings have maximum number of unique\n-- characters, return the one which comes first in lexicographical order.\n-- >>> find_max({'name', 'of', 'string'})\n-- 'string'\n-- >>> find_max({'name', 'enam', 'game'})\n-- 'enam'\n-- >>> find_max({'aaaaaaa', 'bb', 'cc'})\n-- 'aaaaaaa'\nlocal function find_max(words)\n local max_word = ''\n local max_unique = 0\n for _, word in ipairs(words) do\n local unique_chars = {}\n for _, char in ipairs(word) do\n unique_chars[char] = true\n end\n local num_unique = #unique_chars\n if num_unique > max_unique or (num_unique == max_unique and word < max_word) then\n max_word = word\n max_unique = num_unique\n end\n end\n return max_word\nend"], ["-- You're a hungry rabbit, and you already have eaten a certain number of carrots,\n-- but now you need to eat more carrots to complete the day's meals.\n-- you should return a table of [ total number of eaten carrots after your meals,\n-- the number of carrots left after your meals ]\n-- if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n-- Example:\n-- >>> eat(5, 6, 10)\n-- {11, 4}\n-- >>> eat(4, 8, 9)\n-- {12, 1}\n-- >>> eat(1, 10, 10)\n-- {11, 0}\n-- >>> eat(2, 11, 5)\n-- {7, 0}\n-- Variables:\n-- @number : integer\n-- the number of carrots that you have eaten.\n-- @need : integer\n-- the number of carrots that you need to eat.\n-- @remaining : integer\n-- the number of remaining carrots thet exist in stock\n-- Constrain:\n-- * 0 <= number <= 1000\n-- * 0 <= need <= 1000\n-- * 0 <= remaining <= 1000\n-- Have fun :)\nlocal function eat(number, need, remaining)\n local eaten = number + need\n local left = remaining - need\n if left < 0 then\n left = 0\n end\n return {eaten, left}\nend"], ["-- Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n-- >>> string_sequence(0)\n-- '0'\n-- >>> string_sequence(5)\n-- '0 1 2 3 4 5'\nlocal function string_sequence(n)\n local result = \"\"\n for i = 0, n do\n result = result .. tostring(i) .. \" \"\n end\n return string.sub(result, 1, -2)\nend"], ["-- Given two tables operator, and operand. The first table has basic algebra operations, and \n-- the second table is a table of integers. Use the two given tables to build the algebric \n-- expression and return the evaluation of this expression.\n-- The basic algebra operations:\n-- Addition ( + ) \n-- Subtraction ( - ) \n-- Multiplication ( * ) \n-- Floor division ( // ) \n-- Exponentiation ( ** ) \n-- Example:\n-- operator['+', '*', '-']\n-- table = [2, 3, 4, 5]\n-- result = 2 + 3 * 4 - 5\n-- => result = 9\n-- Note:\n-- The length of operator table is equal to the length of operand table minus one.\n-- Operand is a table of of non-negative integers.\n-- Operator table has at least one operator, and operand table has at least two operands.\nlocal function do_algebra(operator, operand)\n local result = operand[1]\n for i = 1, #operator do\n local op = operator[i]\n local num = operand[i + 1]\n if op == '+' then\n result = result + num\n elseif op == '-' then\n result = result - num\n elseif op == '*' then\n result = result * num\n elseif op == '//' then\n result = math.floor(result / num)\n elseif op == '**' then\n result = result ^ num\n end\n end\n return result\nend"], ["-- You are given a string s.\n-- if s[i] is a letter, reverse its case from lower to upper or vise versa, \n-- otherwise keep it as it is.\n-- If the string contains no letters, reverse the string.\n-- The function should return the resulted string.\n-- Examples\n-- >>> solve('1234')\n-- '4321'\n-- >>> solve('ab')\n-- 'AB'\n-- >>> solve('#a@C')\n-- '#A@c'\nlocal function solve(s)\n local result = ''\n local has_letters = false\n for i = 1, #s do\n local c = s:sub(i, i)\n if c:match('%a') then\n has_letters = true\n if c:match('%l') then\n result = result .. c:upper()\n else\n result = result .. c:lower()\n end\n else\n result = result .. c\n end\n end\n if not has_letters then\n result = s:reverse()\n end\n return result\nend\n"], ["-- Given a string 'text', return its md5 hash equivalent string.\n-- If 'text' is an empty string, return nil.\n-- >>> string_to_md5('Hello world')\n-- '3e25960a79dbc69b674cd4ec67a72c62'\nlocal function string_to_md5(text)\n if text == '' then\n return nil\n end\n local md5 = require('md5')\n return md5.sumhexa(text)\nend"], ["-- Given two positive integers a and b, return the even digits between a\n-- and b, in ascending order.\n-- For example:\n-- >>> generate_integers(2, 8)\n-- {2, 4, 6, 8}\n-- >>> generate_integers(8, 2)\n-- {2, 4, 6, 8}\n-- >>> generate_integers(10, 14)\n-- {}\nlocal function generate_integers(a, b)\n local result = {}\n for i = a, b do\n local digits = {}\n for digit in string.gmatch(tostring(i), \"%d\") do\n table.insert(digits, tonumber(digit))\n end\n local even_digits = {}\n for _, digit in ipairs(digits) do\n if digit % 2 == 0 then\n table.insert(even_digits, digit)\n end\n end\n table.sort(even_digits)\n for _, digit in ipairs(even_digits) do\n table.insert(result, digit)\n end\n end\n return result\nend"], ["-- Given a string, find out how many distinct characters (regardless of case) does it consist of\n-- >>> count_distinct_characters('xyzXYZ')\n-- 3\n-- >>> count_distinct_characters('Jerry')\n-- 4\nlocal function count_distinct_characters(string)\n local seen = {}\n local count = 0\n for i = 1, #string do\n local char = string:sub(i, i):lower()\n if not seen[char] then\n seen[char] = true\n count = count + 1\n end\n end\n return count\nend"], ["-- Input to this function is a string representing musical notes in a special ASCII format.\n-- Your task is to parse this string and return table of integers corresponding to how many beats does each\n-- not last.\n-- Here is a legend:\n-- 'o' - whole note, lasts four beats\n-- 'o|' - half note, lasts two beats\n-- '.|' - quater note, lasts one beat\n-- >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n-- {4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4}\nlocal function parse_music(music_string)\n local notes = {}\n local current_note = \"\"\n for i = 1, #music_string do\n local char = music_string:sub(i, i)\n if char == \" \" then\n if current_note == \"o\" then\n table.insert(notes, 4)\n elseif current_note == \"o|\" then\n table.insert(notes, 2)\n elseif current_note == \".|\" then\n table.insert(notes, 1)\n end\n current_note = \"\"\n else\n current_note = current_note .. char\n end\n end\n return notes\nend"], ["-- Find how many times a given substring can be found in the original string. Count overlaping cases.\n-- >>> how_many_times('', 'a')\n-- 0\n-- >>> how_many_times('aaa', 'a')\n-- 3\n-- >>> how_many_times('aaaa', 'aa')\n-- 3\nlocal function how_many_times(string, substring)\n local count = 0\n local start_index = 1\n while true do\n local index = string.find(string, substring, start_index)\n if index == nil then\n break\n end\n count = count + 1\n start_index = index + 1\n end\n return count\nend"], ["-- Input is a space-delimited string of numberals from 'zero' to 'nine'.\n-- Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n-- Return the string with numbers sorted from smallest to largest\n-- >>> sort_numbers('three one five')\n-- 'one three five'\nlocal function sort_numbers(numbers)\n local num_to_word = {\n ['zero'] = 0,\n ['one'] = 1,\n ['two'] = 2,\n ['three'] = 3,\n ['four'] = 4,\n ['five'] = 5,\n ['six'] = 6,\n ['seven'] = 7,\n ['eight'] = 8,\n ['nine'] = 9\n }\n local words = {}\n for word in numbers:gmatch(\"%S+\") do\n table.insert(words, word)\n end\n table.sort(words, function(a, b)\n return num_to_word[a] < num_to_word[b]\n end)\n return table.concat(words, \" \")\nend"], ["-- Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n-- separate those group into separate strings and return the table of those.\n-- Separate groups are balanced (each open brace is properly closed) and not nested within each other\n-- Ignore any spaces in the input string.\n-- >>> separate_paren_groups('( ) (( )) (( )( ))')\n-- {'()', '(())', '(()())'}\nlocal function separate_paren_groups(paren_string)\n local groups = {}\n local current_group = ''\n local open_count = 0\n for i = 1, #paren_string do\n local char = paren_string:sub(i, i)\n if char == '(' then\n open_count = open_count + 1\n elseif char == ')' then\n open_count = open_count - 1\n end\n if open_count == 0 then\n table.insert(groups, current_group)\n current_group = ''\n else\n current_group = current_group .. char\n end\n end\n return groups\nend"], ["-- From a supplied table of numbers (of length at least two) select and return two that are the closest to each\n-- other and return them in order (smaller number, larger number).\n-- >>> find_closest_elements({1.0, 2.0, 3.0, 4.0, 5.0, 2.2})\n-- {2.0, 2.2}\n-- >>> find_closest_elements({1.0, 2.0, 3.0, 4.0, 5.0, 2.0})\n-- {2.0, 2.0}\nlocal function find_closest_elements(numbers)\n local closest_distance = math.huge\n local closest_elements = {}\n for i = 1, #numbers do\n for j = i + 1, #numbers do\n local distance = math.abs(numbers[i] - numbers[j])\n if distance < closest_distance then\n closest_distance = distance\n closest_elements = {numbers[i], numbers[j]}\n end\n end\n end\n table.sort(closest_elements)\n return closest_elements\nend"], ["-- Given table of numbers (of at least two elements), apply a linear transform to that table,\n-- such that the smallest number will become 0 and the largest will become 1\n-- >>> rescale_to_unit({1.0, 2.0, 3.0, 4.0, 5.0})\n-- {0.0, 0.25, 0.5, 0.75, 1.0}\nlocal function rescale_to_unit(numbers)\n local min_num = math.min(unpack(numbers))\n local max_num = math.max(unpack(numbers))\n local range = max_num - min_num\n local rescaled_numbers = {}\n for i, num in ipairs(numbers) do\n rescaled_numbers[i] = (num - min_num) / range\n end\n return rescaled_numbers\nend"], ["-- Filter given table of any luathon values only for integers\n-- >>> filter_integers({'a', 3.14, 5})\n-- {5}\n-- >>> filter_integers({1, 2, 3, 'abc', {}, {}})\n-- {1, 2, 3}\nlocal function filter_integers(values)\n local integers = {}\n for i, value in ipairs(values) do\n if type(value) == 'number' and value == math.floor(value) then\n table.insert(integers, value)\n end\n end\n return integers\nend"], ["-- Return length of given string\n-- >>> strlen('')\n-- 0\n-- >>> strlen('abc')\n-- 3\nlocal function strlen(string)\n return #string\nend"], ["-- For a given number n, find the largest number that divides n evenly, smaller than n\n-- >>> largest_divisor(15)\n-- 5\nlocal function largest_divisor(n)\n for i = n - 1, 1, -1 do\n if n % i == 0 then\n return i\n end\n end\nend"], ["-- Return table of prime factors of given integer in the order from smallest to largest.\n-- Each of the factors should be tableed number of times corresponding to how many times it appeares in factorization.\n-- Input number should be equal to the product of all factors\n-- >>> factorize(8)\n-- {2, 2, 2}\n-- >>> factorize(25)\n-- {5, 5}\n-- >>> factorize(70)\n-- {2, 5, 7}\nlocal function factorize(n)\n local factors = {}\n local i = 2\n while i <= n do\n if n % i == 0 then\n table.insert(factors, i)\n n = n / i\n else\n i = i + 1\n end\n end\n return factors\nend"], ["-- From a table of integers, remove all elements that occur more than once.\n-- Keep order of elements left the same as in the input.\n-- >>> remove_duplicates({1, 2, 3, 2, 4})\n-- {1, 3, 4}\nlocal function remove_duplicates(numbers)\n local seen = {}\n local result = {}\n for _, num in ipairs(numbers) do\n if not seen[num] then\n table.insert(result, num)\n seen[num] = true\n end\n end\n return result\nend"], ["-- For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n-- >>> flip_case('Hello')\n-- 'hELLO'\nlocal function flip_case(string)\n local result = ''\n for i = 1, #string do\n local char = string:sub(i, i)\n if char:lower() == char then\n result = result .. char:upper()\n else\n result = result .. char:lower()\n end\n end\n return result\nend"], ["-- Concatenate table of strings into a single string\n-- >>> concatenate({})\n-- ''\n-- >>> concatenate({'a', 'b', 'c'})\n-- 'abc'\nlocal function concatenate(strings)\n local result = ''\n for _, s in ipairs(strings) do\n result = result .. s\n end\n return result\nend"], ["-- Filter an input table of strings only for ones that start with a given prefix.\n-- >>> filter_by_prefix({}, 'a')\n-- {}\n-- >>> filter_by_prefix({'abc', 'bcd', 'cde', 'array'}, 'a')\n-- {'abc', 'array'}\nlocal function filter_by_prefix(strings, prefix)\n local filtered = {}\n for _, str in ipairs(strings) do\n if str:sub(1, #prefix) == prefix then\n table.insert(filtered, str)\n end\n end\n return filtered\nend"], ["-- Given a positive floating point number, it can be decomposed into\n-- and integer part (largest integer smaller than given number) and decimals\n-- (leftover part always smaller than 1).\n-- Return the decimal part of the number.\n-- >>> truncate_number(3.5)\n-- 0.5\nlocal function truncate_number(number)\n local integer_part = math.floor(number)\n local decimal_part = number - integer_part\n return decimal_part\nend"], ["-- Return only positive numbers in the table.\n-- >>> get_positive({-1, 2, -4, 5, 6})\n-- {2, 5, 6}\n-- >>> get_positive({5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10})\n-- {5, 3, 2, 3, 9, 123, 1}\nlocal function get_positive(l)\n local result = {}\n for _, num in ipairs(l) do\n if num > 0 then\n table.insert(result, num)\n end\n end\n return result\nend"], ["-- Return true if a given number is prime, and false otherwise.\n-- >>> is_prime(6)\n-- false\n-- >>> is_prime(101)\n-- true\n-- >>> is_prime(11)\n-- true\n-- >>> is_prime(13441)\n-- true\n-- >>> is_prime(61)\n-- true\n-- >>> is_prime(4)\n-- false\n-- >>> is_prime(1)\n-- false\nlocal function is_prime(n)\n if n <= 1 then\n return false\n end\n for i = 2, math.sqrt(n) do\n if n % i == 0 then\n return false\n end\n end\n return true\nend"], ["-- This function takes a table l and returns a table l' such that\n-- l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n-- to the values of the corresponding indicies of l, but sorted.\n-- >>> sort_third({1, 2, 3})\n-- {1, 2, 3}\n-- >>> sort_third({5, 6, 3, 4, 8, 9, 2})\n-- {2, 6, 3, 4, 8, 9, 5}\nlocal function sort_third(l)\n local l_prime = {}\n local third_values = {}\n for i, v in ipairs(l) do\n if i % 3 == 0 then\n table.insert(third_values, v)\n end\n end\n table.sort(third_values)\n for i, v in ipairs(l) do\n if i % 3 == 0 then\n table.insert(l_prime, third_values[math.ceil(i/3)])\n else\n table.insert(l_prime, v)\n end\n end\n return l_prime\nend"], ["-- Return sorted unique elements in a table\n-- >>> unique({5, 3, 5, 2, 3, 3, 9, 0, 123})\n-- {0, 2, 3, 5, 9, 123}\nlocal function unique(l)\n local seen = {}\n local result = {}\n for _, v in ipairs(l) do\n if not seen[v] then\n seen[v] = true\n table.insert(result, v)\n end\n end\n table.sort(result)\n return result\nend"], ["-- Return maximum element in the table.\n-- >>> max_element({1, 2, 3})\n-- 3\n-- >>> max_element({5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10})\n-- 123\nlocal function max_element(l)\n local m = l[1]\n for i = 2, #l do\n if l[i] > m then\n m = l[i]\n end\n end\n return m\nend"], ["-- Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n-- >>> fizz_buzz(50)\n-- 0\n-- >>> fizz_buzz(78)\n-- 2\n-- >>> fizz_buzz(79)\n-- 3\nlocal function fizz_buzz(n)\n local count = 0\n for i = 1, n-1 do\n if (i % 11 == 0 or i % 13 == 0) and tostring(i):find(\"7\") then\n count = count + 1\n end\n end\n return count\nend\n"], ["-- This function takes a table l and returns a table l' such that\n-- l' is identical to l in the odd indicies, while its values at the even indicies are equal\n-- to the values of the even indicies of l, but sorted.\n-- >>> sort_even({1, 2, 3})\n-- {1, 2, 3}\n-- >>> sort_even({5, 6, 3, 4})\n-- {3, 6, 5, 4}\nlocal function sort_even(l)\n local l_even = {}\n for i = 2, #l, 2 do\n table.insert(l_even, l[i])\n end\n table.sort(l_even)\n local l_sorted = {}\n for i = 1, #l do\n if i % 2 == 0 then\n table.insert(l_sorted, l_even[i/2])\n else\n table.insert(l_sorted, l[i])\n end\n end\n return l_sorted\nend"], ["-- prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n-- >>> prime_fib(1)\n-- 2\n-- >>> prime_fib(2)\n-- 3\n-- >>> prime_fib(3)\n-- 5\n-- >>> prime_fib(4)\n-- 13\n-- >>> prime_fib(5)\n-- 89\nlocal function prime_fib(n)\n local fib = {1, 1}\n local i = 2\n while #fib < n do\n fib[i+1] = fib[i] + fib[i-1]\n i = i + 1\n end\n local prime = {}\n for j = 1, #fib do\n local is_prime = true\n for k = 2, math.floor(math.sqrt(fib[j])) do\n if fib[j] % k == 0 then\n is_prime = false\n break\n end\n end\n if is_prime then\n table.insert(prime, fib[j])\n end\n end\n return prime[n]\nend"], ["-- You're given a table of deposit and withdrawal operations on a bank account that starts with\n-- zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n-- at that point function should return true. Otherwise it should return false.\n-- >>> below_zero({1, 2, 3})\n-- false\n-- >>> below_zero({1, 2, -4, 5})\n-- true\nlocal function below_zero(operations)\n local balance = 0\n for _, op in ipairs(operations) do\n balance = balance + op\n if balance < 0 then\n return true\n end\n end\n return false\nend"], ["-- triples_sum_to_zero takes a table of integers as an input.\n-- it returns true if there are three distinct elements in the table that\n-- sum to zero, and false otherwise.\n-- >>> triples_sum_to_zero({1, 3, 5, 0})\n-- false\n-- >>> triples_sum_to_zero({1, 3, -2, 1})\n-- true\n-- >>> triples_sum_to_zero({1, 2, 3, 7})\n-- false\n-- >>> triples_sum_to_zero({2, 4, -5, 3, 9, 7})\n-- true\n-- >>> triples_sum_to_zero({1})\n-- false\nlocal function triples_sum_to_zero(l)\n local n = #l\n for i = 1, n-2 do\n for j = i+1, n-1 do\n for k = j+1, n do\n if l[i] + l[j] + l[k] == 0 then\n return true\n end\n end\n end\n end\n return false\nend\n"], ["-- Imagine a road that's a perfectly straight infinitely long line.\n-- n cars are driving left to right; simultaneously, a different set of n cars\n-- are driving right to left. The two sets of cars start out being very far from\n-- each other. All cars move in the same speed. Two cars are said to collide\n-- when a car that's moving left to right hits a car that's moving right to left.\n-- However, the cars are infinitely sturdy and strong; as a result, they continue moving\n-- in their trajectory as if they did not collide.\n-- This function outputs the number of such collisions.\nlocal function car_race_collision(n)\n return n\nend\n"], ["-- Return table with elements incremented by 1.\n-- >>> incr_list({1, 2, 3})\n-- {2, 3, 4}\n-- >>> incr_list({5, 3, 5, 2, 3, 3, 9, 0, 123})\n-- {6, 4, 6, 3, 4, 4, 10, 1, 124}\nlocal function incr_list(l)\n local new_l = {}\n for i, v in ipairs(l) do\n new_l[i] = v + 1\n end\n return new_l\nend"], ["-- pairs_sum_to_zero takes a table of integers as an input.\n-- it returns true if there are two distinct elements in the table that\n-- sum to zero, and false otherwise.\n-- >>> pairs_sum_to_zero({1, 3, 5, 0})\n-- false\n-- >>> pairs_sum_to_zero({1, 3, -2, 1})\n-- false\n-- >>> pairs_sum_to_zero({1, 2, 3, 7})\n-- false\n-- >>> pairs_sum_to_zero({2, 4, -5, 3, 5, 7})\n-- true\n-- >>> pairs_sum_to_zero({1})\n-- false\nlocal function pairs_sum_to_zero(l)\n local seen = {}\n for _, x in ipairs(l) do\n if seen[-x] then\n return true\n end\n seen[x] = true\n end\n return false\nend\n"], ["-- Change numerical base of input number x to base.\n-- return string representation after the conversion.\n-- base numbers are less than 10.\n-- >>> change_base(8, 3)\n-- '22'\n-- >>> change_base(8, 2)\n-- '1000'\n-- >>> change_base(7, 2)\n-- '111'\nlocal function change_base(x, base)\n local result = \"\"\n while x > 0 do\n local digit = x % base\n result = tostring(digit) .. result\n x = (x - digit) / base\n end\n return result\nend"], ["-- Given length of a side and high return area for a triangle.\n-- >>> triangle_area(5, 3)\n-- 7.5\nlocal function triangle_area(a, h)\n return (a * h) / 2\nend"], ["-- The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n-- fib4(0) -> 0\n-- fib4(1) -> 0\n-- fib4(2) -> 2\n-- fib4(3) -> 0\n-- fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n-- Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n-- >>> fib4(5)\n-- 4\n-- >>> fib4(6)\n-- 8\n-- >>> fib4(7)\n-- 14\nlocal function fib4(n)\n local fibs = {0, 0, 2, 0}\n for i = 4, n do\n fibs[i] = fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4]\n end\n return fibs[n]\nend"], ["-- Return median of elements in the table l.\n-- >>> median({3, 1, 2, 4, 5})\n-- 3\n-- >>> median({-10, 4, 6, 1000, 10, 20})\n-- 15.0\nlocal function median(l)\n local sorted = {}\n for _, v in ipairs(l) do\n table.insert(sorted, v)\n end\n table.sort(sorted)\n local n = #sorted\n if n % 2 == 1 then\n return sorted[(n + 1) / 2]\n else\n return (sorted[n / 2] + sorted[n / 2 + 1]) / 2\n end\nend"], ["-- Checks if given string is a palindrome\n-- >>> is_palindrome('')\n-- true\n-- >>> is_palindrome('aba')\n-- true\n-- >>> is_palindrome('aaaaa')\n-- true\n-- >>> is_palindrome('zbcd')\n-- false\nlocal function is_palindrome(text)\n local reversed = ''\n for i = #text, 1, -1 do\n reversed = reversed .. text:sub(i, i)\n end\n return text == reversed\nend"], ["-- Return 2^n modulo p (be aware of numerics).\n-- >>> modp(3, 5)\n-- 3\n-- >>> modp(1101, 101)\n-- 2\n-- >>> modp(0, 101)\n-- 1\n-- >>> modp(3, 11)\n-- 8\n-- >>> modp(100, 101)\n-- 1\nlocal function modp(n, p)\n return (2^n) % p\nend\n"], ["-- For a given table of input numbers, calculate Mean Absolute Deviation\n-- around the mean of this dataset.\n-- Mean Absolute Deviation is the average absolute difference between each\n-- element and a centerpoint (mean in this case):\n-- MAD = average | x - x_mean |\n-- >>> mean_absolute_deviation({1.0, 2.0, 3.0, 4.0})\n-- 1.0\nlocal function mean_absolute_deviation(numbers)\n local sum = 0\n local count = 0\n for _, number in ipairs(numbers) do\n sum = sum + number\n count = count + 1\n end\n local mean = sum / count\n local mad_sum = 0\n for _, number in ipairs(numbers) do\n mad_sum = mad_sum + math.abs(number - mean)\n end\n return mad_sum / count\nend"], ["-- remove_vowels is a function that takes string and returns string without vowels.\n-- >>> remove_vowels('')\n-- ''\n-- >>> remove_vowels('abcdef')\n-- 'bcdf'\n-- >>> remove_vowels('aaaaa')\n-- ''\n-- >>> remove_vowels('aaBAA')\n-- 'B'\n-- >>> remove_vowels('zbcd')\n-- 'zbcd'\nlocal function remove_vowels(text)\n local vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }\n local result = ''\n for i = 1, #text do\n local char = text:sub(i, i)\n if not table.contains(vowels, char) then\n result = result .. char\n end\n end\n return result\nend"], ["-- Return true if all numbers in the table l are below threshold t.\n-- >>> below_threshold({1, 2, 4, 10}, 100)\n-- true\n-- >>> below_threshold({1, 20, 4, 10}, 5)\n-- false\nlocal function below_threshold(l, t)\n for _, n in ipairs(l) do\n if n >= t then\n return false\n end\n end\n return true\nend"], ["-- Add two numbers x and y\n-- >>> add(2, 3)\n-- 5\n-- >>> add(5, 7)\n-- 12\nlocal function add(x, y)\n return x + y\nend"], ["-- Check if two words have the same characters.\n-- >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n-- true\n-- >>> same_chars('abcd', 'dddddddabc')\n-- true\n-- >>> same_chars('dddddddabc', 'abcd')\n-- true\n-- >>> same_chars('eabcd', 'dddddddabc')\n-- false\n-- >>> same_chars('abcd', 'dddddddabce')\n-- false\n-- >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n-- false\nlocal function same_chars(s0, s1)\n local t0 = {}\n local t1 = {}\n for i = 1, #s0 do\n t0[s0:sub(i, i)] = (t0[s0:sub(i, i)] or 0) + 1\n end\n for i = 1, #s1 do\n t1[s1:sub(i, i)] = (t1[s1:sub(i, i)] or 0) + 1\n end\n for k, v in pairs(t0) do\n if t1[k] ~= v then\n return false\n end\n end\n for k, v in pairs(t1) do\n if t0[k] ~= v then\n return false\n end\n end\n return true\nend\n"], ["-- Return n-th Fibonacci number.\n-- >>> fib(10)\n-- 55\n-- >>> fib(1)\n-- 1\n-- >>> fib(8)\n-- 21\nlocal function fib(n)\n if n == 0 then\n return 0\n elseif n == 1 then\n return 1\n else\n local a, b = 0, 1\n for i = 2, n do\n local c = a + b\n a = b\n b = c\n end\n return b\n end\nend"], ["-- brackets is a string of \"<\" and \">\".\n-- return true if every opening bracket has a corresponding closing bracket.\n-- >>> correct_bracketing('<')\n-- false\n-- >>> correct_bracketing('<>')\n-- true\n-- >>> correct_bracketing('<<><>>')\n-- true\n-- >>> correct_bracketing('><<>')\n-- false\nlocal function correct_bracketing(brackets)\n local count = 0\n for i = 1, #brackets do\n if brackets:sub(i, i) == \"<\" then\n count = count + 1\n else\n count = count - 1\n if count < 0 then\n return false\n end\n end\n end\n return count == 0\nend\n"], ["-- Return true is table elements are monotonically increasing or decreasing.\n-- >>> monotonic({1, 2, 4, 20})\n-- true\n-- >>> monotonic({1, 20, 4, 10})\n-- false\n-- >>> monotonic({4, 1, 0, -10})\n-- true\nlocal function monotonic(l)\n local increasing = true\n local decreasing = true\n for i = 2, #l do\n if l[i] > l[i-1] then\n decreasing = false\n elseif l[i] < l[i-1] then\n increasing = false\n end\n end\n return increasing or decreasing\nend"], ["-- Return sorted unique common elements for two tables.\n-- >>> common({1, 4, 3, 34, 653, 2, 5}, {5, 7, 1, 5, 9, 653, 121})\n-- {1, 5, 653}\n-- >>> common({5, 3, 2, 8}, {3, 2})\n-- {2, 3}\nlocal function common(l1, l2)\n local common_elements = {}\n for _, element in ipairs(l1) do\n if l2[element] then\n common_elements[element] = true\n end\n end\n local sorted_common_elements = {}\n for element in pairs(common_elements) do\n table.insert(sorted_common_elements, element)\n end\n table.sort(sorted_common_elements)\n return sorted_common_elements\nend"], ["-- Return the largest prime factor of n. Assume n > 1 and is not a prime.\n-- >>> largest_prime_factor(13195)\n-- 29\n-- >>> largest_prime_factor(2048)\n-- 2\nlocal function largest_prime_factor(n)\n local factor = 2\n while n % factor ~= 0 do\n factor = factor + 1\n end\n if n == factor then\n return factor\n else\n return largest_prime_factor(n / factor)\n end\nend"], ["-- Insert a number 'delimeter' between every two consecutive elements of input table `numbers'\n-- >>> intersperse({}, 4)\n-- {}\n-- >>> intersperse({1, 2, 3}, 4)\n-- {1, 4, 2, 4, 3}\nlocal function intersperse(numbers, delimeter)\n local result = {}\n for i, number in ipairs(numbers) do\n table.insert(result, number)\n if i < #numbers then\n table.insert(result, delimeter)\n end\n end\n return result\nend\n"], ["-- sum_to_n is a function that sums numbers from 1 to n.\n-- >>> sum_to_n(30)\n-- 465\n-- >>> sum_to_n(100)\n-- 5050\n-- >>> sum_to_n(5)\n-- 15\n-- >>> sum_to_n(10)\n-- 55\n-- >>> sum_to_n(1)\n-- 1\nlocal function sum_to_n(n)\n local sum = 0\n for i = 1, n do\n sum = sum + i\n end\n return sum\nend"], ["-- brackets is a string of \"(\" and \")\".\n-- return true if every opening bracket has a corresponding closing bracket.\n-- >>> correct_bracketing('(')\n-- false\n-- >>> correct_bracketing('()')\n-- true\n-- >>> correct_bracketing('(()())')\n-- true\n-- >>> correct_bracketing(')(()')\n-- false\nlocal function correct_bracketing(brackets)\n local count = 0\n for i = 1, #brackets do\n if brackets:sub(i, i) == \"(\" then\n count = count + 1\n elseif brackets:sub(i, i) == \")\" then\n count = count - 1\n end\n if count < 0 then\n return false\n end\n end\n return count == 0\nend\n"], ["-- xs represent coefficients of a polynomial.\n-- xs[0] + xs[1] * x + xs[2] * x^2 + ....\n-- Return derivative of this polynomial in the same form.\n-- >>> derivative({3, 1, 2, 4, 5})\n-- {1, 4, 12, 20}\n-- >>> derivative({1, 2, 3})\n-- {2, 6}\nlocal function derivative(xs)\n local result = {}\n for i = 1, #xs - 1 do\n table.insert(result, i * xs[i])\n end\n return result\nend"], ["-- The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n-- fibfib(0) == 0\n-- fibfib(1) == 0\n-- fibfib(2) == 1\n-- fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n-- Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n-- >>> fibfib(1)\n-- 0\n-- >>> fibfib(5)\n-- 4\n-- >>> fibfib(8)\n-- 24\nlocal function fibfib(n)\n if n == 0 then\n return 0\n elseif n == 1 then\n return 0\n elseif n == 2 then\n return 1\n else\n local a, b, c = 0, 0, 1\n for i = 3, n do\n local d = a + b + c\n a, b, c = b, c, d\n end\n return c\n end\nend"], ["-- Write a function vowels_count which takes a string representing\n-- a word as input and returns the number of vowels in the string.\n-- Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n-- vowel, but only when it is at the end of the given word.\n-- Example:\n-- >>> vowels_count('abcde')\n-- 2\n-- >>> vowels_count('ACEDY')\n-- 3\nlocal function vowels_count(s)\n local count = 0\n for i = 1, #s do\n local c = string.lower(s:sub(i, i))\n if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' then\n count = count + 1\n end\n end\n return count\nend"], ["-- Circular shift the digits of the integer x, shift the digits right by shift\n-- and return the result as a string.\n-- If shift > number of digits, return digits reversed.\n-- >>> circular_shift(12, 1)\n-- '21'\n-- >>> circular_shift(12, 2)\n-- '12'\nlocal function circular_shift(x, shift)\n local digits = {}\n while x > 0 do\n table.insert(digits, 1, x % 10)\n x = math.floor(x / 10)\n end\n if shift > #digits then\n shift = #digits\n end\n local shifted_digits = {}\n for i = 1, #digits do\n local index = (i + shift - 1) % #digits + 1\n table.insert(shifted_digits, digits[index])\n end\n return table.concat(shifted_digits)\nend"], ["-- Task\n-- Write a function that takes a string as input and returns the sum of the upper characters only'\n-- ASCII codes.\n-- Examples:\n-- >>> digitSum('')\n-- 0\n-- >>> digitSum('abAB')\n-- 131\n-- >>> digitSum('abcCd')\n-- 67\n-- >>> digitSum('helloE')\n-- 69\n-- >>> digitSum('woArBld')\n-- 131\n-- >>> digitSum('aAaaaXa')\n-- 153\nlocal function digitSum(s)\n local sum = 0\n for i = 1, #s do\n local c = string.byte(s, i)\n if c >= 65 and c <= 90 then\n sum = sum + c\n end\n end\n return sum\nend\n"], ["-- In this task, you will be given a string that represents a number of apples and oranges \n-- that are distributed in a basket of fruit this basket contains \n-- apples, oranges, and mango fruits. Given the string that represents the total number of \n-- the oranges and apples and an integer that represent the total number of the fruits \n-- in the basket return the number of the mango fruits in the basket.\n-- for examble:\n-- >>> fruit_distribution('5 apples and 6 oranges', 19)\n-- 8\n-- >>> fruit_distribution('0 apples and 1 oranges', 3)\n-- 2\n-- >>> fruit_distribution('2 apples and 3 oranges', 100)\n-- 95\n-- >>> fruit_distribution('100 apples and 1 oranges', 120)\n-- 19\nlocal function fruit_distribution(s, n)\n local apples, oranges = s:match(\"(%d+) apples and (%d+) oranges\")\n local total_fruits = apples + oranges\n return n - total_fruits\nend\n"], ["-- \"Given a table representing a branch of a tree that has non-negative integer nodes\n-- your task is to pluck one of the nodes and return it.\n-- The plucked node should be the node with the smallest even value.\n-- If multiple nodes with the same smallest even value are found return the node that has smallest index.\n-- The plucked node should be returned in a table, [ smalest_value, its index ],\n-- If there are no even values or the given table is empty, return [].\n-- Example 1:\n-- >>> pluck({4, 2, 3})\n-- {2, 1}\n-- Explanation: 2 has the smallest even value, and 2 has the smallest index.\n-- Example 2:\n-- >>> pluck({1, 2, 3})\n-- {2, 1}\n-- Explanation: 2 has the smallest even value, and 2 has the smallest index.\n-- Example 3:\n-- >>> pluck({})\n-- {}\n-- Example 4:\n-- >>> pluck({5, 0, 3, 0, 4, 2})\n-- {0, 1}\n-- Explanation: 0 is the smallest value, but there are two zeros,\n-- so we will choose the first zero, which has the smallest index.\n-- Constraints:\n-- * 1 <= nodes.length <= 10000\n-- * 0 <= node.value\nlocal function pluck(arr)\n local smallest_even = math.huge\n local smallest_index = -1\n for i, v in ipairs(arr) do\n if v % 2 == 0 and v < smallest_even then\n smallest_even = v\n smallest_index = i\n end\n end\n if smallest_index == -1 then\n return {}\n else\n return {smallest_even, smallest_index}\n end\nend\n"], ["-- You are given a non-empty table of positive integers. Return the greatest integer that is greater than \n-- zero, and has a frequency greater than or equal to the value of the integer itself. \n-- The frequency of an integer is the number of times it appears in the table.\n-- If no such a value exist, return -1.\n-- Examples:\n-- >>> search({4, 1, 2, 2, 3, 1})\n-- 2\n-- >>> search({1, 2, 2, 3, 3, 3, 4, 4, 4})\n-- 3\n-- >>> search({5, 5, 4, 4, 4})\n-- -1\nlocal function search(lst)\n local freq = {}\n for _, num in ipairs(lst) do\n freq[num] = (freq[num] or 0) + 1\n end\n for i = #lst, 1, -1 do\n if freq[i] >= i then\n return i\n end\n end\n return -1\nend\n"], ["-- Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n-- For each of the group, output the deepest level of nesting of parentheses.\n-- E.g. (()()) has maximum two levels of nesting while ((())) has three.\n-- >>> parse_nested_parens('(()()) ((())) () ((())()())')\n-- {2, 3, 1, 3}\nlocal function parse_nested_parens(paren_string)\n local max_depth = 0\n local current_depth = 0\n local depths = {}\n for i = 1, #paren_string do\n local char = paren_string:sub(i, i)\n if char == '(' then\n current_depth = current_depth + 1\n if current_depth > max_depth then\n max_depth = current_depth\n end\n elseif char == ')' then\n current_depth = current_depth - 1\n elseif char == ' ' then\n table.insert(depths, max_depth)\n max_depth = 0\n current_depth = 0\n end\n end\n table.insert(depths, max_depth)\n return depths\nend"], ["-- Given table of integers, return table in strange order.\n-- Strange sorting, is when you start with the minimum value,\n-- then maximum of the remaining integers, then minimum and so on.\n-- Examples:\n-- >>> strange_sort_list({1, 2, 3, 4})\n-- {1, 4, 2, 3}\n-- >>> strange_sort_list({5, 5, 5, 5})\n-- {5, 5, 5, 5}\n-- >>> strange_sort_list({})\n-- {}\nlocal function strange_sort_list(lst)\n local sorted = {}\n while #lst > 0 do\n table.insert(sorted, table.remove(lst, 1))\n if #lst > 0 then\n local max_val = math.max(unpack(lst))\n local max_idx = table.indexof(lst, max_val)\n table.insert(sorted, table.remove(lst, max_idx))\n end\n end\n return sorted\nend\n"], ["-- Given the lengths of the three sides of a triangle. Return the area of\n-- the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n-- Otherwise return -1\n-- Three sides make a valid triangle when the sum of any two sides is greater \n-- than the third side.\n-- Example:\n-- >>> triangle_area(3, 4, 5)\n-- 6.0\n-- >>> triangle_area(1, 2, 10)\n-- -1\nlocal function triangle_area(a, b, c)\n if a + b > c and a + c > b and b + c > a then\n local s = (a + b + c) / 2\n local area = math.sqrt(s * (s - a) * (s - b) * (s - c))\n return math.floor(area * 100 + 0.5) / 100\n else\n return -1\n end\nend"], ["-- Write a function that returns true if the object q will fly, and false otherwise.\n-- The object q will fly if it's balanced (it is a palindromic table) and the sum of its elements is less than or equal the maximum possible weight w.\n-- Example:\n-- >>> will_it_fly({1, 2}, 5)\n-- false\n-- # 1+2 is less than the maximum possible weight, but it's unbalanced.\n-- >>> will_it_fly({3, 2, 3}, 1)\n-- false\n-- # it's balanced, but 3+2+3 is more than the maximum possible weight.\n-- >>> will_it_fly({3, 2, 3}, 9)\n-- true\n-- # 3+2+3 is less than the maximum possible weight, and it's balanced.\n-- >>> will_it_fly({3}, 5)\n-- true\n-- # 3 is less than the maximum possible weight, and it's balanced.\nlocal function will_it_fly(q, w)\n local sum = 0\n for i = 1, #q do\n sum = sum + q[i]\n end\n if sum > w then\n return false\n end\n for i = 1, #q/2 do\n if q[i] ~= q[#q-i+1] then\n return false\n end\n end\n return true\nend\n"], ["-- Given a table arr of integers, find the minimum number of elements that\n-- need to be changed to make the table palindromic. A palindromic table is a table that\n-- is read the same backwards and forwards. In one change, you can change one element to any other element.\n-- For example:\n-- >>> smallest_change({1, 2, 3, 5, 4, 7, 9, 6})\n-- 4\n-- >>> smallest_change({1, 2, 3, 4, 3, 2, 2})\n-- 1\n-- >>> smallest_change({1, 2, 3, 2, 1})\n-- 0\nlocal function smallest_change(arr)\n local n = #arr\n local count = 0\n for i = 1, n/2 do\n if arr[i] ~= arr[n-i+1] then\n count = count + 1\n end\n end\n return count\nend"], ["-- Write a function that accepts two tables of strings and returns the table that has \n-- total number of chars in the all strings of the table less than the other table.\n-- if the two tables have the same number of chars, return the first table.\n-- Examples\n-- >>> total_match({}, {})\n-- {}\n-- >>> total_match({'hi', 'admin'}, {'hI', 'Hi'})\n-- {'hI', 'Hi'}\n-- >>> total_match({'hi', 'admin'}, {'hi', 'hi', 'admin', 'project'})\n-- {'hi', 'admin'}\n-- >>> total_match({'hi', 'admin'}, {'hI', 'hi', 'hi'})\n-- {'hI', 'hi', 'hi'}\n-- >>> total_match({'4'}, {'1', '2', '3', '4', '5'})\n-- {'4'}\nlocal function total_match(lst1, lst2)\n local total1 = 0\n local total2 = 0\n for _, str in ipairs(lst1) do\n total1 = total1 + #str\n end\n for _, str in ipairs(lst2) do\n total2 = total2 + #str\n end\n if total1 < total2 then\n return lst1\n elseif total1 > total2 then\n return lst2\n else\n return lst1\n end\nend\n"], ["-- Write a function that returns true if the given number is the multiplication of 3 prime numbers\n-- and false otherwise.\n-- Knowing that (a) is less then 100. \n-- Example:\n-- >>> is_multiply_prime(30)\n-- true\n-- 30 = 2 * 3 * 5\nlocal function is_multiply_prime(a)\n local 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}\n local count = 0\n for i = 1, #primes do\n if a % primes[i] == 0 then\n count = count + 1\n a = a / primes[i]\n if count == 3 then\n return true\n end\n end\n end\n return false\nend"], ["-- Your task is to write a function that returns true if a number x is a simple\n-- power of n and false in other cases.\n-- x is a simple power of n if n**int=x\n-- For example:\n-- >>> is_simple_power(1, 4)\n-- true\n-- >>> is_simple_power(2, 2)\n-- true\n-- >>> is_simple_power(8, 2)\n-- true\n-- >>> is_simple_power(3, 2)\n-- false\n-- >>> is_simple_power(3, 1)\n-- false\n-- >>> is_simple_power(5, 3)\n-- false\nlocal function is_simple_power(x, n)\n if x == 1 then\n return true\n end\n local i = 1\n while n^i <= x do\n if n^i == x then\n return true\n end\n i = i + 1\n end\n return false\nend\n"], ["-- Write a function that takes an integer a and returns true \n-- if this ingeger is a cube of some integer number.\n-- Note: you may assume the input is always valid.\n-- Examples:\n-- >>> iscube(1)\n-- true\n-- >>> iscube(2)\n-- false\n-- >>> iscube(-1)\n-- true\n-- >>> iscube(64)\n-- true\n-- >>> iscube(0)\n-- true\n-- >>> iscube(180)\n-- false\nlocal function iscube(a)\n local cube_root = math.pow(math.abs(a), 1/3)\n local rounded_cube_root = math.floor(cube_root + 0.5)\n return rounded_cube_root * rounded_cube_root * rounded_cube_root == a\nend\n"], ["-- You have been tasked to write a function that receives \n-- a hexadecimal number as a string and counts the number of hexadecimal \n-- digits that are primes (prime number, or a prime, is a natural number \n-- greater than 1 that is not a product of two smaller natural numbers).\n-- Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n-- Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n-- So you have to determine a number of the following digits: 2, 3, 5, 7, \n-- B (=decimal 11), D (=decimal 13).\n-- Note: you may assume the input is always correct or empty string, \n-- and symbols A,B,C,D,E,F are always uppercase.\n-- Examples:\n-- >>> hex_key('AB')\n-- 1\n-- >>> hex_key('1077E')\n-- 2\n-- >>> hex_key('ABED1A33')\n-- 4\n-- >>> hex_key('123456789ABCDEF0')\n-- 6\n-- >>> hex_key('2020')\n-- 2\nlocal function hex_key(num)\n local primes = {2, 3, 5, 7, 11, 13}\n local count = 0\n for i = 1, #num do\n local digit = tonumber(num:sub(i, i), 16)\n if primes[digit] then\n count = count + 1\n end\n end\n return count\nend\n"], ["-- You will be given a number in decimal form and your task is to convert it to\n-- binary format. The function should return a string, with each character representing a binary\n-- number. Each character in the string will be '0' or '1'.\n-- There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n-- The extra characters are there to help with the format.\n-- Examples:\n-- >>> decimal_to_binary(15)\n-- 'db1111db'\n-- >>> decimal_to_binary(32)\n-- 'db100000db'\nlocal function decimal_to_binary(decimal)\n local binary = \"\"\n while decimal > 0 do\n binary = tostring(decimal % 2) .. binary\n decimal = math.floor(decimal / 2)\n end\n return \"db\" .. binary .. \"db\"\nend"], ["-- Filter an input table of strings only for ones that contain given substring\n-- >>> filter_by_substring({}, 'a')\n-- {}\n-- >>> filter_by_substring({'abc', 'bacd', 'cde', 'array'}, 'a')\n-- {'abc', 'bacd', 'array'}\nlocal function filter_by_substring(strings, substring)\n local filtered = {}\n for _, str in ipairs(strings) do\n if string.find(str, substring) then\n table.insert(filtered, str)\n end\n end\n return filtered\nend\n"], ["-- You are given a string s.\n-- Your task is to check if the string is haplua or not.\n-- A string is haplua if its length is at least 3 and every 3 consecutive letters are distinct\n-- For example:\n-- >>> is_happy('a')\n-- false\n-- >>> is_happy('aa')\n-- false\n-- >>> is_happy('abcd')\n-- true\n-- >>> is_happy('aabb')\n-- false\n-- >>> is_happy('adb')\n-- true\n-- >>> is_happy('xyy')\n-- false\nlocal function is_happy(s)\n if string.len(s) < 3 then\n return false\n end\n for i = 1, string.len(s) - 2 do\n if s:sub(i, i + 2):find('^%a%a%a$') == nil then\n return false\n end\n end\n return true\nend\n"], ["-- It is the last week of the semester and the teacher has to give the grades\n-- to students. The teacher has been making her own algorithm for grading.\n-- The only problem is, she has lost the code she used for grading.\n-- She has given you a table of GPAs for some students and you have to write \n-- a function that can output a table of letter grades using the following table:\n-- GPA | Letter grade\n-- 4.0 A+\n-- > 3.7 A \n-- > 3.3 A- \n-- > 3.0 B+\n-- > 2.7 B \n-- > 2.3 B-\n-- > 2.0 C+\n-- > 1.7 C\n-- > 1.3 C-\n-- > 1.0 D+ \n-- > 0.7 D \n-- > 0.0 D-\n-- 0.0 E\n-- Example:\n-- >>> grade_equation({4.0, 3, 1.7, 2, 3.5})\n-- {'A+', 'B', 'C-', 'C', 'A-'}\nlocal function numerical_letter_grade(grades)\n local letter_grades = {}\n for _, gpa in ipairs(grades) do\n if gpa == 4.0 then\n table.insert(letter_grades, \"A+\")\n elseif gpa > 3.7 then\n table.insert(letter_grades, \"A\")\n elseif gpa > 3.3 then\n table.insert(letter_grades, \"A-\")\n elseif gpa > 3.0 then\n table.insert(letter_grades, \"B+\")\n elseif gpa > 2.7 then\n table.insert(letter_grades, \"B\")\n elseif gpa > 2.3 then\n table.insert(letter_grades, \"B-\")\n elseif gpa > 2.0 then\n table.insert(letter_grades, \"C+\")\n elseif gpa > 1.7 then\n table.insert(letter_grades, \"C\")\n elseif gpa > 1.3 then\n table.insert(letter_grades, \"C-\")\n elseif gpa > 1.0 then\n table.insert(letter_grades, \"D+\")\n elseif gpa > 0.7 then\n table.insert(letter_grades, \"D\")\n elseif gpa > 0.0 then\n table.insert(letter_grades, \"D-\")\n else\n table.insert(letter_grades, \"E\")\n end\n end\n return letter_grades\nend"], ["-- Write a function that takes a string and returns true if the string\n-- length is a prime number or false otherwise\n-- Examples\n-- >>> prime_length('Hello')\n-- true\n-- >>> prime_length('abcdcba')\n-- true\n-- >>> prime_length('kittens')\n-- true\n-- >>> prime_length('orange')\n-- false\nlocal function prime_length(string)\n local length = string.len(string)\n if length < 2 then\n return false\n end\n for i = 2, math.sqrt(length) do\n if length % i == 0 then\n return false\n end\n end\n return true\nend\n"], ["-- Given a positive integer n, return the count of the numbers of n-digit\n-- positive integers that start or end with 1.\nlocal function starts_one_ends(n)\n if n == 1 then\n return 1\n else\n return 2 * (10^(n-2))\n end\nend\n"], ["-- Given a positive integer N, return the total sum of its digits in binary.\n-- Example\n-- >>> solve(1000)\n-- '1'\n-- >>> solve(150)\n-- '110'\n-- >>> solve(147)\n-- '1100'\n-- Variables:\n-- @N integer\n-- Constraints: 0 \u2264 N \u2264 10000.\n-- Output:\n-- a string of binary number\nlocal function solve(N)\n local sum = 0\n while N > 0 do\n sum = sum + N % 2\n N = math.floor(N / 2)\n end\n return string.format(\"%b\", sum)\nend\n"], ["-- Given a non-empty table of integers lst. add the even elements that are at odd indices..\n-- Examples:\n-- >>> add({4, 2, 6, 7})\n-- 2\nlocal function add(lst)\n local sum = 0\n for i = 1, #lst, 2 do\n if lst[i] % 2 == 0 then\n sum = sum + lst[i]\n end\n end\n return sum\nend\n"], ["-- Write a function that takes a string and returns an ordered version of it.\n-- Ordered version of string, is a string where all words (separated by space)\n-- are replaced by a new word where all the characters arranged in\n-- ascending order based on ascii value.\n-- Note: You should keep the order of words and blank spaces in the sentence.\n-- For example:\n-- >>> anti_shuffle('Hi')\n-- 'Hi'\n-- >>> anti_shuffle('hello')\n-- 'ehllo'\n-- >>> anti_shuffle('Hello World!!!')\n-- 'Hello !!!Wdlor'\nlocal function anti_shuffle(s)\n local words = {}\n for word in s:gmatch(\"%S+\") do\n local chars = {}\n for char in word:gmatch(\".\") do\n table.insert(chars, char)\n end\n table.sort(chars)\n table.insert(words, table.concat(chars))\n end\n return table.concat(words, \" \")\nend"], ["-- You are given a 2 dimensional data, as a nested tables,\n-- which is similar to matrix, however, unlike matrices,\n-- each row may contain a different number of columns.\n-- Given lst, and integer x, find integers x in the table,\n-- and return table of tables, [(x1, y1), (x2, y2) ...] such that\n-- each table is a coordinate - (row, columns), starting with 0.\n-- Sort coordinates initially by rows in ascending order.\n-- Also, sort coordinates of the row by columns in descending order.\n-- Examples:\n-- >>> get_row({{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 1, 6}, {1, 2, 3, 4, 5, 1}}, 1)\n-- {{0, 0}, {1, 4}, {1, 0}, {2, 5}, {2, 0}}\n-- >>> get_row({}, 1)\n-- {}\n-- >>> get_row({{}, {1}, {1, 2, 3}}, 3)\n-- {{2, 2}}\nlocal function get_row(lst, x)\n local result = {}\n for i, row in ipairs(lst) do\n for j, val in ipairs(row) do\n if val == x then\n table.insert(result, {i - 1, j - 1})\n end\n end\n end\n table.sort(result, function(a, b)\n if a[1] == b[1] then\n return a[2] > b[2]\n else\n return a[1] < b[1]\n end\n end)\n return result\nend\n"], ["-- Given a table of non-negative integers, return a colua of the given table after sorting,\n-- you will sort the given table in ascending order if the sum( first index value, last index value) is odd,\n-- or sort it in descending order if the sum( first index value, last index value) is even.\n-- Note:\n-- * don't change the given table.\n-- Examples:\n-- >>> sort_array({})\n-- {}\n-- >>> sort_array({5})\n-- {5}\n-- >>> sort_array({2, 4, 3, 0, 1, 5})\n-- {0, 1, 2, 3, 4, 5}\n-- >>> sort_array({2, 4, 3, 0, 1, 5, 6})\n-- {6, 5, 4, 3, 2, 1, 0}\nlocal function sort_array(array)\n local sum = array[1] + array[#array]\n local sorted_array = {}\n for _, value in ipairs(array) do\n table.insert(sorted_array, value)\n end\n if sum % 2 == 0 then\n table.sort(sorted_array, function(a, b) return a > b end)\n else\n table.sort(sorted_array)\n end\n return sorted_array\nend\n"], ["-- Create a function encrypt that takes a string as an argument and\n-- returns a string encrypted with the alphabet being rotated. \n-- The alphabet should be rotated in a manner such that the letters \n-- shift down by two multiplied to two places.\n-- For example:\n-- >>> encrypt('hi')\n-- 'lm'\n-- >>> encrypt('asdfghjkl')\n-- 'ewhjklnop'\n-- >>> encrypt('gf')\n-- 'kj'\n-- >>> encrypt('et')\n-- 'ix'\nlocal function encrypt(s)\n local encrypted = ''\n for i = 1, #s do\n local c = string.byte(s, i)\n if c >= 97 and c <= 122 then\n c = c + 2*2\n if c > 122 then\n c = c - 26\n end\n end\n encrypted = encrypted .. string.char(c)\n end\n return encrypted\nend\n"], ["-- For a given table of integers, return a table consisting of a sum and a product of all the integers in a table.\n-- Empty sum should be equal to 0 and empty product should be equal to 1.\n-- >>> sum_product({})\n-- {0, 1}\n-- >>> sum_product({1, 2, 3, 4})\n-- {10, 24}\nlocal function sum_product(numbers)\n local sum = 0\n local product = 1\n for _, number in ipairs(numbers) do\n sum = sum + number\n product = product * number\n end\n return {sum, product}\nend"], ["-- You are given a table of integers.\n-- Write a function next_smallest() that returns the 2nd smallest element of the table.\n-- Return nil if there is no such element.\n-- >>> next_smallest({1, 2, 3, 4, 5})\n-- 2\n-- >>> next_smallest({5, 1, 4, 3, 2})\n-- 2\n-- >>> next_smallest({})\n-- None\n-- >>> next_smallest({1, 1})\n-- None\nlocal function next_smallest(lst)\n local smallest = math.huge\n local second_smallest = math.huge\n for _, num in ipairs(lst) do\n if num < smallest then\n second_smallest = smallest\n smallest = num\n elseif num < second_smallest and num != smallest then\n second_smallest = num\n end\n end\n if second_smallest == math.huge then\n return nil\n else\n return second_smallest\n end\nend"], ["-- You'll be given a string of words, and your task is to count the number\n-- of boredoms. A boredom is a sentence that starts with the word \"I\".\n-- Sentences are delimited by '.', '?' or '!'.\n-- For example:\n-- >>> is_bored('Hello world')\n-- 0\n-- >>> is_bored('The sky is blue. The sun is shining. I love this weather')\n-- 1\nlocal function is_bored(S)\n local count = 0\n local sentence = ''\n for i = 1, #S do\n local c = S:sub(i, i)\n if c == '.' or c == '?' or c == '!' then\n if sentence:sub(1, 2) == 'I ' then\n count = count + 1\n end\n sentence = ''\n else\n sentence = sentence .. c\n end\n end\n return count\nend\n"], ["-- Create a function that takes 3 numbers.\n-- Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n-- Returns false in any other cases.\n-- Examples\n-- >>> any_int(5, 2, 7)\n-- true\n-- >>> any_int(3, 2, 2)\n-- false\n-- >>> any_int(3, -2, 1)\n-- true\n-- >>> any_int(3.6, -2.2, 2)\n-- false\nlocal function any_int(x, y, z)\n -- Check if all numbers are integers\n if math.floor(x) == x and math.floor(y) == y and math.floor(z) == z then\n -- Check if one of the numbers is equal to the sum of the other two\n if x == y + z or y == x + z or z == x + y then\n return true\n end\n end\n return false\nend"], ["-- Write a function that takes a message, and encodes in such a \n-- way that it swaps case of all letters, replaces all vowels in \n-- the message with the letter that appears 2 places ahead of that \n-- vowel in the english alphabet. \n-- Assume only letters. \n-- Examples:\n-- >>> encode('test')\n-- 'TGST'\n-- >>> encode('This is a message')\n-- 'tHKS KS C MGSSCGG'\nlocal function encode(message)\n local vowels = {'a', 'e', 'i', 'o', 'u'}\n local encoded = ''\n for i = 1, #message do\n local char = message:sub(i, i)\n if char:lower() == char then\n char = char:upper()\n else\n char = char:lower()\n end\n if vowels[char] then\n local index = vowels[char] + 2\n if index > 5 then\n index = index - 5\n end\n char = vowels[index]\n end\n encoded = encoded .. char\n end\n return encoded\nend"], ["-- You are given a table of integers.\n-- You need to find the largest prime value and return the sum of its digits.\n-- Examples:\n-- >>> skjkasdkd({0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3})\n-- 10\n-- >>> skjkasdkd({1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1})\n-- 25\n-- >>> skjkasdkd({1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3})\n-- 13\n-- >>> skjkasdkd({0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6})\n-- 11\n-- >>> skjkasdkd({0, 81, 12, 3, 1, 21})\n-- 3\n-- >>> skjkasdkd({0, 8, 1, 2, 1, 7})\n-- 7\nlocal function skjkasdkd(lst)\n local largest_prime = 0\n for _, num in ipairs(lst) do\n if num > largest_prime and is_prime(num) then\n largest_prime = num\n end\n end\n local sum_of_digits = 0\n while largest_prime > 0 do\n sum_of_digits = sum_of_digits + largest_prime % 10\n largest_prime = math.floor(largest_prime / 10)\n end\n return sum_of_digits\nend"], ["-- Given a table, return true if all keys are strings in lower \n-- case or all keys are strings in upper case, else return false.\n-- The function should return false is the given table is empty.\n-- Examples:\n-- >>> check_dict_case({['a'] = 'apple', ['b'] = 'banana'})\n-- true\n-- >>> check_dict_case({['a'] = 'apple', ['A'] = 'banana', ['B'] = 'banana'})\n-- false\n-- >>> check_dict_case({['a'] = 'apple', [8] = 'banana', ['a'] = 'apple'})\n-- false\n-- >>> check_dict_case({['Name'] = 'John', ['Age'] = '36', ['City'] = 'Houston'})\n-- false\n-- >>> check_dict_case({['STATE'] = 'NC', ['ZIP'] = '12345'})\n-- true\nlocal function check_dict_case(dict)\n if next(dict) == nil then\n return false\n end\n local is_lower = true\n local is_upper = true\n for k, v in pairs(dict) do\n if type(k) ~= 'string' then\n return false\n end\n if not k:match('^[a-z]+$') then\n is_lower = false\n end\n if not k:match('^[A-Z]+$') then\n is_upper = false\n end\n end\n return is_lower or is_upper\nend\n"], ["-- Implement a function that takes an non-negative integer and returns a table of the first n\n-- integers that are prime numbers and less than n.\n-- for example:\n-- >>> count_up_to(5)\n-- {2, 3}\n-- >>> count_up_to(11)\n-- {2, 3, 5, 7}\n-- >>> count_up_to(0)\n-- {}\n-- >>> count_up_to(20)\n-- {2, 3, 5, 7, 11, 13, 17, 19}\n-- >>> count_up_to(1)\n-- {}\n-- >>> count_up_to(18)\n-- {2, 3, 5, 7, 11, 13, 17}\nlocal function count_up_to(n)\n local primes = {}\n for i = 2, n do\n local is_prime = true\n for j = 2, math.sqrt(i) do\n if i % j == 0 then\n is_prime = false\n break\n end\n end\n if is_prime then\n table.insert(primes, i)\n end\n end\n return primes\nend\n"], ["-- Complete the function that takes two integers and returns \n-- the product of their unit digits.\n-- Assume the input is always valid.\n-- Examples:\n-- >>> multiply(148, 412)\n-- 16\n-- >>> multiply(19, 28)\n-- 72\n-- >>> multiply(2020, 1851)\n-- 0\n-- >>> multiply(14, -15)\n-- 20\nlocal function multiply(a, b)\n local unit_a = a % 10\n local unit_b = b % 10\n return unit_a * unit_b\nend"], ["-- Given a string s, count the number of uppercase vowels in even indices.\n-- For example:\n-- >>> count_upper('aBCdEf')\n-- 1\n-- >>> count_upper('abcdefg')\n-- 0\n-- >>> count_upper('dBBE')\n-- 0\nlocal function count_upper(s)\n local count = 0\n for i = 1, #s, 2 do\n local c = s:sub(i, i)\n if c:match('[AEIOU]') then\n count = count + 1\n end\n end\n return count\nend"], ["-- Create a function that takes a value (string) representing a number\n-- and returns the closest integer to it. If the number is equidistant\n-- from two integers, round it away from zero.\n-- Examples\n-- >>> closest_integer('10')\n-- 10\n-- >>> closest_integer('15.3')\n-- 15\n-- Note:\n-- Rounding away from zero means that if the given number is equidistant\n-- from two integers, the one you should return is the one that is the\n-- farthest from zero. For example closest_integer(\"14.5\") should\n-- return 15 and closest_integer(\"-14.5\") should return -15.\nlocal function closest_integer(value)\n local num = tonumber(value)\n local rounded = math.floor(num + 0.5)\n if num > 0 and num - rounded == 0.5 then\n return rounded + 1\n elseif num < 0 and num - rounded == -0.5 then\n return rounded - 1\n else\n return rounded\n end\nend"], ["-- From a given table of integers, generate a table of rolling maximum element found until given moment\n-- in the sequence.\n-- >>> rolling_max({1, 2, 3, 2, 3, 4, 2})\n-- {1, 2, 3, 3, 3, 4, 4}\nlocal function rolling_max(numbers)\n local max_table = {}\n local max_value = -math.huge\n for i = 1, #numbers do\n max_value = math.max(max_value, numbers[i])\n table.insert(max_table, max_value)\n end\n return max_table\nend"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-php_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-php_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..21d9b346bfef54645dfc9269dede294ab92b0f31 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-php_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[[">> has_close_elements(array(1.0, 2.0, 3.0), 0.5)\n// false\n// >>> has_close_elements(array(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3)\n// true\nfunction has_close_elements($numbers, $threshold) {\n // Sort the array in ascending order\n sort($numbers);\n\n // Iterate through the array and check if any two adjacent numbers\n // are closer to each other than the given threshold\n for ($i = 0; $i < count($numbers) - 1; $i++) {\n if ($numbers[$i + 1] - $numbers[$i] < $threshold) {\n return true;\n }\n }\n\n // If no two adjacent numbers are closer to each other than the threshold,\n // return false\n return false;\n}\n"], [">> make_a_pile(3)\n// array(3, 5, 7)\nfunction make_a_pile($n) {\n $pile = array($n);\n for ($i = 1; $i < $n; $i++) {\n if ($n % 2 == 0) {\n $pile[] = $n + $i * 2;\n } else {\n $pile[] = $n + $i * 2 - 1;\n }\n }\n return $pile;\n}\n"], [">> words_string(\"Hi, my name is John\")\n// array(\"Hi\", \"my\", \"name\", \"is\", \"John\")\n// >>> words_string(\"One, two, three, four, five, six\")\n// array(\"One\", \"two\", \"three\", \"four\", \"five\", \"six\")\nfunction words_string($s) {\n $words = preg_split('/[\\s,]+/', $s);\n return $words;\n}"], [">> choose_num(12, 15)\n// 14\n// >>> choose_num(13, 12)\n// -1\nfunction choose_num($x, $y) {\n // If x is even, return x\n if ($x % 2 == 0) {\n return $x;\n }\n // If x is odd, return the next even number\n else {\n $x += 1;\n if ($x > $y) {\n return -1;\n }\n else {\n return $x;\n }\n }\n}\n"], [">> rounded_avg(1, 5)\n// \"0b11\"\n// >>> rounded_avg(7, 5)\n// -1\n// >>> rounded_avg(10, 20)\n// \"0b1111\"\n// >>> rounded_avg(20, 33)\n// \"0b11010\"\nfunction rounded_avg($n, $m) {\n if ($n > $m) {\n return -1;\n }\n $sum = 0;\n for ($i = $n; $i <= $m; $i++) {\n $sum += $i;\n }\n $avg = round($sum / ($m - $n + 1));\n return decbin($avg);\n}\n\necho rounded_avg(1, 5) . \"\\n\"; // \"0b11\"\necho rounded_avg(7, 5) . \"\\n\"; // -1\necho rounded_avg(10, 20) . \"\\n\"; // \"0b1111\"\necho rounded_avg(20, 33) . \"\\n\"; // \"0b11010\""], [">> unique_digits(array(15, 33, 1422, 1))\n// array(1, 15, 33)\n// >>> unique_digits(array(152, 323, 1422, 10))\n// array()\nfunction unique_digits($x) {\n $result = array();\n foreach ($x as $num) {\n $has_even_digit = false;\n while ($num > 0) {\n $digit = $num % 10;\n if ($digit % 2 == 0) {\n $has_even_digit = true;\n break;\n }\n $num = floor($num / 10);\n }\n if (!$has_even_digit) {\n $result[] = $num;\n }\n }\n sort($result);\n return $result;\n}\n"], [">> by_length(array(2, 1, 1, 4, 5, 8, 2, 3))\n// array(\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\")\n// If the array is empty, return an empty array:\n// >>> by_length(array())\n// array()\n// If the array has any strange number ignore it:\n// >>> by_length(array(1, -1, 55))\n// array(\"One\")\nfunction by_length($arr) {\n $names = array(\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\");\n $sorted = array_filter($arr, function($num) {\n return $num >= 1 && $num <= 9;\n });\n rsort($sorted);\n $result = array_map(function($num) use ($names) {\n return $names[$num - 1];\n }, $sorted);\n return $result;\n}\n"], [">> f(5)\n// array(1, 2, 6, 24, 15)\nfunction f($n) {\n $result = array();\n for ($i = 1; $i <= $n; $i++) {\n if ($i % 2 == 0) {\n $factorial = 1;\n for ($j = 1; $j <= $i; $j++) {\n $factorial *= $j;\n }\n $result[] = $factorial;\n } else {\n $sum = 0;\n for ($j = 1; $j <= $i; $j++) {\n $sum += $j;\n }\n $result[] = $sum;\n }\n }\n return $result;\n}\n"], [">> even_odd_palindrome(3)\n// array(1, 2)\n// Explanation:\n// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n// Example 2:\n// >>> even_odd_palindrome(12)\n// array(4, 6)\n// Explanation:\n// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n// Note:\n// 1. 1 <= n <= 10^3\n// 2. returned array has the number of even and odd integer palindromes respectively.\nfunction even_odd_palindrome($n) {\n $even_count = 0;\n $odd_count = 0;\n for ($i = 1; $i <= $n; $i++) {\n if (strrev(strval($i)) == strval($i)) {\n if ($i % 2 == 0) {\n $even_count++;\n } else {\n $odd_count++;\n }\n }\n }\n return array($even_count, $odd_count);\n}"], [" 0.\n// If a number is negative, then its first signed digit will be negative:\n// e.g. -123 has signed digits -1, 2, and 3.\n// >>> count_nums(array())\n// 0\n// >>> count_nums(array(-1, 11, -11))\n// 1\n// >>> count_nums(array(1, 1, 2))\n// 3\nfunction count_nums($arr) {\n $count = 0;\n foreach ($arr as $num) {\n $sum = 0;\n $num_str = strval(abs($num));\n for ($i = 0; $i < strlen($num_str); $i++) {\n $sum += intval($num_str[$i]);\n }\n if ($sum > 0) {\n $count++;\n }\n }\n return $count;\n}\n"], [">> move_one_ball(array(3, 4, 5, 1, 2))\n// true\n// Explanation: By performin 2 right shift operations, non-decreasing order can\n// be achieved for the given array.\n// >>> move_one_ball(array(3, 5, 4, 1, 2))\n// false\n// Explanation:It is not possible to get non-decreasing order for the given\n// array by performing any number of right shift operations.\nfunction move_one_ball($arr) {\n // If the array is empty, return true\n if (empty($arr)) {\n return true;\n }\n\n // Find the index of the maximum element in the array\n $max_index = array_search(max($arr), $arr);\n\n // If the maximum element is at the beginning of the array, return true\n if ($max_index == 0) {\n return true;\n }\n\n // If the maximum element is at the end of the array, return false\n if ($max_index == count($arr) - 1) {\n return false;\n }\n\n // If the maximum element is in the middle of the array, check if it can be\n // moved to the beginning of the array by performing right shift operations\n for ($i = $max_index; $i > 0; $i--) {\n if ($arr[$i] < $arr[$i - 1]) {\n return false;\n }\n }\n\n return true;\n}\n"], [">> make_palindrome(\"\")\n// \"\"\n// >>> make_palindrome(\"cat\")\n// \"catac\"\n// >>> make_palindrome(\"cata\")\n// \"catac\"\nfunction make_palindrome($string) {\n // Find the longest postfix of supplied string that is a palindrome.\n $len = strlen($string);\n $i = 0;\n while ($i < $len) {\n $j = $len - 1;\n while ($j > $i && $string[$i] == $string[$j]) {\n $i++;\n $j--;\n }\n if ($i >= $j) {\n break;\n }\n $i = 0;\n $len--;\n }\n // Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n $prefix = substr($string, 0, $len);\n $suffix = strrev($prefix);\n return $string . $suffix;\n}\n"], [">> exchange(array(1, 2, 3, 4), array(1, 2, 3, 4))\n// \"YES\"\n// >>> exchange(array(1, 2, 3, 4), array(1, 5, 3, 4))\n// \"NO\"\n// It is assumed that the input arrays will be non-empty.\nfunction exchange($lst1, $lst2) {\n // Count the number of odd numbers in lst1\n $odd_count = 0;\n foreach ($lst1 as $num) {\n if ($num % 2 != 0) {\n $odd_count++;\n }\n }\n\n // Count the number of even numbers in lst2\n $even_count = 0;\n foreach ($lst2 as $num) {\n if ($num % 2 == 0) {\n $even_count++;\n }\n }\n\n // If there are more odd numbers in lst1 than even numbers in lst2,\n // it is not possible to exchange elements to make lst1 all even.\n if ($odd_count > $even_count) {\n return \"NO\";\n }\n\n return \"YES\";\n}\n"], [">> histogram(\"a b c\")\n// array(\"a\" => 1, \"b\" => 1, \"c\" => 1)\n// >>> histogram(\"a b b a\")\n// array(\"a\" => 2, \"b\" => 2)\n// >>> histogram(\"a b c a b\")\n// array(\"a\" => 2, \"b\" => 2)\n// >>> histogram(\"b b b b a\")\n// array(\"b\" => 4)\n// >>> histogram(\"\")\n// array()\nfunction histogram($test) {\n $letters = explode(\" \", $test);\n $counts = array_count_values($letters);\n $max_count = max($counts);\n $result = array();\n foreach ($counts as $letter => $count) {\n if ($count == $max_count) {\n $result[$letter] = $count;\n }\n }\n return $result;\n}"], [">> reverse_delete(\"abcde\", \"ae\")\n// array(\"bcd\", false)\n// >>> reverse_delete(\"abcdef\", \"b\")\n// array(\"acdef\", false)\n// >>> reverse_delete(\"abcdedcba\", \"ab\")\n// array(\"cdedc\", true)\nfunction reverse_delete($s, $c) {\n // Remove all characters in $c from $s\n $s = str_replace(str_split($c), '', $s);\n\n // Check if $s is a palindrome\n $is_palindrome = ($s == strrev($s));\n\n // Return the result as an array\n return array($s, $is_palindrome);\n}\n"], [">> odd_count(array(\"1234567\"))\n// array(\"the number of odd elements 4n the str4ng 4 of the 4nput.\")\n// >>> odd_count(array(\"3\", \"11111111\"))\n// array(\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\")\nfunction odd_count($lst) {\n $result = array();\n foreach ($lst as $str) {\n $count = 0;\n for ($i = 0; $i < strlen($str); $i++) {\n if ($str[$i] % 2 != 0) {\n $count++;\n }\n }\n $result[] = \"the number of odd elements $countn the str$countng $count of the $countnput.\";\n }\n return $result;\n}\n\n$input = array(\"1234567\", \"3\", \"11111111\");\n$output = odd_count($input);\nprint_r($output);"], [">> minSubArraySum(array(2, 3, 4, 1, 2, 4))\n// 1\n// >>> minSubArraySum(array(-1, -2, -3))\n// -6\nfunction minSubArraySum($nums) {\n $minSum = $nums[0];\n $currSum = $nums[0];\n for ($i = 1; $i < count($nums); $i++) {\n $currSum = min($nums[$i], $currSum + $nums[$i]);\n $minSum = min($minSum, $currSum);\n }\n return $minSum;\n}\n"], [">> max_fill(array(array(0, 0, 1, 0), array(0, 1, 0, 0), array(1, 1, 1, 1)), 1)\n// 6\n// Example 2:\n// >>> max_fill(array(array(0, 0, 1, 1), array(0, 0, 0, 0), array(1, 1, 1, 1), array(0, 1, 1, 1)), 2)\n// 5\n// Example 3:\n// >>> max_fill(array(array(0, 0, 0), array(0, 0, 0)), 5)\n// 0\n// Constraints:\n// * all wells have the same length\n// * 1 <= grid.length <= 10^2\n// * 1 <= grid[:,1].length <= 10^2\n// * grid[i][j] -> 0 | 1\n// * 1 <= capacity <= 10\nfunction max_fill($grid, $capacity) {\n $num_rows = count($grid);\n $num_cols = count($grid[0]);\n $num_buckets = 0;\n $num_wells = 0;\n for ($i = 0; $i < $num_rows; $i++) {\n for ($j = 0; $j < $num_cols; $j++) {\n if ($grid[$i][$j] == 1) {\n $num_wells++;\n }\n }\n }\n while ($num_wells > 0) {\n $num_buckets++;\n $num_wells -= $capacity;\n }\n return $num_buckets;\n}"], [">> sort_array(array(1, 5, 2, 3, 4))\n// array(1, 2, 3, 4, 5)\n// >>> sort_array(array(-2, -3, -4, -5, -6))\n// array(-6, -5, -4, -3, -2)\n// >>> sort_array(array(1, 0, 2, 3, 4))\n// array(0, 1, 2, 3, 4)\nfunction sort_array($arr) {\n $counts = array_map(function($num) {\n return array_sum(str_split(decbin($num)));\n }, $arr);\n array_multisort($counts, $arr);\n return $arr;\n}\n"], [">> select_words(\"Mary had a little lamb\", 4)\n// array(\"little\")\n// >>> select_words(\"Mary had a little lamb\", 3)\n// array(\"Mary\", \"lamb\")\n// >>> select_words(\"simple white space\", 2)\n// array()\n// >>> select_words(\"Hello world\", 4)\n// array(\"world\")\n// >>> select_words(\"Uncle sam\", 3)\n// array(\"Uncle\")\nfunction select_words($s, $n) {\n $words = explode(\" \", $s);\n $result = array();\n foreach ($words as $word) {\n $consonants = 0;\n for ($i = 0; $i < strlen($word); $i++) {\n $char = strtolower($word[$i]);\n if ($char != 'a' && $char != 'e' && $char != 'i' && $char != 'o' && $char != 'u') {\n $consonants++;\n }\n }\n if ($consonants == $n) {\n $result[] = $word;\n }\n }\n return $result;\n}\n"], [">> get_closest_vowel(\"yogurt\")\n// \"u\"\n// >>> get_closest_vowel(\"FULL\")\n// \"U\"\n// >>> get_closest_vowel(\"quick\")\n// \"\"\n// >>> get_closest_vowel(\"ab\")\n// \"\"\nfunction get_closest_vowel($word) {\n $vowels = array('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');\n $closest_vowel = '';\n $word_length = strlen($word);\n for ($i = $word_length - 1; $i >= 2; $i--) {\n if (!in_array($word[$i], $vowels) && in_array($word[$i - 1], $vowels) && !in_array($word[$i - 2], $vowels)) {\n $closest_vowel = $word[$i - 1];\n break;\n }\n }\n return $closest_vowel;\n}\n\necho get_closest_vowel(\"yogurt\"); // Output: \"u\"\necho get_closest_vowel(\"FULL\"); // Output: \"U\"\necho get_closest_vowel(\"quick\"); // Output: \"\"\necho get_closest_vowel(\"ab\"); // Output: \"\""], [">> match_parens(array(\"()(\", \")\"))\n// \"Yes\"\n// >>> match_parens(array(\")\", \")\"))\n// \"No\"\nfunction match_parens($lst) {\n $str = $lst[0] . $lst[1];\n $stack = array();\n for ($i = 0; $i < strlen($str); $i++) {\n if ($str[$i] == '(') {\n array_push($stack, '(');\n } else {\n if (empty($stack)) {\n return \"No\";\n }\n array_pop($stack);\n }\n }\n if (empty($stack)) {\n return \"Yes\";\n } else {\n return \"No\";\n }\n}\n"], [">> string_xor(\"010\", \"110\")\n// \"100\"\nfunction string_xor($a, $b) {\n $result = \"\";\n for ($i = 0; $i < strlen($a); $i++) {\n $result .= ($a[$i] ^ $b[$i]);\n }\n return $result;\n}\n"], [">> maximum(array(-3, -4, 5), 3)\n// array(-4, -3, 5)\n// Example 2:\n// >>> maximum(array(4, -4, 4), 2)\n// array(4, 4)\n// Example 3:\n// >>> maximum(array(-3, 2, 1, 2, -1, -2, 1), 1)\n// array(2)\n// Note:\n// 1. The length of the array will be in the range of [1, 1000].\n// 2. The elements in the array will be in the range of [-1000, 1000].\n// 3. 0 <= k <= len(arr)\nfunction maximum($arr, $k) {\n sort($arr); // Sort the array in ascending order\n $result = array_slice($arr, -$k); // Get the last $k elements of the sorted array\n return $result;\n}"], [">> solution(array(5, 8, 7, 1))\n// 12\n// >>> solution(array(3, 3, 3, 3, 3))\n// 9\n// >>> solution(array(30, 13, 24, 321))\n// 0\nfunction solution($lst) {\n $sum = 0;\n for ($i = 0; $i < count($lst); $i += 2) {\n if ($lst[$i] % 2 != 0) {\n $sum += $lst[$i];\n }\n }\n return $sum;\n}\n"], [">> add_elements(array(111, 21, 3, 4000, 5, 6, 7, 8, 9), 4)\n// 24\n// Constraints:\n// 1. 1 <= len(arr) <= 100\n// 2. 1 <= k <= len(arr)\nfunction add_elements($arr, $k) {\n $sum = 0;\n for ($i = 0; $i < $k; $i++) {\n if (strlen(strval($arr[$i])) <= 2) {\n $sum += $arr[$i];\n }\n }\n return $sum;\n}\n"], [">> get_odd_collatz(5)\n// array(1, 5)\nfunction get_odd_collatz($n) {\n $collatz_sequence = array($n);\n while ($n != 1) {\n if ($n % 2 == 0) {\n $n = $n / 2;\n } else {\n $n = 3 * $n + 1;\n }\n $collatz_sequence[] = $n;\n }\n $odd_collatz_sequence = array();\n foreach ($collatz_sequence as $num) {\n if ($num % 2 != 0) {\n $odd_collatz_sequence[] = $num;\n }\n }\n sort($odd_collatz_sequence);\n return $odd_collatz_sequence;\n}\n"], [">> valid_date(\"03-11-2000\")\n// true\n// >>> valid_date(\"15-01-2012\")\n// false\n// >>> valid_date(\"04-0-2040\")\n// false\n// >>> valid_date(\"06-04-2020\")\n// true\n// >>> valid_date(\"06/04/2020\")\n// false\nfunction valid_date($date) {\n // Check if the date string is not empty\n if (empty($date)) {\n return false;\n }\n\n // Split the date string into month, day, and year\n $date_parts = explode(\"-\", $date);\n\n // Check if the date string is in the format: mm-dd-yyyy\n if (count($date_parts) != 3) {\n return false;\n }\n\n // Extract the month, day, and year from the date string\n $month = $date_parts[0];\n $day = $date_parts[1];\n $year = $date_parts[2];\n\n // Check if the month is valid\n if ($month < 1 || $month > 12) {\n return false;\n }\n\n // Check if the day is valid\n if ($day < 1 || $day > 31) {\n return false;\n }\n\n // Check if the day is valid for February\n if ($month == 2) {\n if ($day > 29) {\n return false;\n }\n if ($day == 29) {\n if (!($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0))) {\n return false;\n }\n }\n }\n\n // Check if the day is valid for April, June, September, and November\n if ($month == 4 || $month == 6 || $month == 9 || $month == 11) {\n if ($day > 30) {\n return false;\n }\n }\n\n // The date is valid\n return true;\n}\n"], [">> split_words(\"Hello world!\")\n// array(\"Hello\", \"world!\")\n// >>> split_words(\"Hello,world!\")\n// array(\"Hello\", \"world!\")\n// >>> split_words(\"abcdef\")\n// 3\nfunction split_words($txt) {\n $words = explode(\" \", $txt);\n if (count($words) > 1) {\n return $words;\n }\n $words = explode(\",\", $txt);\n if (count($words) > 1) {\n return $words;\n }\n $count = 0;\n for ($i = 0; $i < strlen($txt); $i++) {\n if (ctype_lower($txt[$i]) && ord($txt[$i]) % 2 != 0) {\n $count++;\n }\n }\n return $count;\n}"], [">> is_sorted(array(5))\n// true\n// >>> is_sorted(array(1, 2, 3, 4, 5))\n// true\n// >>> is_sorted(array(1, 3, 2, 4, 5))\n// false\n// >>> is_sorted(array(1, 2, 3, 4, 5, 6))\n// true\n// >>> is_sorted(array(1, 2, 3, 4, 5, 6, 7))\n// true\n// >>> is_sorted(array(1, 3, 2, 4, 5, 6, 7))\n// false\n// >>> is_sorted(array(1, 2, 2, 3, 3, 4))\n// true\n// >>> is_sorted(array(1, 2, 2, 2, 3, 4))\n// false\nfunction is_sorted($lst) {\n // Check if array has more than 1 duplicate of the same number\n if (count($lst) !== count(array_unique($lst))) {\n return false;\n }\n // Check if array is sorted in ascending order\n for ($i = 0; $i < count($lst) - 1; $i++) {\n if ($lst[$i] > $lst[$i + 1]) {\n return false;\n }\n }\n return true;\n}\n"], [">> intersection(array(1, 2), array(2, 3))\n// \"NO\"\n// >>> intersection(array(-1, 1), array(0, 4))\n// \"NO\"\n// >>> intersection(array(-3, -1), array(-5, 5))\n// \"YES\"\nfunction intersection($interval1, $interval2) {\n $start = max($interval1[0], $interval2[0]);\n $end = min($interval1[1], $interval2[1]);\n $length = $end - $start;\n if ($length < 0) {\n return \"NO\";\n }\n if ($length == 1) {\n return \"NO\";\n }\n for ($i = 2; $i < $length; $i++) {\n if ($length % $i == 0) {\n return \"NO\";\n }\n }\n return \"YES\";\n}\n"], [">> prod_signs(array(1, 2, 2, -4))\n// 9\n// >>> prod_signs(array(0, 1))\n// 0\n// >>> prod_signs(array())\n// null\nfunction prod_signs($arr) {\n if (empty($arr)) {\n return null;\n }\n $product = 1;\n $sum = 0;\n foreach ($arr as $num) {\n $product *= ($num > 0) - ($num < 0);\n $sum += abs($num);\n }\n return $product * $sum;\n}\n"], ["= 2) and a positive integer k, \n// each cell of the grid contains a value. Every integer in the range [1, N * N]\n// inclusive appears exactly once on the cells of the grid.\n// You have to find the minimum path of length k in the grid. You can start\n// from any cell, and in each step you can move to any of the neighbor cells,\n// in other words, you can go to cells which share an edge with you current\n// cell.\n// Please note that a path of length k means visiting exactly k cells (not\n// necessarily distinct).\n// You CANNOT go off the grid.\n// A path A (of length k) is considered less than a path B (of length k) if\n// after making the ordered arrays of the values on the cells that A and B go\n// through (let's call them lst_A and lst_B), lst_A is lexicographically less\n// than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n// lst_A[j] = lst_B[j].\n// It is guaranteed that the answer is unique.\n// Return an ordered array of the values on the cells that the minimum path go through.\n// Examples: \n// >>> minPath(array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)), 3)\n// array(1, 2, 1)\n// >>> minPath(array(array(5, 9, 3), array(4, 1, 6), array(7, 8, 2)), 1)\n// array(1)\nfunction minPath($grid, $k) {\n $n = count($grid);\n $dp = array_fill(0, $n, array_fill(0, $n, array_fill(0, $k + 1, PHP_INT_MAX)));\n for ($i = 0; $i < $n; $i++) {\n for ($j = 0; $j < $n; $j++) {\n $dp[$i][$j][1] = $grid[$i][$j];\n }\n }\n for ($l = 2; $l <= $k; $l++) {\n for ($i = 0; $i < $n; $i++) {\n for ($j = 0; $j < $n; $j++) {\n for ($x = 0; $x < $n; $x++) {\n for ($y = 0; $y < $n; $y++) {\n if ($x != $i || $y != $j) {\n $dp[$i][$j][$l] = min($dp[$i][$j][$l], $dp[$x][$y][$l - 1] + $grid[$i][$j]);\n }\n }\n }\n }\n }\n }\n $min_path = array_fill(0, $k, PHP_INT_MAX);\n for ($i = 0; $i < $n; $i++) {\n for ($j = 0; $j < $n; $j++) {\n $min_path[$k - 1] = min($min_path[$k - 1], $dp[$i][$j][$k]);\n }\n }\n return $min_path;\n}"], [">> longest(array())\n// null\n// >>> longest(array(\"a\", \"b\", \"c\"))\n// \"a\"\n// >>> longest(array(\"a\", \"bb\", \"ccc\"))\n// \"ccc\"\nfunction longest($strings) {\n $longest = null;\n foreach ($strings as $string) {\n if ($longest === null || strlen($string) > strlen($longest)) {\n $longest = $string;\n }\n }\n return $longest;\n}\n"], [">> tri(3)\n// array(1, 3, 2, 8)\nfunction tri($n) {\n $tri = array(1, 3);\n for ($i = 2; $i <= $n; $i++) {\n if ($i % 2 == 0) {\n $tri[$i] = 1 + $i / 2;\n } else {\n $tri[$i] = $tri[$i - 1] + $tri[$i - 2] + $tri[$i + 1];\n }\n }\n return $tri;\n}\n\nprint_r(tri(3));"], [">> digits(1)\n// 1\n// >>> digits(4)\n// 0\n// >>> digits(235)\n// 15\nfunction digits($n) {\n $product = 1;\n $has_odd = false;\n while ($n > 0) {\n $digit = $n % 10;\n if ($digit % 2 != 0) {\n $product *= $digit;\n $has_odd = true;\n }\n $n = floor($n / 10);\n }\n if (!$has_odd) {\n return 0;\n }\n return $product;\n}\n\necho digits(1) . \"\\n\"; // Output: 1\necho digits(4) . \"\\n\"; // Output: 0\necho digits(235) . \"\\n\"; // Output: 15"], [">> is_nested(\"[[]]\")\n// true\n// >>> is_nested(\"[]]]]]]][[[[[]\")\n// false\n// >>> is_nested(\"[][]\")\n// false\n// >>> is_nested(\"[]\")\n// false\n// >>> is_nested(\"[[][]]\")\n// true\n// >>> is_nested(\"[[]][[\")\n// true\nfunction is_nested($string) {\n // Initialize a stack to keep track of the brackets.\n $stack = array();\n\n // Iterate through each character in the string.\n for ($i = 0; $i < strlen($string); $i++) {\n // If the character is an opening bracket, push it onto the stack.\n if ($string[$i] == '[') {\n array_push($stack, '[');\n }\n // If the character is a closing bracket, check if there is an opening bracket on the stack.\n else if ($string[$i] == ']') {\n // If there is an opening bracket on the stack, pop it off and continue.\n if (count($stack) > 0 && $stack[count($stack) - 1] == '[') {\n array_pop($stack);\n }\n // If there is not an opening bracket on the stack, return false.\n else {\n return false;\n }\n }\n }\n\n // If there are any opening brackets left on the stack, return false.\n if (count($stack) > 0) {\n return false;\n }\n\n // If there are no opening brackets left on the stack and all brackets have been matched, return true.\n return true;\n}\n"], [">> lst(array(1.0, 2.0, 3.0))\n// 14\n// >>> lst(array(1.0, 4.0, 9.0))\n// 98\n// >>> lst(array(1.0, 3.0, 5.0, 7.0))\n// 84\n// >>> lst(array(1.4, 4.2, 0.0))\n// 29\n// >>> lst(array(-2.4, 1.0, 1.0))\n// 6\nfunction sum_squares($lst) {\n $sum = 0;\n foreach ($lst as $num) {\n $sum += pow(ceil($num), 2);\n }\n return $sum;\n}\n"], [">> check_if_last_char_is_a_letter(\"apple pie\")\n// false\n// >>> check_if_last_char_is_a_letter(\"apple pi e\")\n// true\n// >>> check_if_last_char_is_a_letter(\"apple pi e \")\n// false\n// >>> check_if_last_char_is_a_letter(\"\")\n// false\nfunction check_if_last_char_is_a_letter($txt) {\n // Remove any trailing spaces from the input string\n $txt = rtrim($txt);\n\n // Check if the last character is an alphabetical character\n if (ctype_alpha($txt[strlen($txt) - 1])) {\n // Check if the last character is not part of a word\n if ($txt[strlen($txt) - 2] == ' ') {\n return true;\n }\n }\n\n return false;\n}\n"], [">> can_arrange(array(1, 2, 4, 3, 5))\n// 3\n// >>> can_arrange(array(1, 2, 3))\n// -1\nfunction can_arrange($arr) {\n $max_index = -1;\n for ($i = 1; $i < count($arr); $i++) {\n if ($arr[$i] < $arr[$i-1]) {\n $max_index = $i-1;\n }\n }\n return $max_index;\n}\n"], [">> largest_smallest_integers(array(2, 4, 1, 3, 5, 7))\n// array(null, 1)\n// >>> largest_smallest_integers(array())\n// array(null, null)\n// >>> largest_smallest_integers(array(0))\n// array(null, null)\nfunction largest_smallest_integers($lst) {\n $largest_negative = null;\n $smallest_positive = null;\n foreach ($lst as $num) {\n if ($num < 0 && ($largest_negative === null || $num > $largest_negative)) {\n $largest_negative = $num;\n } elseif ($num > 0 && ($smallest_positive === null || $num < $smallest_positive)) {\n $smallest_positive = $num;\n }\n }\n return array($largest_negative, $smallest_positive);\n}\n"], [">> compare_one(1, 2.5)\n// 2.5\n// >>> compare_one(1, \"2,3\")\n// \"2,3\"\n// >>> compare_one(\"5,1\", \"6\")\n// \"6\"\n// >>> compare_one(\"1\", 1)\n// null\nfunction compare_one($a, $b) {\n // Convert strings to floats\n $a = str_replace(',', '.', $a);\n $b = str_replace(',', '.', $b);\n $a = floatval($a);\n $b = floatval($b);\n\n // Compare the values\n if ($a > $b) {\n return $a;\n } elseif ($b > $a) {\n return $b;\n } else {\n return null;\n }\n}\n"], [">> is_equal_to_sum_even(4)\n// false\n// >>> is_equal_to_sum_even(6)\n// false\n// >>> is_equal_to_sum_even(8)\n// true\nfunction is_equal_to_sum_even($n) {\n // Check if n is divisible by 4\n if ($n % 4 != 0) {\n return false;\n }\n // If n is divisible by 4, then it can be written as the sum of exactly 4 positive even numbers\n return true;\n}\n"], [" 0\n// For example:\n// >>> special_factorial(4)\n// 288\n// The function will receive an integer as input and should return the special\n// factorial of this integer.\nfunction special_factorial($n) {\n $result = 1;\n for ($i = $n; $i > 0; $i--) {\n $result *= $i;\n }\n return $result;\n}\n"], [">> greatest_common_divisor(3, 5)\n// 1\n// >>> greatest_common_divisor(25, 15)\n// 5\nfunction greatest_common_divisor($a, $b) {\n if ($b == 0) {\n return $a;\n } else {\n return greatest_common_divisor($b, $a % $b);\n }\n}\n\necho greatest_common_divisor(3, 5) . \"\\n\"; // Output: 1\necho greatest_common_divisor(25, 15) . \"\\n\"; // Output: 5"], [">> fix_spaces(\" Example\")\n// \"Example\"\n// >>> fix_spaces(\" Example 1\")\n// \"Example_1\"\n// >>> fix_spaces(\" Example 2\")\n// \"_Example_2\"\n// >>> fix_spaces(\" Example 3\")\n// \"_Example-3\"\nfunction fix_spaces($text) {\n $text = trim($text); // remove leading/trailing spaces\n $text = preg_replace('/\\s+/', ' ', $text); // replace multiple spaces with single space\n $text = str_replace(' ', '_', $text); // replace spaces with underscores\n $text = preg_replace('/-{2,}/', '-', $text); // replace multiple dashes with single dash\n return $text;\n}\n\necho fix_spaces(\" Example\") . \"\\n\"; // \"Example\"\necho fix_spaces(\" Example 1\") . \"\\n\"; // \"Example_1\"\necho fix_spaces(\" Example 2\") . \"\\n\"; // \"_Example_2\"\necho fix_spaces(\" Example 3\") . \"\\n\"; // \"_Example-3\""], [">> file_name_check(\"example.txt\")\n// \"Yes\"\n// >>> file_name_check(\"1example.dll\")\n// \"No\"\nfunction file_name_check($file_name) {\n // Check if there are more than three digits in the file's name.\n if (preg_match('/\\d{4,}/', $file_name)) {\n return \"No\";\n }\n\n // Check if the file's name contains exactly one dot.\n if (substr_count($file_name, '.') != 1) {\n return \"No\";\n }\n\n // Split the file's name into two substrings: the substring before the dot,\n // and the substring after the dot.\n $parts = explode('.', $file_name);\n $before_dot = $parts[0];\n $after_dot = $parts[1];\n\n // Check if the substring before the dot is empty or does not start with a letter.\n if (empty($before_dot) || !preg_match('/^[a-zA-Z]/', $before_dot)) {\n return \"No\";\n }\n\n // Check if the substring after the dot is one of the allowed extensions.\n $allowed_extensions = ['txt', 'exe', 'dll'];\n if (!in_array($after_dot, $allowed_extensions)) {\n return \"No\";\n }\n\n // If all conditions are met, return 'Yes'.\n return \"Yes\";\n}\n"], [">> lst\n// array(1, 2, 3)\n// >>> lst\n// array()\n// >>> lst\n// array(-1, -5, 2, -1, -5)\nfunction sum_squares($lst) {\n $sum = 0;\n for ($i = 0; $i < count($lst); $i++) {\n if ($i % 3 == 0) {\n $sum += pow($lst[$i], 2);\n } elseif ($i % 4 == 0) {\n $sum += pow($lst[$i], 3);\n } else {\n $sum += $lst[$i];\n }\n }\n return $sum;\n}"], [">> words_in_sentence(\"This is a test\")\n// \"is\"\n// Example 2:\n// >>> words_in_sentence(\"lets go for swimming\")\n// \"go for\"\n// Constraints:\n// * 1 <= len(sentence) <= 100\n// * sentence contains only letters\nfunction words_in_sentence($sentence) {\n $words = explode(\" \", $sentence);\n $prime_words = array();\n foreach ($words as $word) {\n $length = strlen($word);\n if (is_prime($length)) {\n $prime_words[] = $word;\n }\n }\n return implode(\" \", $prime_words);\n}\n"], ["/ where both numerator and denominator are positive whole numbers.\n// You can assume that x, and n are valid fractions, and do not have zero as denominator.\n// >>> simplify(\"1/5\", \"5/1\")\n// true\n// >>> simplify(\"1/6\", \"2/1\")\n// false\n// >>> simplify(\"7/10\", \"10/2\")\n// false\nfunction simplify($x, $n) {\n $x_parts = explode(\"/\", $x);\n $n_parts = explode(\"/\", $n);\n $x_numerator = $x_parts[0];\n $x_denominator = $x_parts[1];\n $n_numerator = $n_parts[0];\n $n_denominator = $n_parts[1];\n $result = ($x_numerator * $n_denominator) / ($x_denominator * $n_numerator);\n return is_int($result);\n}\n"], [">> order_by_points(array(1, 11, -1, -11, -12))\n// array(-1, -11, 1, -12, 11)\n// >>> order_by_points(array())\n// array()\nfunction order_by_points($nums) {\n // Helper function to calculate the sum of digits of a number\n function sum_digits($num) {\n $sum = 0;\n while ($num > 0) {\n $sum += $num % 10;\n $num = floor($num / 10);\n }\n return $sum;\n }\n\n // Sort the array based on the sum of digits\n usort($nums, function($a, $b) {\n $sum_a = sum_digits($a);\n $sum_b = sum_digits($b);\n if ($sum_a == $sum_b) {\n return 0;\n }\n return ($sum_a < $sum_b) ? -1 : 1;\n });\n\n return $nums;\n}\n"], [">> specialFilter(array(15, -73, 14, -15))\n// 1\n// >>> specialFilter(array(33, -2, -3, 45, 21, 109))\n// 2\nfunction specialFilter($nums) {\n $count = 0;\n foreach ($nums as $num) {\n if ($num > 10 && abs($num) % 2 != 0 && abs($num) % 10 % 2 != 0) {\n $count++;\n }\n }\n return $count;\n}\n"], [">> get_max_triples(5)\n// 1\n// Explanation: \n// a = [1, 3, 7, 13, 21]\n// The only valid triple is (1, 7, 13).\nfunction get_max_triples($n) {\n $a = array();\n for ($i = 1; $i <= $n; $i++) {\n $a[$i] = $i * $i - $i + 1;\n }\n $count = 0;\n for ($i = 1; $i <= $n - 2; $i++) {\n for ($j = $i + 1; $j <= $n - 1; $j++) {\n for ($k = $j + 1; $k <= $n; $k++) {\n if (($a[$i] + $a[$j] + $a[$k]) % 3 == 0) {\n $count++;\n }\n }\n }\n }\n return $count;\n}\n\necho get_max_triples(5);"], [">> bf(\"Jupiter\", \"Neptune\")\n// array(\"Saturn\", \"Uranus\")\n// >>> bf(\"Earth\", \"Mercury\")\n// \"Venus\"\n// >>> bf(\"Mercury\", \"Uranus\")\n// array(\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\nfunction bf($planet1, $planet2) {\n $planets = array(\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\");\n $start = array_search($planet1, $planets);\n $end = array_search($planet2, $planets);\n if ($start === false || $end === false) {\n return array();\n }\n $result = array();\n for ($i = $start + 1; $i < $end; $i++) {\n $result[] = $planets[$i];\n }\n return $result;\n}"], [">> list_sort(array(\"aa\", \"a\", \"aaa\"))\n// array(\"aa\")\n// >>> list_sort(array(\"ab\", \"a\", \"aaa\", \"cd\"))\n// array(\"ab\", \"cd\")\nfunction sorted_list_sum($lst) {\n $result = array();\n foreach ($lst as $word) {\n if (strlen($word) % 2 == 0) {\n array_push($result, $word);\n }\n }\n sort($result);\n return $result;\n}\n\n$lst = array(\"aa\", \"a\", \"aaa\");\nprint_r(sorted_list_sum($lst));\n\n$lst = array(\"ab\", \"a\", \"aaa\", \"cd\");\nprint_r(sorted_list_sum($lst));"], [">> all_prefixes(\"abc\")\n// array(\"a\", \"ab\", \"abc\")\nfunction all_prefixes($string) {\n $prefixes = array();\n $length = strlen($string);\n for ($i = 1; $i <= $length; $i++) {\n $prefixes[] = substr($string, 0, $i);\n }\n return $prefixes;\n}\n"], [">> x_or_y(7, 34, 12)\n// 34\n// >>> x_or_y(15, 8, 5)\n// 5\nfunction x_or_y($n, $x, $y) {\n if (gmp_prob_prime($n) == 2) {\n return $x;\n } else {\n return $y;\n }\n}\n\necho x_or_y(7, 34, 12) . \"\\n\"; // Output: 34\necho x_or_y(15, 8, 5) . \"\\n\"; // Output: 5"], [">> double_the_difference(array(1, 3, 2, 0))\n// 10\n// >>> double_the_difference(array(-1, -2, 0))\n// 0\n// >>> double_the_difference(array(9, -2))\n// 81\n// >>> double_the_difference(array(0))\n// 0\n// If the input array is empty, return 0.\nfunction double_the_difference($lst) {\n $sum = 0;\n foreach ($lst as $num) {\n if (is_int($num) && $num % 2 != 0) {\n $sum += $num * $num;\n }\n }\n return $sum;\n}\n"], [">> compare(array(1, 2, 3, 4, 5, 1), array(1, 2, 3, 4, 2, -2))\n// array(0, 0, 0, 0, 3, 3)\n// >>> compare(array(0, 5, 0, 0, 0, 4), array(4, 1, 1, 0, 0, -2))\n// array(4, 4, 1, 0, 0, 6)\nfunction compare($game, $guess) {\n $result = array();\n for ($i = 0; $i < count($game); $i++) {\n if ($game[$i] == $guess[$i]) {\n array_push($result, 0);\n } else {\n array_push($result, abs($game[$i] - $guess[$i]));\n }\n }\n return $result;\n}"], [">> Strongest_Extension(\"my_class\", array(\"AA\", \"Be\", \"CC\"))\n// \"my_class.AA\"\nfunction Strongest_Extension($class_name, $extensions) {\n $strength = array();\n foreach ($extensions as $extension) {\n $uppercase_count = preg_match_all('/[A-Z]/', $extension);\n $lowercase_count = preg_match_all('/[a-z]/', $extension);\n $strength[$extension] = $uppercase_count - $lowercase_count;\n }\n arsort($strength);\n $strongest_extension = key($strength);\n return $class_name . '.' . $strongest_extension;\n}\n"], [">> cycpattern_check(\"abcd\", \"abd\")\n// false\n// >>> cycpattern_check(\"hello\", \"ell\")\n// true\n// >>> cycpattern_check(\"whassup\", \"psus\")\n// false\n// >>> cycpattern_check(\"abab\", \"baa\")\n// true\n// >>> cycpattern_check(\"efef\", \"eeff\")\n// false\n// >>> cycpattern_check(\"himenss\", \"simen\")\n// true\nfunction cycpattern_check($a, $b) {\n // Concatenate the first word with itself to create a cyclic string\n $cyclic_string = $a . $a;\n \n // Check if the second word is a substring in the cyclic string\n if (strpos($cyclic_string, $b) !== false) {\n return true;\n }\n \n // If the second word is not a substring, check if any of its rotations are\n for ($i = 0; $i < strlen($b); $i++) {\n $rotated_word = substr($b, $i) . substr($b, 0, $i);\n if (strpos($cyclic_string, $rotated_word) !== false) {\n return true;\n }\n }\n \n // If none of the rotations are found, return false\n return false;\n}\n"], [">> even_odd_count(-12)\n// array(1, 1)\n// >>> even_odd_count(123)\n// array(1, 2)\nfunction even_odd_count($num) {\n $even_count = 0;\n $odd_count = 0;\n $num = abs($num); // convert to positive number\n while ($num > 0) {\n $digit = $num % 10;\n if ($digit % 2 == 0) {\n $even_count++;\n } else {\n $odd_count++;\n }\n $num = floor($num / 10);\n }\n return array($even_count, $odd_count);\n}\n"], [">> int_to_mini_roman(19)\n// \"xix\"\n// >>> int_to_mini_roman(152)\n// \"clii\"\n// >>> int_to_mini_roman(426)\n// \"cdxxvi\"\nfunction int_to_mini_roman($number) {\n $roman_numerals = array(\n 'M' => 1000,\n 'CM' => 900,\n 'D' => 500,\n 'CD' => 400,\n 'C' => 100,\n 'XC' => 90,\n 'L' => 50,\n 'XL' => 40,\n 'X' => 10,\n 'IX' => 9,\n 'V' => 5,\n 'IV' => 4,\n 'I' => 1\n );\n $result = '';\n foreach ($roman_numerals as $roman => $value) {\n while ($number >= $value) {\n $result .= $roman;\n $number -= $value;\n }\n }\n return strtolower($result);\n}\n\necho int_to_mini_roman(19) . \"\\n\"; // Output: \"xix\"\necho int_to_mini_roman(152) . \"\\n\"; // Output: \"clii\"\necho int_to_mini_roman(426) . \"\\n\"; // Output: \"cdxxvi\""], [">> right_angle_triangle(3, 4, 5)\n// true\n// >>> right_angle_triangle(1, 2, 3)\n// false\nfunction right_angle_triangle($a, $b, $c) {\n // Sort the sides in ascending order\n $sides = array($a, $b, $c);\n sort($sides);\n\n // Check if the square of the longest side is equal to the sum of the squares\n // of the other two sides\n return (pow($sides[2], 2) == pow($sides[0], 2) + pow($sides[1], 2));\n}\n"], [">> find_max(array(\"name\", \"of\", \"string\"))\n// \"string\"\n// >>> find_max(array(\"name\", \"enam\", \"game\"))\n// \"enam\"\n// >>> find_max(array(\"aaaaaaa\", \"bb\", \"cc\"))\n// \"aaaaaaa\"\nfunction find_max($words) {\n $max_unique = 0;\n $max_word = \"\";\n foreach ($words as $word) {\n $unique_chars = count(array_unique(str_split($word)));\n if ($unique_chars > $max_unique) {\n $max_unique = $unique_chars;\n $max_word = $word;\n } elseif ($unique_chars == $max_unique && $word < $max_word) {\n $max_word = $word;\n }\n }\n return $max_word;\n}\n"], [">> eat(5, 6, 10)\n// array(11, 4)\n// >>> eat(4, 8, 9)\n// array(12, 1)\n// >>> eat(1, 10, 10)\n// array(11, 0)\n// >>> eat(2, 11, 5)\n// array(7, 0)\n// Variables:\n// @number : integer\n// the number of carrots that you have eaten.\n// @need : integer\n// the number of carrots that you need to eat.\n// @remaining : integer\n// the number of remaining carrots thet exist in stock\n// Constrain:\n// * 0 <= number <= 1000\n// * 0 <= need <= 1000\n// * 0 <= remaining <= 1000\n// Have fun :)\nfunction eat($number, $need, $remaining) {\n // Calculate the total number of carrots eaten after meals\n $total = $number + $need;\n \n // Calculate the number of carrots left after meals\n $left = $remaining - $need;\n \n // If there are not enough remaining carrots, eat all remaining carrots\n if ($left < 0) {\n $left = 0;\n }\n \n // Return the result as an array\n return array($total, $left);\n}"], [">> string_sequence(0)\n// \"0\"\n// >>> string_sequence(5)\n// \"0 1 2 3 4 5\"\nfunction string_sequence($n) {\n $sequence = \"\";\n for ($i = 0; $i <= $n; $i++) {\n $sequence .= $i . \" \";\n }\n return trim($sequence);\n}\n\necho string_sequence(0); // Output: \"0\"\necho string_sequence(5); // Output: \"0 1 2 3 4 5\""], [" result = 9\n// Note:\n// The length of operator array is equal to the length of operand array minus one.\n// Operand is an array of of non-negative integers.\n// Operator array has at least one operator, and operand array has at least two operands.\nfunction do_algebra($operator, $operand) {\n $result = $operand[0];\n for ($i = 1; $i < count($operand); $i++) {\n switch ($operator[$i-1]) {\n case '+':\n $result += $operand[$i];\n break;\n case '-':\n $result -= $operand[$i];\n break;\n case '*':\n $result *= $operand[$i];\n break;\n case '//':\n $result = floor($result / $operand[$i]);\n break;\n case '**':\n $result = pow($result, $operand[$i]);\n break;\n }\n }\n return $result;\n}\n\n$operator = ['+', '*', '-'];\n$operand = [2, 3, 4, 5];\n$result = do_algebra($operator, $operand);\necho $result; // Output: 9"], [">> solve(\"1234\")\n// \"4321\"\n// >>> solve(\"ab\")\n// \"AB\"\n// >>> solve(\"#a@C\")\n// \"#A@c\"\nfunction solve($s) {\n $letters = [];\n $result = \"\";\n for ($i = 0; $i < strlen($s); $i++) {\n if (ctype_alpha($s[$i])) {\n $letters[] = $s[$i];\n }\n }\n if (count($letters) == 0) {\n return strrev($s);\n }\n for ($i = 0; $i < strlen($s); $i++) {\n if (ctype_alpha($s[$i])) {\n $result .= ctype_upper($s[$i]) ? strtolower($letters[count($letters) - 1]) : strtoupper($letters[count($letters) - 1]);\n array_pop($letters);\n } else {\n $result .= $s[$i];\n }\n }\n return $result;\n}\n\necho solve(\"1234\") . \"\\n\"; // Output: \"4321\"\necho solve(\"ab\") . \"\\n\"; // Output: \"AB\"\necho solve(\"#a@C\") . \"\\n\"; // Output: \"#A@c\""], [">> string_to_md5(\"Hello world\")\n// \"3e25960a79dbc69b674cd4ec67a72c62\"\nfunction string_to_md5($text) {\n if (empty($text)) {\n return null;\n }\n return md5($text);\n}\n"], [">> generate_integers(2, 8)\n// array(2, 4, 6, 8)\n// >>> generate_integers(8, 2)\n// array(2, 4, 6, 8)\n// >>> generate_integers(10, 14)\n// array()\nfunction generate_integers($a, $b) {\n $result = array();\n for ($i = $a; $i <= $b; $i++) {\n $digits = str_split(strval($i));\n foreach ($digits as $digit) {\n if ($digit % 2 == 0) {\n array_push($result, $digit);\n }\n }\n }\n sort($result);\n return $result;\n}\n"], [">> count_distinct_characters(\"xyzXYZ\")\n// 3\n// >>> count_distinct_characters(\"Jerry\")\n// 4\nfunction count_distinct_characters($string) {\n $string = strtolower($string); // convert string to lowercase\n $char_array = str_split($string); // split string into an array of characters\n $char_array = array_unique($char_array); // remove duplicates from array\n return count($char_array); // return the count of unique characters\n}\n\necho count_distinct_characters(\"xyzXYZ\"); // output: 3\necho count_distinct_characters(\"Jerry\"); // output: 4"], [">> parse_music(\"o o| .| o| o| .| .| .| .| o o\")\n// array(4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4)\nfunction parse_music($music_string) {\n $beats = array();\n $notes = explode(' ', $music_string);\n foreach ($notes as $note) {\n switch ($note) {\n case 'o':\n $beats[] = 4;\n break;\n case 'o|':\n $beats[] = 2;\n break;\n case '.|':\n $beats[] = 1;\n break;\n }\n }\n return $beats;\n}\n\n$music_string = \"o o| .| o| o| .| .| .| .| o o\";\n$beats = parse_music($music_string);\nprint_r($beats);"], [">> how_many_times(\"\", \"a\")\n// 0\n// >>> how_many_times(\"aaa\", \"a\")\n// 3\n// >>> how_many_times(\"aaaa\", \"aa\")\n// 3\nfunction how_many_times($string, $substring) {\n $count = 0;\n $offset = 0;\n while (($pos = strpos($string, $substring, $offset)) !== false) {\n $count++;\n $offset = $pos + 1;\n }\n return $count;\n}\n\necho how_many_times(\"\", \"a\"); // 0\necho how_many_times(\"aaa\", \"a\"); // 3\necho how_many_times(\"aaaa\", \"aa\"); // 3"], [">> sort_numbers(\"three one five\")\n// \"one three five\"\nfunction sort_numbers($numbers) {\n $numbers_array = explode(\" \", $numbers);\n $sorted_array = array();\n foreach ($numbers_array as $number) {\n switch ($number) {\n case \"zero\":\n $sorted_array[] = 0;\n break;\n case \"one\":\n $sorted_array[] = 1;\n break;\n case \"two\":\n $sorted_array[] = 2;\n break;\n case \"three\":\n $sorted_array[] = 3;\n break;\n case \"four\":\n $sorted_array[] = 4;\n break;\n case \"five\":\n $sorted_array[] = 5;\n break;\n case \"six\":\n $sorted_array[] = 6;\n break;\n case \"seven\":\n $sorted_array[] = 7;\n break;\n case \"eight\":\n $sorted_array[] = 8;\n break;\n case \"nine\":\n $sorted_array[] = 9;\n break;\n }\n }\n sort($sorted_array);\n $sorted_numbers = \"\";\n foreach ($sorted_array as $number) {\n switch ($number) {\n case 0:\n $sorted_numbers .= \"zero \";\n break;\n case 1:\n $sorted_numbers .= \"one \";\n break;\n case 2:\n $sorted_numbers .= \"two \";\n break;\n case 3:\n $sorted_numbers .= \"three \";\n break;\n case 4:\n $sorted_numbers .= \"four \";\n break;\n case 5:\n $sorted_numbers .= \"five \";\n break;\n case 6:\n $sorted_numbers .= \"six \";\n break;\n case 7:\n $sorted_numbers .= \"seven \";\n break;\n case 8:\n $sorted_numbers .= \"eight \";\n break;\n case 9:\n $sorted_numbers .= \"nine \";\n break;\n }\n }\n return trim($sorted_numbers);\n}\n\necho sort_numbers(\"three one five\");"], [">> separate_paren_groups(\"( ) (( )) (( )( ))\")\n// array(\"()\", \"(())\", \"(()())\")\nfunction separate_paren_groups($paren_string) {\n $groups = array();\n $current_group = \"\";\n $open_count = 0;\n\n for ($i = 0; $i < strlen($paren_string); $i++) {\n $char = $paren_string[$i];\n\n if ($char == \"(\") {\n $open_count++;\n } elseif ($char == \")\") {\n $open_count--;\n }\n\n $current_group .= $char;\n\n if ($open_count == 0) {\n $groups[] = $current_group;\n $current_group = \"\";\n }\n }\n\n return $groups;\n}\n\n$paren_string = \"( ) (( )) (( )( ))\";\n$separated_groups = separate_paren_groups($paren_string);\nprint_r($separated_groups);"], [">> find_closest_elements(array(1.0, 2.0, 3.0, 4.0, 5.0, 2.2))\n// array(2.0, 2.2)\n// >>> find_closest_elements(array(1.0, 2.0, 3.0, 4.0, 5.0, 2.0))\n// array(2.0, 2.0)\nfunction find_closest_elements($numbers) {\n $closest_distance = INF;\n $closest_elements = array();\n for ($i = 0; $i < count($numbers) - 1; $i++) {\n for ($j = $i + 1; $j < count($numbers); $j++) {\n $distance = abs($numbers[$i] - $numbers[$j]);\n if ($distance < $closest_distance) {\n $closest_distance = $distance;\n $closest_elements = array($numbers[$i], $numbers[$j]);\n }\n }\n }\n sort($closest_elements);\n return $closest_elements;\n}\n\n$numbers = array(1.0, 2.0, 3.0, 4.0, 5.0, 2.2);\nprint_r(find_closest_elements($numbers));\n\n$numbers = array(1.0, 2.0, 3.0, 4.0, 5.0, 2.0);\nprint_r(find_closest_elements($numbers));"], [">> rescale_to_unit(array(1.0, 2.0, 3.0, 4.0, 5.0))\n// array(0.0, 0.25, 0.5, 0.75, 1.0)\nfunction rescale_to_unit($numbers) {\n $min_val = min($numbers);\n $max_val = max($numbers);\n $range = $max_val - $min_val;\n $rescaled_numbers = array();\n foreach ($numbers as $num) {\n $rescaled_numbers[] = ($num - $min_val) / $range;\n }\n return $rescaled_numbers;\n}\n\n$numbers = array(1.0, 2.0, 3.0, 4.0, 5.0);\n$rescaled_numbers = rescale_to_unit($numbers);\nprint_r($rescaled_numbers);"], [">> filter_integers(array(\"a\", 3.14, 5))\n// array(5)\n// >>> filter_integers(array(1, 2, 3, \"abc\", array(), array()))\n// array(1, 2, 3)\nfunction filter_integers($values) {\n $filtered = array();\n foreach ($values as $value) {\n if (is_int($value)) {\n $filtered[] = $value;\n }\n }\n return $filtered;\n}\n"], [">> strlen(\"\")\n// 0\n// >>> strlen(\"abc\")\n// 3\nfunction strlen($string) {\n $count = 0;\n while (isset($string[$count])) {\n $count++;\n }\n return $count;\n}\n\necho strlen(\"\"); // Output: 0\necho strlen(\"abc\"); // Output: 3"], [">> largest_divisor(15)\n// 5\nfunction largest_divisor($n) {\n for ($i = $n - 1; $i > 0; $i--) {\n if ($n % $i == 0) {\n return $i;\n }\n }\n}\n\necho largest_divisor(15); // Output: 5\n"], [">> factorize(8)\n// array(2, 2, 2)\n// >>> factorize(25)\n// array(5, 5)\n// >>> factorize(70)\n// array(2, 5, 7)\nfunction factorize($n) {\n $factors = array();\n $divisor = 2;\n while ($n > 1) {\n if ($n % $divisor == 0) {\n $factors[] = $divisor;\n $n /= $divisor;\n } else {\n $divisor++;\n }\n }\n return $factors;\n}\n"], [">> remove_duplicates(array(1, 2, 3, 2, 4))\n// array(1, 3, 4)\nfunction remove_duplicates($numbers) {\n $result = array();\n foreach ($numbers as $number) {\n if (!in_array($number, $result)) {\n $result[] = $number;\n }\n }\n return $result;\n}\n\n$numbers = array(1, 2, 3, 2, 4);\n$result = remove_duplicates($numbers);\nprint_r($result);"], [">> flip_case(\"Hello\")\n// \"hELLO\"\nfunction flip_case($string) {\n $flipped_string = \"\";\n for ($i = 0; $i < strlen($string); $i++) {\n $char = substr($string, $i, 1);\n if (ctype_upper($char)) {\n $flipped_string .= strtolower($char);\n } elseif (ctype_lower($char)) {\n $flipped_string .= strtoupper($char);\n } else {\n $flipped_string .= $char;\n }\n }\n return $flipped_string;\n}\n\necho flip_case(\"Hello\"); // Output: \"hELLO\""], [">> concatenate(array())\n// \"\"\n// >>> concatenate(array(\"a\", \"b\", \"c\"))\n// \"abc\"\nfunction concatenate($strings) {\n $result = \"\";\n foreach ($strings as $string) {\n $result .= $string;\n }\n return $result;\n}\n"], [">> filter_by_prefix(array(), \"a\")\n// array()\n// >>> filter_by_prefix(array(\"abc\", \"bcd\", \"cde\", \"array\"), \"a\")\n// array(\"abc\", \"array\")\nfunction filter_by_prefix($strings, $prefix) {\n $filtered_strings = array();\n foreach ($strings as $string) {\n if (strpos($string, $prefix) === 0) {\n $filtered_strings[] = $string;\n }\n }\n return $filtered_strings;\n}\n"], [">> truncate_number(3.5)\n// 0.5\nfunction truncate_number($number) {\n return $number - floor($number);\n}\n\necho truncate_number(3.5); // Output: 0.5"], [">> get_positive(array(-1, 2, -4, 5, 6))\n// array(2, 5, 6)\n// >>> get_positive(array(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))\n// array(5, 3, 2, 3, 9, 123, 1)\nfunction get_positive($l) {\n $result = array();\n foreach ($l as $num) {\n if ($num > 0) {\n array_push($result, $num);\n }\n }\n return $result;\n}\n"], [">> is_prime(6)\n// false\n// >>> is_prime(101)\n// true\n// >>> is_prime(11)\n// true\n// >>> is_prime(13441)\n// true\n// >>> is_prime(61)\n// true\n// >>> is_prime(4)\n// false\n// >>> is_prime(1)\n// false\nfunction is_prime($n) {\n if ($n <= 1) {\n return false;\n }\n for ($i = 2; $i <= sqrt($n); $i++) {\n if ($n % $i == 0) {\n return false;\n }\n }\n return true;\n}\n"], [">> sort_third(array(1, 2, 3))\n// array(1, 2, 3)\n// >>> sort_third(array(5, 6, 3, 4, 8, 9, 2))\n// array(2, 6, 3, 4, 8, 9, 5)\nfunction sort_third($l) {\n $l_prime = $l;\n $third_values = array();\n for ($i = 0; $i < count($l); $i++) {\n if (($i + 1) % 3 == 0) {\n array_push($third_values, $l[$i]);\n }\n }\n sort($third_values);\n $j = 0;\n for ($i = 0; $i < count($l); $i++) {\n if (($i + 1) % 3 == 0) {\n $l_prime[$i] = $third_values[$j];\n $j++;\n }\n }\n return $l_prime;\n}\n"], [">> unique(array(5, 3, 5, 2, 3, 3, 9, 0, 123))\n// array(0, 2, 3, 5, 9, 123)\nfunction unique($l) {\n sort($l);\n return array_values(array_unique($l));\n}\n\n$arr = array(5, 3, 5, 2, 3, 3, 9, 0, 123);\nprint_r(unique($arr));"], [">> max_element(array(1, 2, 3))\n// 3\n// >>> max_element(array(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))\n// 123\nfunction max_element($l) {\n return max($l);\n}\n\necho max_element(array(1, 2, 3)); // Output: 3\necho max_element(array(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10)); // Output: 123"], [">> fizz_buzz(50)\n// 0\n// >>> fizz_buzz(78)\n// 2\n// >>> fizz_buzz(79)\n// 3\nfunction fizz_buzz($n) {\n $count = 0;\n for ($i = 1; $i < $n; $i++) {\n if ($i % 11 == 0 || $i % 13 == 0) {\n $count += substr_count(strval($i), '7');\n }\n }\n return $count;\n}\n\necho fizz_buzz(50) . \"\\n\"; // Output: 0\necho fizz_buzz(78) . \"\\n\"; // Output: 2\necho fizz_buzz(79) . \"\\n\"; // Output: 3"], [">> sort_even(array(1, 2, 3))\n// array(1, 2, 3)\n// >>> sort_even(array(5, 6, 3, 4))\n// array(3, 6, 5, 4)\nfunction sort_even($l) {\n $even_values = array();\n for ($i = 0; $i < count($l); $i += 2) {\n array_push($even_values, $l[$i]);\n }\n sort($even_values);\n $result = array();\n for ($i = 0; $i < count($l); $i++) {\n if ($i % 2 == 0) {\n array_push($result, $l[$i]);\n } else {\n array_push($result, $even_values[$i/2]);\n }\n }\n return $result;\n}\n"], [">> prime_fib(1)\n// 2\n// >>> prime_fib(2)\n// 3\n// >>> prime_fib(3)\n// 5\n// >>> prime_fib(4)\n// 13\n// >>> prime_fib(5)\n// 89\nfunction prime_fib($n) {\n $fib = [0, 1];\n $i = 2;\n while (count($fib) < $n) {\n $fib[$i] = $fib[$i-1] + $fib[$i-2];\n $i++;\n }\n $prime_fib = [];\n foreach ($fib as $num) {\n if (is_prime($num)) {\n $prime_fib[] = $num;\n }\n }\n return $prime_fib[$n-1];\n}\n"], [">> below_zero(array(1, 2, 3))\n// false\n// >>> below_zero(array(1, 2, -4, 5))\n// true\nfunction below_zero($operations) {\n $balance = 0;\n foreach ($operations as $operation) {\n $balance += $operation;\n if ($balance < 0) {\n return true;\n }\n }\n return false;\n}\n"], [">> triples_sum_to_zero(array(1, 3, 5, 0))\n// false\n// >>> triples_sum_to_zero(array(1, 3, -2, 1))\n// true\n// >>> triples_sum_to_zero(array(1, 2, 3, 7))\n// false\n// >>> triples_sum_to_zero(array(2, 4, -5, 3, 9, 7))\n// true\n// >>> triples_sum_to_zero(array(1))\n// false\nfunction triples_sum_to_zero($l) {\n // Sort the array in ascending order.\n sort($l);\n\n // Iterate through the array, checking if there are three distinct\n // elements that sum to zero.\n for ($i = 0; $i < count($l) - 2; $i++) {\n // If the current element is the same as the previous one, skip it.\n if ($i > 0 && $l[$i] == $l[$i - 1]) {\n continue;\n }\n\n // Set two pointers, one at the beginning of the array and one at the\n // end.\n $j = $i + 1;\n $k = count($l) - 1;\n\n // Iterate through the remaining elements, checking if there are two\n // elements that sum to the negative of the current element.\n while ($j < $k) {\n // If the sum of the current elements is zero, return true.\n if ($l[$i] + $l[$j] + $l[$k] == 0) {\n return true;\n }\n\n // If the sum is too small, move the left pointer to the right.\n if ($l[$i] + $l[$j] + $l[$k] < 0) {\n $j++;\n }\n\n // If the sum is too large, move the right pointer to the left.\n else {\n $k--;\n }\n }\n }\n\n // If no three distinct elements sum to zero, return false.\n return false;\n}\n"], [">> incr_list(array(1, 2, 3))\n// array(2, 3, 4)\n// >>> incr_list(array(5, 3, 5, 2, 3, 3, 9, 0, 123))\n// array(6, 4, 6, 3, 4, 4, 10, 1, 124)\nfunction incr_list($l) {\n $result = array();\n foreach ($l as $item) {\n array_push($result, $item + 1);\n }\n return $result;\n}\n"], [">> pairs_sum_to_zero(array(1, 3, 5, 0))\n// false\n// >>> pairs_sum_to_zero(array(1, 3, -2, 1))\n// false\n// >>> pairs_sum_to_zero(array(1, 2, 3, 7))\n// false\n// >>> pairs_sum_to_zero(array(2, 4, -5, 3, 5, 7))\n// true\n// >>> pairs_sum_to_zero(array(1))\n// false\nfunction pairs_sum_to_zero($l) {\n // create an empty set to store the seen elements\n $seen = array();\n // iterate over the array\n foreach ($l as $num) {\n // check if the negative of the current number has been seen\n if (in_array(-$num, $seen)) {\n return true;\n }\n // add the current number to the set of seen elements\n $seen[] = $num;\n }\n // if no pairs sum to zero were found, return false\n return false;\n}\n"], [">> change_base(8, 3)\n// \"22\"\n// >>> change_base(8, 2)\n// \"1000\"\n// >>> change_base(7, 2)\n// \"111\"\nfunction change_base($x, $base) {\n $result = \"\";\n while ($x > 0) {\n $remainder = $x % $base;\n $result = $remainder . $result;\n $x = floor($x / $base);\n }\n return $result;\n}\n"], [">> triangle_area(5, 3)\n// 7.5\nfunction triangle_area($a, $h) {\n return ($a * $h) / 2;\n}\n\necho triangle_area(5, 3);"], [" 0\n// fib4(1) -> 0\n// fib4(2) -> 2\n// fib4(3) -> 0\n// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n// >>> fib4(5)\n// 4\n// >>> fib4(6)\n// 8\n// >>> fib4(7)\n// 14\nfunction fib4($n) {\n if ($n < 4) {\n return $n == 2 ? 2 : 0;\n }\n $a = 0;\n $b = 0;\n $c = 2;\n $d = 0;\n for ($i = 4; $i <= $n; $i++) {\n $temp = $a + $b + $c + $d;\n $a = $b;\n $b = $c;\n $c = $d;\n $d = $temp;\n }\n return $d;\n}\n\necho fib4(5) . \"\\n\"; // Output: 4\necho fib4(6) . \"\\n\"; // Output: 8\necho fib4(7) . \"\\n\"; // Output: 14"], [">> median(array(3, 1, 2, 4, 5))\n// 3\n// >>> median(array(-10, 4, 6, 1000, 10, 20))\n// 15.0\nfunction median($l) {\n sort($l);\n $n = count($l);\n if ($n % 2 == 0) {\n return ($l[$n/2 - 1] + $l[$n/2]) / 2;\n } else {\n return $l[floor($n/2)];\n }\n}\n\necho median(array(3, 1, 2, 4, 5)) . \"\\n\";\necho median(array(-10, 4, 6, 1000, 10, 20)) . \"\\n\";"], [">> is_palindrome(\"\")\n// true\n// >>> is_palindrome(\"aba\")\n// true\n// >>> is_palindrome(\"aaaaa\")\n// true\n// >>> is_palindrome(\"zbcd\")\n// false\nfunction is_palindrome($text) {\n $reversed = strrev($text);\n if ($text == $reversed) {\n return true;\n } else {\n return false;\n }\n}\n"], [">> modp(3, 5)\n// 3\n// >>> modp(1101, 101)\n// 2\n// >>> modp(0, 101)\n// 1\n// >>> modp(3, 11)\n// 8\n// >>> modp(100, 101)\n// 1\nfunction modp($n, $p) {\n return pow(2, $n) % $p;\n}\n\necho modp(3, 5) . \"\\n\"; // Output: 3\necho modp(1101, 101) . \"\\n\"; // Output: 2\necho modp(0, 101) . \"\\n\"; // Output: 1\necho modp(3, 11) . \"\\n\"; // Output: 8\necho modp(100, 101) . \"\\n\"; // Output: 1"], [">> mean_absolute_deviation(array(1.0, 2.0, 3.0, 4.0))\n// 1.0\nfunction mean_absolute_deviation($numbers) {\n $mean = array_sum($numbers) / count($numbers);\n $deviations = array_map(function($x) use ($mean) {\n return abs($x - $mean);\n }, $numbers);\n $mad = array_sum($deviations) / count($deviations);\n return $mad;\n}\n\n$numbers = array(1.0, 2.0, 3.0, 4.0);\n$mad = mean_absolute_deviation($numbers);\necho $mad;"], [">> remove_vowels(\"\")\n// \"\"\n// >>> remove_vowels(\"abcdef\")\n// \"bcdf\"\n// >>> remove_vowels(\"aaaaa\")\n// \"\"\n// >>> remove_vowels(\"aaBAA\")\n// \"B\"\n// >>> remove_vowels(\"zbcd\")\n// \"zbcd\"\nfunction remove_vowels($text) {\n $vowels = array(\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", \"I\", \"O\", \"U\");\n $result = str_replace($vowels, \"\", $text);\n return $result;\n}\n\necho remove_vowels(\"\"); // \"\"\necho remove_vowels(\"abcdef\"); // \"bcdf\"\necho remove_vowels(\"aaaaa\"); // \"\"\necho remove_vowels(\"aaBAA\"); // \"B\"\necho remove_vowels(\"zbcd\"); // \"zbcd\""], [">> below_threshold(array(1, 2, 4, 10), 100)\n// true\n// >>> below_threshold(array(1, 20, 4, 10), 5)\n// false\nfunction below_threshold($l, $t) {\n foreach ($l as $num) {\n if ($num >= $t) {\n return false;\n }\n }\n return true;\n}\n"], [">> add(2, 3)\n// 5\n// >>> add(5, 7)\n// 12\nfunction add($x, $y) {\n return $x + $y;\n}\n"], [">> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddeddabc\")\n// true\n// >>> same_chars(\"abcd\", \"dddddddabc\")\n// true\n// >>> same_chars(\"dddddddabc\", \"abcd\")\n// true\n// >>> same_chars(\"eabcd\", \"dddddddabc\")\n// false\n// >>> same_chars(\"abcd\", \"dddddddabce\")\n// false\n// >>> same_chars(\"eabcdzzzz\", \"dddzzzzzzzddddabc\")\n// false\nfunction same_chars($s0, $s1) {\n $chars0 = count_chars($s0, 1);\n $chars1 = count_chars($s1, 1);\n return $chars0 == $chars1;\n}\n"], [">> fib(10)\n// 55\n// >>> fib(1)\n// 1\n// >>> fib(8)\n// 21\nfunction fib($n) {\n if ($n <= 1) {\n return $n;\n }\n return fib($n - 1) + fib($n - 2);\n}\n\necho fib(10) . \"\\n\"; // Output: 55\necho fib(1) . \"\\n\"; // Output: 1\necho fib(8) . \"\\n\"; // Output: 21"], ["\".\n// return true if every opening bracket has a corresponding closing bracket.\n// >>> correct_bracketing(\"<\")\n// false\n// >>> correct_bracketing(\"<>\")\n// true\n// >>> correct_bracketing(\"<<><>>\")\n// true\n// >>> correct_bracketing(\"><<>\")\n// false\nfunction correct_bracketing($brackets) {\n $stack = array();\n for ($i = 0; $i < strlen($brackets); $i++) {\n if ($brackets[$i] == \"<\") {\n array_push($stack, \"<\");\n } else {\n if (empty($stack)) {\n return false;\n }\n array_pop($stack);\n }\n }\n return empty($stack);\n}\n"], [">> monotonic(array(1, 2, 4, 20))\n// true\n// >>> monotonic(array(1, 20, 4, 10))\n// false\n// >>> monotonic(array(4, 1, 0, -10))\n// true\nfunction monotonic($l) {\n $increasing = true;\n $decreasing = true;\n for ($i = 0; $i < count($l) - 1; $i++) {\n if ($l[$i] > $l[$i + 1]) {\n $increasing = false;\n }\n if ($l[$i] < $l[$i + 1]) {\n $decreasing = false;\n }\n }\n return $increasing || $decreasing;\n}\n"], [">> common(array(1, 4, 3, 34, 653, 2, 5), array(5, 7, 1, 5, 9, 653, 121))\n// array(1, 5, 653)\n// >>> common(array(5, 3, 2, 8), array(3, 2))\n// array(2, 3)\nfunction common($l1, $l2) {\n $common = array_intersect($l1, $l2);\n sort($common);\n return array_unique($common);\n}\n\n$result1 = common(array(1, 4, 3, 34, 653, 2, 5), array(5, 7, 1, 5, 9, 653, 121));\nprint_r($result1);\n\n$result2 = common(array(5, 3, 2, 8), array(3, 2));\nprint_r($result2);"], [" 1 and is not a prime.\n// >>> largest_prime_factor(13195)\n// 29\n// >>> largest_prime_factor(2048)\n// 2\nfunction largest_prime_factor($n) {\n $i = 2;\n while ($i * $i <= $n) {\n if ($n % $i == 0) {\n $n /= $i;\n } else {\n $i++;\n }\n }\n return $n;\n}\n\necho largest_prime_factor(13195); // Output: 29\necho largest_prime_factor(2048); // Output: 2"], [">> intersperse(array(), 4)\n// array()\n// >>> intersperse(array(1, 2, 3), 4)\n// array(1, 4, 2, 4, 3)\nfunction intersperse($numbers, $delimeter) {\n $result = array();\n foreach ($numbers as $number) {\n $result[] = $number;\n $result[] = $delimeter;\n }\n array_pop($result); // remove the last delimeter\n return $result;\n}\n"], [">> sum_to_n(30)\n// 465\n// >>> sum_to_n(100)\n// 5050\n// >>> sum_to_n(5)\n// 15\n// >>> sum_to_n(10)\n// 55\n// >>> sum_to_n(1)\n// 1\nfunction sum_to_n($n) {\n return ($n * ($n + 1)) / 2;\n}\n\necho sum_to_n(30) . \"\\n\"; // Output: 465\necho sum_to_n(100) . \"\\n\"; // Output: 5050\necho sum_to_n(5) . \"\\n\"; // Output: 15\necho sum_to_n(10) . \"\\n\"; // Output: 55\necho sum_to_n(1) . \"\\n\"; // Output: 1"], [">> correct_bracketing(\"(\")\n// false\n// >>> correct_bracketing(\"()\")\n// true\n// >>> correct_bracketing(\"(()())\")\n// true\n// >>> correct_bracketing(\")(()\")\n// false\nfunction correct_bracketing($brackets) {\n $stack = array();\n for ($i = 0; $i < strlen($brackets); $i++) {\n if ($brackets[$i] == \"(\") {\n array_push($stack, \"(\");\n } else if ($brackets[$i] == \")\") {\n if (empty($stack)) {\n return false;\n }\n array_pop($stack);\n }\n }\n return empty($stack);\n}\n"], [">> derivative(array(3, 1, 2, 4, 5))\n// array(1, 4, 12, 20)\n// >>> derivative(array(1, 2, 3))\n// array(2, 6)\nfunction derivative($xs) {\n $result = array();\n for ($i = 1; $i < count($xs); $i++) {\n $result[] = $i * $xs[$i];\n }\n return $result;\n}\n"], [">> fibfib(1)\n// 0\n// >>> fibfib(5)\n// 4\n// >>> fibfib(8)\n// 24\nfunction fibfib($n) {\n if ($n == 0) {\n return 0;\n } elseif ($n == 1) {\n return 0;\n } elseif ($n == 2) {\n return 1;\n } else {\n return fibfib($n-1) + fibfib($n-2) + fibfib($n-3);\n }\n}\n"], [">> vowels_count(\"abcde\")\n// 2\n// >>> vowels_count(\"ACEDY\")\n// 3\nfunction vowels_count($s) {\n $vowels = array('a', 'e', 'i', 'o', 'u', 'y');\n $count = 0;\n for ($i = 0; $i < strlen($s); $i++) {\n if (in_array(strtolower($s[$i]), $vowels)) {\n $count++;\n }\n }\n return $count;\n}\n"], [" number of digits, return digits reversed.\n// >>> circular_shift(12, 1)\n// \"21\"\n// >>> circular_shift(12, 2)\n// \"12\"\nfunction circular_shift($x, $shift) {\n $digits = str_split(strval($x));\n $num_digits = count($digits);\n if ($shift > $num_digits) {\n $shift = $num_digits;\n }\n $shifted_digits = array_slice($digits, -$shift);\n $remaining_digits = array_slice($digits, 0, $num_digits - $shift);\n $result = array_merge($shifted_digits, $remaining_digits);\n return implode(\"\", $result);\n}\n\necho circular_shift(12, 1); // Output: \"21\"\necho circular_shift(12, 2); // Output: \"12\""], [">> digitSum(\"\")\n// 0\n// >>> digitSum(\"abAB\")\n// 131\n// >>> digitSum(\"abcCd\")\n// 67\n// >>> digitSum(\"helloE\")\n// 69\n// >>> digitSum(\"woArBld\")\n// 131\n// >>> digitSum(\"aAaaaXa\")\n// 153\nfunction digitSum($s) {\n $sum = 0;\n for ($i = 0; $i < strlen($s); $i++) {\n if (ctype_upper($s[$i])) {\n $sum += ord($s[$i]);\n }\n }\n return $sum;\n}\n"], [">> fruit_distribution(\"5 apples and 6 oranges\", 19)\n// 8\n// >>> fruit_distribution(\"0 apples and 1 oranges\", 3)\n// 2\n// >>> fruit_distribution(\"2 apples and 3 oranges\", 100)\n// 95\n// >>> fruit_distribution(\"100 apples and 1 oranges\", 120)\n// 19\nfunction fruit_distribution($s, $n) {\n $fruit_count = explode(\" and \", $s);\n $apples = intval($fruit_count[0]);\n $oranges = intval($fruit_count[1]);\n $total_fruits = $apples + $oranges;\n $mango_fruits = $n - $total_fruits;\n return $mango_fruits;\n}\n\necho fruit_distribution(\"5 apples and 6 oranges\", 19); // Output: 8\necho fruit_distribution(\"0 apples and 1 oranges\", 3); // Output: 2\necho fruit_distribution(\"2 apples and 3 oranges\", 100); // Output: 95\necho fruit_distribution(\"100 apples and 1 oranges\", 120); // Output: 19"], [">> pluck(array(4, 2, 3))\n// array(2, 1)\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 2:\n// >>> pluck(array(1, 2, 3))\n// array(2, 1)\n// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n// Example 3:\n// >>> pluck(array())\n// array()\n// Example 4:\n// >>> pluck(array(5, 0, 3, 0, 4, 2))\n// array(0, 1)\n// Explanation: 0 is the smallest value, but there are two zeros,\n// so we will choose the first zero, which has the smallest index.\n// Constraints:\n// * 1 <= nodes.length <= 10000\n// * 0 <= node.value\nfunction pluck($arr) {\n $even_values = array_filter($arr, function($val) {\n return $val % 2 == 0;\n });\n if (empty($even_values)) {\n return [];\n }\n $min_even_val = min($even_values);\n $min_even_index = array_search($min_even_val, $arr);\n return [$min_even_val, $min_even_index];\n}"], [">> search(array(4, 1, 2, 2, 3, 1))\n// 2\n// >>> search(array(1, 2, 2, 3, 3, 3, 4, 4, 4))\n// 3\n// >>> search(array(5, 5, 4, 4, 4))\n// -1\nfunction search($lst) {\n $counts = array_count_values($lst);\n rsort($counts);\n foreach ($counts as $num => $count) {\n if ($num <= $count) {\n return $num;\n }\n }\n return -1;\n}\n\necho search(array(4, 1, 2, 2, 3, 1)); // Output: 2\necho search(array(1, 2, 2, 3, 3, 3, 4, 4, 4)); // Output: 3\necho search(array(5, 5, 4, 4, 4)); // Output: -1"], [">> parse_nested_parens(\"(()()) ((())) () ((())()())\")\n// array(2, 3, 1, 3)\nfunction parse_nested_parens($paren_string) {\n $paren_groups = explode(\" \", $paren_string);\n $max_depths = array();\n foreach ($paren_groups as $group) {\n $depth = 0;\n $max_depth = 0;\n for ($i = 0; $i < strlen($group); $i++) {\n if ($group[$i] == \"(\") {\n $depth++;\n if ($depth > $max_depth) {\n $max_depth = $depth;\n }\n } else if ($group[$i] == \")\") {\n $depth--;\n }\n }\n $max_depths[] = $max_depth;\n }\n return $max_depths;\n}\n\n$result = parse_nested_parens(\"(()()) ((())) () ((())()())\");\nprint_r($result);"], [">> strange_sort_list(array(1, 2, 3, 4))\n// array(1, 4, 2, 3)\n// >>> strange_sort_list(array(5, 5, 5, 5))\n// array(5, 5, 5, 5)\n// >>> strange_sort_list(array())\n// array()\nfunction strange_sort_list($lst) {\n $result = array();\n while (count($lst) > 0) {\n $result[] = min($lst);\n $result[] = max($lst);\n array_splice($lst, array_search(min($lst), $lst), 1);\n array_splice($lst, array_search(max($lst), $lst), 1);\n }\n return $result;\n}\n"], [">> triangle_area(3, 4, 5)\n// 6.0\n// >>> triangle_area(1, 2, 10)\n// -1\nfunction triangle_area($a, $b, $c) {\n if ($a + $b > $c && $a + $c > $b && $b + $c > $a) {\n $s = ($a + $b + $c) / 2;\n $area = sqrt($s * ($s - $a) * ($s - $b) * ($s - $c));\n return round($area, 2);\n } else {\n return -1;\n }\n}\n\necho triangle_area(3, 4, 5) . \"\\n\"; // Output: 6.0\necho triangle_area(1, 2, 10) . \"\\n\"; // Output: -1"], [">> will_it_fly(array(1, 2), 5)\n// false\n// # 1+2 is less than the maximum possible weight, but it's unbalanced.\n// >>> will_it_fly(array(3, 2, 3), 1)\n// false\n// # it's balanced, but 3+2+3 is more than the maximum possible weight.\n// >>> will_it_fly(array(3, 2, 3), 9)\n// true\n// # 3+2+3 is less than the maximum possible weight, and it's balanced.\n// >>> will_it_fly(array(3), 5)\n// true\n// # 3 is less than the maximum possible weight, and it's balanced.\nfunction will_it_fly($q, $w) {\n // Check if the array is balanced (palindromic)\n $reversed_q = array_reverse($q);\n if ($q != $reversed_q) {\n return false;\n }\n // Check if the sum of the elements is less than or equal to the maximum possible weight\n $sum = array_sum($q);\n if ($sum > $w) {\n return false;\n }\n return true;\n}\n"], [">> smallest_change(array(1, 2, 3, 5, 4, 7, 9, 6))\n// 4\n// >>> smallest_change(array(1, 2, 3, 4, 3, 2, 2))\n// 1\n// >>> smallest_change(array(1, 2, 3, 2, 1))\n// 0\nfunction smallest_change($arr) {\n $n = count($arr);\n $count = 0;\n for ($i = 0; $i < $n / 2; $i++) {\n if ($arr[$i] != $arr[$n - $i - 1]) {\n $count++;\n }\n }\n return $count;\n}\n"], [">> total_match(array(), array())\n// array()\n// >>> total_match(array(\"hi\", \"admin\"), array(\"hI\", \"Hi\"))\n// array(\"hI\", \"Hi\")\n// >>> total_match(array(\"hi\", \"admin\"), array(\"hi\", \"hi\", \"admin\", \"project\"))\n// array(\"hi\", \"admin\")\n// >>> total_match(array(\"hi\", \"admin\"), array(\"hI\", \"hi\", \"hi\"))\n// array(\"hI\", \"hi\", \"hi\")\n// >>> total_match(array(\"4\"), array(\"1\", \"2\", \"3\", \"4\", \"5\"))\n// array(\"4\")\nfunction total_match($lst1, $lst2) {\n $total1 = array_reduce($lst1, function($acc, $str) {\n return $acc + strlen($str);\n }, 0);\n $total2 = array_reduce($lst2, function($acc, $str) {\n return $acc + strlen($str);\n }, 0);\n if ($total1 < $total2) {\n return $lst1;\n } elseif ($total1 > $total2) {\n return $lst2;\n } else {\n return $lst1;\n }\n}"], [">> is_multiply_prime(30)\n// true\n// 30 = 2 * 3 * 5\nfunction is_multiply_prime($a) {\n // Check if the number is less than 100\n if ($a >= 100) {\n return false;\n }\n\n // Check if the number is a multiple of 3 prime numbers\n $primes = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);\n foreach ($primes as $prime) {\n if ($a % $prime == 0) {\n $a /= $prime;\n }\n }\n return $a == 1;\n}\n"], [">> is_simple_power(1, 4)\n// true\n// >>> is_simple_power(2, 2)\n// true\n// >>> is_simple_power(8, 2)\n// true\n// >>> is_simple_power(3, 2)\n// false\n// >>> is_simple_power(3, 1)\n// false\n// >>> is_simple_power(5, 3)\n// false\nfunction is_simple_power($x, $n) {\n if ($n == 1) {\n return $x == 1;\n }\n $power = 1;\n while ($power < $x) {\n $power *= $n;\n }\n return $power == $x;\n}\n"], [">> iscube(1)\n// true\n// >>> iscube(2)\n// false\n// >>> iscube(-1)\n// true\n// >>> iscube(64)\n// true\n// >>> iscube(0)\n// true\n// >>> iscube(180)\n// false\nfunction iscube($a) {\n $cube_root = round(pow(abs($a), 1/3));\n return pow($cube_root, 3) == $a;\n}\n"], [">> hex_key(\"AB\")\n// 1\n// >>> hex_key(\"1077E\")\n// 2\n// >>> hex_key(\"ABED1A33\")\n// 4\n// >>> hex_key(\"123456789ABCDEF0\")\n// 6\n// >>> hex_key(\"2020\")\n// 2\nfunction hex_key($num) {\n $primes = array(2, 3, 5, 7, 11, 13);\n $count = 0;\n for ($i = 0; $i < strlen($num); $i++) {\n $digit = hexdec($num[$i]);\n if (in_array($digit, $primes)) {\n $count++;\n }\n }\n return $count;\n}"], [">> decimal_to_binary(15)\n// \"db1111db\"\n// >>> decimal_to_binary(32)\n// \"db100000db\"\nfunction decimal_to_binary($decimal) {\n $binary = decbin($decimal);\n return \"db\" . $binary . \"db\";\n}"], [">> filter_by_substring(array(), \"a\")\n// array()\n// >>> filter_by_substring(array(\"abc\", \"bacd\", \"cde\", \"array\"), \"a\")\n// array(\"abc\", \"bacd\", \"array\")\nfunction filter_by_substring($strings, $substring) {\n $filtered_strings = array();\n foreach ($strings as $string) {\n if (strpos($string, $substring) !== false) {\n array_push($filtered_strings, $string);\n }\n }\n return $filtered_strings;\n}\n"], [">> is_happy(\"a\")\n// false\n// >>> is_happy(\"aa\")\n// false\n// >>> is_happy(\"abcd\")\n// true\n// >>> is_happy(\"aabb\")\n// false\n// >>> is_happy(\"adb\")\n// true\n// >>> is_happy(\"xyy\")\n// false\nfunction is_happy($s) {\n if (strlen($s) < 3) {\n return false;\n }\n for ($i = 0; $i < strlen($s) - 2; $i++) {\n if ($s[$i] == $s[$i+1] || $s[$i] == $s[$i+2] || $s[$i+1] == $s[$i+2]) {\n return false;\n }\n }\n return true;\n}\n"], [" 3.7 A \n// > 3.3 A- \n// > 3.0 B+\n// > 2.7 B \n// > 2.3 B-\n// > 2.0 C+\n// > 1.7 C\n// > 1.3 C-\n// > 1.0 D+ \n// > 0.7 D \n// > 0.0 D-\n// 0.0 E\n// Example:\n// >>> grade_equation(array(4.0, 3, 1.7, 2, 3.5))\n// array(\"A+\", \"B\", \"C-\", \"C\", \"A-\")\nfunction numerical_letter_grade($grades) {\n $letter_grades = array();\n foreach ($grades as $grade) {\n if ($grade == 4.0) {\n $letter_grades[] = \"A+\";\n } elseif ($grade > 3.7) {\n $letter_grades[] = \"A\";\n } elseif ($grade > 3.3) {\n $letter_grades[] = \"A-\";\n } elseif ($grade > 3.0) {\n $letter_grades[] = \"B+\";\n } elseif ($grade > 2.7) {\n $letter_grades[] = \"B\";\n } elseif ($grade > 2.3) {\n $letter_grades[] = \"B-\";\n } elseif ($grade > 2.0) {\n $letter_grades[] = \"C+\";\n } elseif ($grade > 1.7) {\n $letter_grades[] = \"C\";\n } elseif ($grade > 1.3) {\n $letter_grades[] = \"C-\";\n } elseif ($grade > 1.0) {\n $letter_grades[] = \"D+\";\n } elseif ($grade > 0.7) {\n $letter_grades[] = \"D\";\n } elseif ($grade > 0.0) {\n $letter_grades[] = \"D-\";\n } else {\n $letter_grades[] = \"E\";\n }\n }\n return $letter_grades;\n}\n\n$grades = array(4.0, 3, 1.7, 2, 3.5);\n$letter_grades = numerical_letter_grade($grades);\nprint_r($letter_grades);"], [">> prime_length(\"Hello\")\n// true\n// >>> prime_length(\"abcdcba\")\n// true\n// >>> prime_length(\"kittens\")\n// true\n// >>> prime_length(\"orange\")\n// false\nfunction prime_length($string) {\n // Get the length of the string\n $length = strlen($string);\n\n // Check if the length is less than 2 (since prime numbers start from 2)\n if ($length < 2) {\n return false;\n }\n\n // Check if the length is divisible by any number between 2 and the square root of the length\n for ($i = 2; $i <= sqrt($length); $i++) {\n if ($length % $i == 0) {\n return false;\n }\n }\n\n // If the length is not divisible by any number, it is a prime number\n return true;\n}\n"], [">> solve(1000)\n// \"1\"\n// >>> solve(150)\n// \"110\"\n// >>> solve(147)\n// \"1100\"\n// Variables:\n// @N integer\n// Constraints: 0 \u2264 N \u2264 10000.\n// Output:\n// a string of binary number\nfunction solve($N) {\n $sum = 0;\n while ($N > 0) {\n $sum += $N % 10;\n $N = floor($N / 10);\n }\n return decbin($sum);\n}"], [">> add(array(4, 2, 6, 7))\n// 2\nfunction add($lst) {\n $sum = 0;\n for ($i = 1; $i < count($lst); $i += 2) {\n if ($lst[$i] % 2 == 0) {\n $sum += $lst[$i];\n }\n }\n return $sum;\n}\n"], [">> anti_shuffle(\"Hi\")\n// \"Hi\"\n// >>> anti_shuffle(\"hello\")\n// \"ehllo\"\n// >>> anti_shuffle(\"Hello World!!!\")\n// \"Hello !!!Wdlor\"\nfunction anti_shuffle($s) {\n $words = explode(\" \", $s);\n $new_words = array();\n foreach ($words as $word) {\n $chars = str_split($word);\n sort($chars);\n $new_word = implode(\"\", $chars);\n array_push($new_words, $new_word);\n }\n return implode(\" \", $new_words);\n}\n\necho anti_shuffle(\"Hello World!!!\") . \"\\n\"; // Output: \"Hello !!!Wdlor\""], [">> get_row(array(array(1, 2, 3, 4, 5, 6), array(1, 2, 3, 4, 1, 6), array(1, 2, 3, 4, 5, 1)), 1)\n// array(array(0, 0), array(1, 4), array(1, 0), array(2, 5), array(2, 0))\n// >>> get_row(array(), 1)\n// array()\n// >>> get_row(array(array(), array(1), array(1, 2, 3)), 3)\n// array(array(2, 2))\nfunction get_row($lst, $x) {\n $coordinates = array();\n foreach ($lst as $row_index => $row) {\n foreach ($row as $col_index => $value) {\n if ($value == $x) {\n $coordinates[] = array($row_index, $col_index);\n }\n }\n }\n usort($coordinates, function($a, $b) {\n if ($a[0] == $b[0]) {\n return $b[1] - $a[1];\n }\n return $a[0] - $b[0];\n });\n return $coordinates;\n}"], [">> sort_array(array())\n// array()\n// >>> sort_array(array(5))\n// array(5)\n// >>> sort_array(array(2, 4, 3, 0, 1, 5))\n// array(0, 1, 2, 3, 4, 5)\n// >>> sort_array(array(2, 4, 3, 0, 1, 5, 6))\n// array(6, 5, 4, 3, 2, 1, 0)\nfunction sort_array($array) {\n $sum = $array[0] + $array[count($array) - 1];\n $sorted_array = $array;\n if ($sum % 2 == 0) {\n rsort($sorted_array);\n } else {\n sort($sorted_array);\n }\n return $sorted_array;\n}"], [">> encrypt(\"hi\")\n// \"lm\"\n// >>> encrypt(\"asdfghjkl\")\n// \"ewhjklnop\"\n// >>> encrypt(\"gf\")\n// \"kj\"\n// >>> encrypt(\"et\")\n// \"ix\"\nfunction encrypt($s) {\n $alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n $rotated_alphabet = substr($alphabet, 2) . substr($alphabet, 0, 2);\n $encrypted_string = \"\";\n for ($i = 0; $i < strlen($s); $i++) {\n $index = strpos($alphabet, $s[$i]);\n $encrypted_string .= $rotated_alphabet[$index];\n }\n return $encrypted_string;\n}\n"], [">> sum_product(array())\n// array(0, 1)\n// >>> sum_product(array(1, 2, 3, 4))\n// array(10, 24)\nfunction sum_product($numbers) {\n $sum = 0;\n $product = 1;\n foreach ($numbers as $number) {\n $sum += $number;\n $product *= $number;\n }\n return array($sum, $product);\n}"], [">> next_smallest(array(1, 2, 3, 4, 5))\n// 2\n// >>> next_smallest(array(5, 1, 4, 3, 2))\n// 2\n// >>> next_smallest(array())\n// null\n// >>> next_smallest(array(1, 1))\n// null\nfunction next_smallest($lst) {\n // Sort the array in ascending order\n sort($lst);\n\n // Check if there are at least 2 elements in the array\n if (count($lst) < 2) {\n return null;\n }\n\n // Return the 2nd smallest element\n return $lst[1];\n}\n"], [">> is_bored(\"Hello world\")\n// 0\n// >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n// 1\nfunction is_bored($S) {\n $boredoms = 0;\n $sentences = explode('.', $S);\n foreach ($sentences as $sentence) {\n $sentence = trim($sentence);\n if (strpos($sentence, 'I') === 0) {\n $boredoms++;\n }\n }\n return $boredoms;\n}\n"], [">> any_int(5, 2, 7)\n// true\n// >>> any_int(3, 2, 2)\n// false\n// >>> any_int(3, -2, 1)\n// true\n// >>> any_int(3.6, -2.2, 2)\n// false\nfunction any_int($x, $y, $z) {\n // Check if all numbers are integers.\n if (!is_int($x) || !is_int($y) || !is_int($z)) {\n return false;\n }\n // Check if one of the numbers is equal to the sum of the other two.\n if ($x == $y + $z || $y == $x + $z || $z == $x + $y) {\n return true;\n }\n return false;\n}\n"], [">> encode(\"test\")\n// \"TGST\"\n// >>> encode(\"This is a message\")\n// \"tHKS KS C MGSSCGG\"\nfunction encode($message) {\n $vowels = array('a', 'e', 'i', 'o', 'u');\n $encoded_message = \"\";\n for ($i = 0; $i < strlen($message); $i++) {\n $char = strtolower($message[$i]);\n if (ctype_alpha($char)) {\n if (in_array($char, $vowels)) {\n $index = array_search($char, $vowels);\n $new_index = ($index + 2) % count($vowels);\n $encoded_char = $vowels[$new_index];\n } else {\n $encoded_char = $char;\n }\n if ($message[$i] === strtoupper($message[$i])) {\n $encoded_char = strtoupper($encoded_char);\n }\n } else {\n $encoded_char = $char;\n }\n $encoded_message .= $encoded_char;\n }\n return $encoded_message;\n}\n\necho encode(\"test\") . \"\\n\"; // Output: \"TGST\"\necho encode(\"This is a message\") . \"\\n\"; // Output: \"tHKS KS C MGSSCGG\""], [">> skjkasdkd(array(0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3))\n// 10\n// >>> skjkasdkd(array(1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1))\n// 25\n// >>> skjkasdkd(array(1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3))\n// 13\n// >>> skjkasdkd(array(0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6))\n// 11\n// >>> skjkasdkd(array(0, 81, 12, 3, 1, 21))\n// 3\n// >>> skjkasdkd(array(0, 8, 1, 2, 1, 7))\n// 7\nfunction skjkasdkd($lst) {\n $max_prime = 0;\n foreach ($lst as $num) {\n if (is_prime($num) && $num > $max_prime) {\n $max_prime = $num;\n }\n }\n return array_sum(str_split(strval($max_prime)));\n}\n"], [">> check_dict_case(array(\"a\" => \"apple\", \"b\" => \"banana\"))\n// true\n// >>> check_dict_case(array(\"a\" => \"apple\", \"A\" => \"banana\", \"B\" => \"banana\"))\n// false\n// >>> check_dict_case(array(\"a\" => \"apple\", 8 => \"banana\", \"a\" => \"apple\"))\n// false\n// >>> check_dict_case(array(\"Name\" => \"John\", \"Age\" => \"36\", \"City\" => \"Houston\"))\n// false\n// >>> check_dict_case(array(\"STATE\" => \"NC\", \"ZIP\" => \"12345\"))\n// true\nfunction check_dict_case($dict) {\n if (empty($dict)) {\n return false;\n }\n $lower_case = true;\n $upper_case = true;\n foreach ($dict as $key => $value) {\n if (!is_string($key)) {\n return false;\n }\n if (!ctype_lower($key)) {\n $lower_case = false;\n }\n if (!ctype_upper($key)) {\n $upper_case = false;\n }\n }\n return $lower_case || $upper_case;\n}"], [">> count_up_to(5)\n// array(2, 3)\n// >>> count_up_to(11)\n// array(2, 3, 5, 7)\n// >>> count_up_to(0)\n// array()\n// >>> count_up_to(20)\n// array(2, 3, 5, 7, 11, 13, 17, 19)\n// >>> count_up_to(1)\n// array()\n// >>> count_up_to(18)\n// array(2, 3, 5, 7, 11, 13, 17)\nfunction count_up_to($n) {\n $primes = array();\n for ($i = 2; $i < $n; $i++) {\n $is_prime = true;\n for ($j = 2; $j < $i; $j++) {\n if ($i % $j == 0) {\n $is_prime = false;\n break;\n }\n }\n if ($is_prime) {\n array_push($primes, $i);\n }\n }\n return $primes;\n}"], [">> multiply(148, 412)\n// 16\n// >>> multiply(19, 28)\n// 72\n// >>> multiply(2020, 1851)\n// 0\n// >>> multiply(14, -15)\n// 20\nfunction multiply($a, $b) {\n return ($a % 10) * ($b % 10);\n}\n"], [">> count_upper(\"aBCdEf\")\n// 1\n// >>> count_upper(\"abcdefg\")\n// 0\n// >>> count_upper(\"dBBE\")\n// 0\nfunction count_upper($s) {\n $count = 0;\n for ($i = 0; $i < strlen($s); $i += 2) {\n if (ctype_upper($s[$i]) && in_array(strtolower($s[$i]), ['a', 'e', 'i', 'o', 'u'])) {\n $count++;\n }\n }\n return $count;\n}\n\necho count_upper(\"aBCdEf\") . \"\\n\"; // Output: 1\necho count_upper(\"abcdefg\") . \"\\n\"; // Output: 0\necho count_upper(\"dBBE\") . \"\\n\"; // Output: 0"], [">> closest_integer(\"10\")\n// 10\n// >>> closest_integer(\"15.3\")\n// 15\n// Note:\n// Rounding away from zero means that if the given number is equidistant\n// from two integers, the one you should return is the one that is the\n// farthest from zero. For example closest_integer(\"14.5\") should\n// return 15 and closest_integer(\"-14.5\") should return -15.\nfunction closest_integer($value) {\n // Convert the value to a float\n $float_value = floatval($value);\n\n // Round the float value to the nearest integer\n $rounded_value = round($float_value);\n\n // If the rounded value is equidistant from two integers, round it away from zero\n if ($rounded_value - $float_value == 0.5) {\n if ($float_value > 0) {\n $rounded_value = ceil($float_value);\n } else {\n $rounded_value = floor($float_value);\n }\n }\n\n // Return the rounded value as an integer\n return intval($rounded_value);\n}\n"], [">> rolling_max(array(1, 2, 3, 2, 3, 4, 2))\n// array(1, 2, 3, 3, 3, 4, 4)\nfunction rolling_max($numbers) {\n $max_values = array();\n $max_so_far = PHP_INT_MIN;\n foreach ($numbers as $number) {\n $max_so_far = max($max_so_far, $number);\n array_push($max_values, $max_so_far);\n }\n return $max_values;\n}\n\n$numbers = array(1, 2, 3, 2, 3, 4, 2);\n$max_values = rolling_max($numbers);\nprint_r($max_values);"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-r_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-r_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..69a00606e9e18f0de3f0e096b2b66f7213bc773a --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-r_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["# Check if in given list of numbers, are any two numbers closer to each other than\n# given threshold.\n# >>> has_close_elements(c(1.0, 2.0, 3.0), 0.5)\n# FALSE\n# >>> has_close_elements(c(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3)\n# TRUE\nhas_close_elements <- function(numbers, threshold) {\n for (i in 1:(length(numbers)-1)) {\n for (j in (i+1):length(numbers)) {\n if (abs(numbers[i] - numbers[j]) <= threshold) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n}\n"], ["# Given a positive integer n, you have to make a pile of n levels of stones.\n# The first level has n stones.\n# The number of stones in the next level is:\n# - the next odd number if n is odd.\n# - the next even number if n is even.\n# Return the number of stones in each level in a list, where element at index\n# i represents the number of stones in the level (i+1).\n# Examples:\n# >>> make_a_pile(3)\n# c(3, 5, 7)\nmake_a_pile <- function(n) {\n stones <- numeric(n)\n stones[1] <- n\n for (i in 2:n) {\n if (n %% 2 == 0) {\n stones[i] <- n + i*2 - 1\n } else {\n stones[i] <- n + i*2\n }\n }\n return(stones)\n}\n"], ["# You will be given a string of words separated by commas or spaces. Your task is\n# to split the string into words and return a vector of the words.\n# For example:\n# >>> words_string('Hi, my name is John')\n# c('Hi', 'my', 'name', 'is', 'John')\n# >>> words_string('One, two, three, four, five, six')\n# c('One', 'two', 'three', 'four', 'five', 'six')\nwords_string <- function(s) {\n strsplit(s, \"[, ]+\")[[1]]\n}\n"], ["# This function takes two positive numbers x and y and returns the\n# biggest even integer number that is in the range [x, y] inclusive. If \n# there's no such number, then the function should return -1.\n# For example:\n# >>> choose_num(12, 15)\n# 14\n# >>> choose_num(13, 12)\n# -1\nchoose_num <- function(x, y) {\n if (x %% 2 != 0) {\n x <- x + 1\n }\n if (x > y) {\n return(-1)\n } else {\n return(x)\n }\n}\n"], ["# You are given two positive integers n and m, and your task is to compute the\n# average of the integers from n through m (including n and m). \n# Round the answer to the nearest integer and convert that to binary.\n# If n is greater than m, return -1.\n# Example:\n# >>> rounded_avg(1, 5)\n# '0b11'\n# >>> rounded_avg(7, 5)\n# -1\n# >>> rounded_avg(10, 20)\n# '0b1111'\n# >>> rounded_avg(20, 33)\n# '0b11010'\nrounded_avg <- function(n, m) {\n if (n > m) {\n return(-1)\n }\n avg <- round(mean(n:m))\n return(as.binary(avg))\n}\n"], ["# Given a list of positive integers x. return a sorted list of all \n# elements that hasn't any even digit.\n# Note: Returned list should be sorted in increasing order.\n# For example:\n# >>> unique_digits(c(15, 33, 1422, 1))\n# c(1, 15, 33)\n# >>> unique_digits(c(152, 323, 1422, 10))\n# c()\nunique_digits <- function(x) {\n # Convert each number to a string\n x_str <- as.character(x)\n \n # Check if each number has an even digit\n has_even_digit <- sapply(x_str, function(num) {\n any(as.integer(strsplit(num, \"\")[[1]]) %% 2 == 0)\n })\n \n # Return the sorted list of numbers without even digits\n sort(x[!has_even_digit])\n}\n"], ["# Given a vector of integers, sort the integers that are between 1 and 9 inclusive,\n# reverse the resulting vector, and then replace each digit by its corresponding name from\n# \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n# For example:\n# >>> by_length(c(2, 1, 1, 4, 5, 8, 2, 3))\n# c('Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One')\n# If the vector is empty, return an empty vector:\n# >>> by_length(c())\n# c()\n# If the vector has any strange number ignore it:\n# >>> by_length(c(1, -1, 55))\n# c('One')\nby_length <- function(arr) {\n # Filter out numbers between 1 and 9 inclusive\n arr <- arr[arr >= 1 & arr <= 9]\n \n # Sort the numbers in descending order\n arr <- sort(arr, decreasing = TRUE)\n \n # Replace each digit by its corresponding name\n names <- c(\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\")\n arr <- names[arr]\n \n return(arr)\n}\n"], ["# Implement the function f that takes n as a parameter,\n# and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n# or the sum of numbers from 1 to i otherwise.\n# i starts from 1.\n# the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n# Example:\n# >>> f(5)\n# c(1, 2, 6, 24, 15)\nf <- function(n) {\n result <- vector(mode=\"numeric\", length=n)\n for (i in 1:n) {\n if (i %% 2 == 0) {\n result[i] <- factorial(i)\n } else {\n result[i] <- sum(1:i)\n }\n }\n return(result)\n}\n"], ["# Given a positive integer n, return a list that has the number of even and odd\n# integer palindromes that fall within the range(1, n), inclusive.\n# Example 1:\n# >>> even_odd_palindrome(3)\n# c(1, 2)\n# Explanation:\n# Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n# Example 2:\n# >>> even_odd_palindrome(12)\n# c(4, 6)\n# Explanation:\n# Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n# Note:\n# 1. 1 <= n <= 10^3\n# 2. returned list has the number of even and odd integer palindromes respectively.\neven_odd_palindrome <- function(n) {\n is_palindrome <- function(x) {\n x_str <- as.character(x)\n x_str == rev(x_str)\n }\n palindromes <- 1:n\n palindromes <- palindromes[sapply(palindromes, is_palindrome)]\n even_palindromes <- palindromes[palindromes %% 2 == 0]\n odd_palindromes <- palindromes[palindromes %% 2 != 0]\n c(length(even_palindromes), length(odd_palindromes))\n}\n"], ["# Write a function count_nums which takes a vector of integers and returns\n# the number of elements which has a sum of digits > 0.\n# If a number is negative, then its first signed digit will be negative:\n# e.g. -123 has signed digits -1, 2, and 3.\n# >>> count_nums(c())\n# 0\n# >>> count_nums(c(-1, 11, -11))\n# 1\n# >>> count_nums(c(1, 1, 2))\n# 3\ncount_nums <- function(arr) {\n count <- 0\n for (i in arr) {\n if (i < 0) {\n i <- abs(i)\n }\n sum_digits <- sum(as.integer(strsplit(as.character(i), \"\")[[1]]))\n if (sum_digits > 0) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# We have a vector 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n# numbers in the vector will be randomly ordered. Your task is to determine if\n# it is possible to get a vector sorted in non-decreasing order by performing \n# the following operation on the given vector:\n# You are allowed to perform right shift operation any number of times.\n# One right shift operation means shifting all elements of the vector by one\n# position in the right direction. The last element of the vector will be moved to\n# the starting position in the vector i.e. 0th index. \n# If it is possible to obtain the sorted vector by performing the above operation\n# then return TRUE else return FALSE.\n# If the given vector is empty then return TRUE.\n# Note: The given list is guaranteed to have unique elements.\n# For Example:\n# >>> move_one_ball(c(3, 4, 5, 1, 2))\n# TRUE\n# Explanation: By performin 2 right shift operations, non-decreasing order can\n# be achieved for the given vector.\n# >>> move_one_ball(c(3, 5, 4, 1, 2))\n# FALSE\n# Explanation:It is not possible to get non-decreasing order for the given\n# vector by performing any number of right shift operations.\nmove_one_ball <- function(arr) {\n n <- length(arr)\n if (n == 0) {\n return(TRUE)\n }\n for (i in 1:(n-1)) {\n if (arr[i] > arr[i+1]) {\n if (arr[1] < arr[n]) {\n return(FALSE)\n }\n for (j in 2:n) {\n if (arr[j] < arr[j-1]) {\n return(FALSE)\n }\n }\n return(TRUE)\n }\n }\n return(TRUE)\n}\n"], ["# Find the shortest palindrome that begins with a supplied string.\n# Algorithm idea is simple:\n# - Find the longest postfix of supplied string that is a palindrome.\n# - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n# >>> make_palindrome('')\n# ''\n# >>> make_palindrome('cat')\n# 'catac'\n# >>> make_palindrome('cata')\n# 'catac'\nmake_palindrome <- function(string) {\n n <- nchar(string)\n for (i in 1:(n-1)) {\n if (identical(substr(string, 1, i), rev(substr(string, i+1, n)))) {\n return(paste0(string, rev(substr(string, 1, i))))\n }\n }\n return(paste0(string, rev(substr(string, 1, n-1))))\n}\n"], ["# In this problem, you will implement a function that takes two lists of numbers,\n# and determines whether it is possible to perform an exchange of elements\n# between them to make lst1 a list of only even numbers.\n# There is no limit on the number of exchanged elements between lst1 and lst2.\n# If it is possible to exchange elements between the lst1 and lst2 to make\n# all the elements of lst1 to be even, return \"YES\".\n# Otherwise, return \"NO\".\n# For example:\n# >>> exchange(c(1, 2, 3, 4), c(1, 2, 3, 4))\n# 'YES'\n# >>> exchange(c(1, 2, 3, 4), c(1, 5, 3, 4))\n# 'NO'\n# It is assumed that the input lists will be non-empty.\nexchange <- function(lst1, lst2) {\n # Check if all elements in lst1 are even\n if (all(lst1 %% 2 == 0)) {\n return(\"YES\")\n }\n \n # Check if there are any even elements in lst2\n if (any(lst2 %% 2 == 0)) {\n return(\"YES\")\n }\n \n # If there are no even elements in lst2, return \"NO\"\n return(\"NO\")\n}\n"], ["# Given a string representing a space separated lowercase letters, return a named list\n# of the letter with the most repetition and containing the corresponding count.\n# If several letters have the same occurrence, return all of them.\n# Example:\n# >>> histogram('a b c')\n# list('a' = 1, 'b' = 1, 'c' = 1)\n# >>> histogram('a b b a')\n# list('a' = 2, 'b' = 2)\n# >>> histogram('a b c a b')\n# list('a' = 2, 'b' = 2)\n# >>> histogram('b b b b a')\n# list('b' = 4)\n# >>> histogram('')\n# list()\nhistogram <- function(test) {\n # Split the string into a vector of individual letters\n letters <- strsplit(test, \" \")[[1]]\n \n # Count the occurrences of each letter\n counts <- table(letters)\n \n # Find the maximum count\n max_count <- max(counts)\n \n # Find all letters with the maximum count\n max_letters <- names(counts)[counts == max_count]\n \n # Return a named list of the letters with the maximum count\n return(setNames(as.list(counts[max_letters]), max_letters))\n}\n"], ["# Task\n# We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n# then check if the result string is palindrome.\n# A string is called palindrome if it reads the same backward as forward.\n# You should return a list containing the result string and TRUE/FALSE for the check.\n# Example\n# >>> reverse_delete('abcde', 'ae')\n# list('bcd', FALSE)\n# >>> reverse_delete('abcdef', 'b')\n# list('acdef', FALSE)\n# >>> reverse_delete('abcdedcba', 'ab')\n# list('cdedc', TRUE)\nreverse_delete <- function(s, c) {\n # Delete all characters in s that are equal to any character in c\n s_new <- gsub(paste0(\"[\", c, \"]\"), \"\", s)\n \n # Check if the result string is palindrome\n is_palindrome <- s_new == rev(s_new)\n \n # Return a list containing the result string and TRUE/FALSE for the check\n return(list(s_new, is_palindrome))\n}\n"], ["# Given a list of strings, where each string consists of only digits, return a list.\n# Each element i of the output should be \"the number of odd elements in the\n# string i of the input.\" where all the i's should be replaced by the number\n# of odd digits in the i'th string of the input.\n# >>> odd_count(c('1234567'))\n# c('the number of odd elements 4n the str4ng 4 of the 4nput.')\n# >>> odd_count(c('3', '11111111'))\n# c('the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.')\nodd_count <- function(lst) {\n lapply(lst, function(x) {\n num_odd <- sum(as.integer(strsplit(x, \"\")[[1]]) %% 2)\n paste0(\"the number of odd elements \", num_odd, \"n the str\", num_odd, \"ng \", num_odd, \" of the \", num_odd, \"nput.\")\n })\n}\n"], ["# Given a vector of integers nums, find the minimum sum of any non-empty sub-vector\n# of nums.\n# Example\n# >>> minSubArraySum(c(2, 3, 4, 1, 2, 4))\n# 1\n# >>> minSubArraySum(c(-1, -2, -3))\n# -6\nminSubArraySum <- function(nums) {\n min_sum <- Inf\n curr_sum <- 0\n for (num in nums) {\n curr_sum <- min(num, curr_sum + num)\n min_sum <- min(min_sum, curr_sum)\n }\n return(min_sum)\n}\n"], ["# You are given a rectangular grid of wells. Each row represents a single well,\n# and each 1 in a row represents a single unit of water.\n# Each well has a corresponding bucket that can be used to extract water from it, \n# and all buckets have the same capacity.\n# Your task is to use the buckets to empty the wells.\n# Output the number of times you need to lower the buckets.\n# Example 1:\n# >>> max_fill(list(c(0, 0, 1, 0), c(0, 1, 0, 0), c(1, 1, 1, 1)), 1)\n# 6\n# Example 2:\n# >>> max_fill(list(c(0, 0, 1, 1), c(0, 0, 0, 0), c(1, 1, 1, 1), c(0, 1, 1, 1)), 2)\n# 5\n# Example 3:\n# >>> max_fill(list(c(0, 0, 0), c(0, 0, 0)), 5)\n# 0\n# Constraints:\n# * all wells have the same length\n# * 1 <= grid.length <= 10^2\n# * 1 <= grid[:,1].length <= 10^2\n# * grid[i][j] -> 0 | 1\n# * 1 <= capacity <= 10\nmax_fill <- function(grid, capacity) {\n # Initialize variables\n num_wells <- nrow(grid)\n num_units <- ncol(grid)\n num_buckets <- ceiling(sum(grid) / capacity)\n num_lowers <- 0\n \n # Loop through each well\n for (i in 1:num_wells) {\n # Loop through each unit in the well\n for (j in 1:num_units) {\n # If the unit has water, lower the bucket\n if (grid[i, j] == 1) {\n num_lowers <- num_lowers + 1\n }\n }\n }\n \n # Return the number of times buckets need to be lowered\n return(num_lowers)\n}\n"], ["# In this Kata, you have to sort a vector of non-negative integers according to\n# number of ones in their binary representation in ascending order.\n# For similar number of ones, sort based on decimal value.\n# It must be implemented like this:\n# >>> sort_array(c(1, 5, 2, 3, 4))\n# c(1, 2, 3, 4, 5)\n# >>> sort_array(c(-2, -3, -4, -5, -6))\n# c(-6, -5, -4, -3, -2)\n# >>> sort_array(c(1, 0, 2, 3, 4))\n# c(0, 1, 2, 3, 4)\nsort_array <- function(arr) {\n # Convert each number to binary and count the number of ones\n ones_count <- sapply(arr, function(x) sum(as.integer(intToBits(x))))\n \n # Sort the array based on the number of ones and decimal value\n arr[order(ones_count, arr)]\n}\n"], ["# Given a string s and a natural number n, you have been tasked to implement \n# a function that returns a list of all words from string s that contain exactly \n# n consonants, in order these words appear in the string s.\n# If the string s is empty then the function should return an empty list.\n# Note: you may assume the input string contains only letters and spaces.\n# Examples:\n# >>> select_words('Mary had a little lamb', 4)\n# c('little')\n# >>> select_words('Mary had a little lamb', 3)\n# c('Mary', 'lamb')\n# >>> select_words('simple white space', 2)\n# c()\n# >>> select_words('Hello world', 4)\n# c('world')\n# >>> select_words('Uncle sam', 3)\n# c('Uncle')\nselect_words <- function(s, n) {\n # Define a helper function to count the number of consonants in a word\n count_consonants <- function(word) {\n consonants <- c('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z')\n sum(sapply(strsplit(tolower(word), '')[[1]], function(x) x %in% consonants))\n }\n \n # Split the input string into a list of words\n words <- strsplit(s, ' ')[[1]]\n \n # Filter the list of words to only include those with n consonants\n selected_words <- words[sapply(words, count_consonants) == n]\n \n # Return the list of selected words\n selected_words\n}\n"], ["# You are given a word. Your task is to find the closest vowel that stands between \n# two consonants from the right side of the word (case sensitive).\n# Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n# find any vowel met the above condition. \n# You may assume that the given string contains English letter only.\n# Example:\n# >>> get_closest_vowel('yogurt')\n# 'u'\n# >>> get_closest_vowel('FULL')\n# 'U'\n# >>> get_closest_vowel('quick')\n# ''\n# >>> get_closest_vowel('ab')\n# ''\nget_closest_vowel <- function(word) {\n vowels <- c('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')\n consonants <- c('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z')\n for (i in (nchar(word) - 1):2) {\n if (substr(word, i, i) %in% consonants & substr(word, i - 1, i - 1) %in% vowels & substr(word, i + 1, i + 1) %in% consonants) {\n return(substr(word, i - 1, i - 1))\n }\n }\n return('')\n}\n"], ["# You are given a list of two strings, both strings consist of open\n# parentheses '(' or close parentheses ')' only.\n# Your job is to check if it is possible to concatenate the two strings in\n# some order, that the resulting string will be good.\n# A string S is considered to be good if and only if all parentheses in S\n# are balanced. For example: the string '(())()' is good, while the string\n# '())' is not.\n# Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n# Examples:\n# >>> match_parens(c('()(', ')'))\n# 'Yes'\n# >>> match_parens(c(')', ')'))\n# 'No'\nmatch_parens <- function(lst) {\n s <- paste(lst, collapse=\"\")\n stack <- c()\n for (i in 1:nchar(s)) {\n if (substr(s, i, i) == \"(\") {\n stack <- c(stack, \"(\")\n } else {\n if (length(stack) == 0) {\n return(\"No\")\n }\n stack <- stack[-length(stack)]\n }\n }\n if (length(stack) == 0) {\n return(\"Yes\")\n } else {\n return(\"No\")\n }\n}\n"], ["# Input are two strings a and b consisting only of 1s and 0s.\n# Perform binary XOR on these inputs and return result also as a string.\n# >>> string_xor('010', '110')\n# '100'\nstring_xor <- function(a, b) {\n xor_result <- as.integer(a) ^ as.integer(b)\n return(paste(xor_result, collapse = \"\"))\n}\n"], ["# Given a vector arr of integers and a positive integer k, return a sorted list \n# of length k with the maximum k numbers in arr.\n# Example 1:\n# >>> maximum(c(-3, -4, 5), 3)\n# c(-4, -3, 5)\n# Example 2:\n# >>> maximum(c(4, -4, 4), 2)\n# c(4, 4)\n# Example 3:\n# >>> maximum(c(-3, 2, 1, 2, -1, -2, 1), 1)\n# c(2)\n# Note:\n# 1. The length of the vector will be in the range of [1, 1000].\n# 2. The elements in the vector will be in the range of [-1000, 1000].\n# 3. 0 <= k <= len(arr)\nmaximum <- function(arr, k) {\n sort(arr, decreasing = TRUE)[1:k]\n}\n"], ["# Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n# Examples\n# >>> solution(c(5, 8, 7, 1))\n# 12\n# >>> solution(c(3, 3, 3, 3, 3))\n# 9\n# >>> solution(c(30, 13, 24, 321))\n# 0\nsolution <- function(lst) {\n sum(lst[seq(2, length(lst), by=2)] %% 2)\n}\n"], ["# Given a non-empty vector of integers arr and an integer k, return\n# the sum of the elements with at most two digits from the first k elements of arr.\n# Example:\n# >>> add_elements(c(111, 21, 3, 4000, 5, 6, 7, 8, 9), 4)\n# 24\n# Constraints:\n# 1. 1 <= len(arr) <= 100\n# 2. 1 <= k <= len(arr)\nadd_elements <- function(arr, k) {\n sum(sapply(arr[1:k], function(x) if (x < 100) x else 0))\n}\n"], ["# Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n# The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n# as follows: start with any positive integer n. Then each term is obtained from the \n# previous term as follows: if the previous term is even, the next term is one half of \n# the previous term. If the previous term is odd, the next term is 3 times the previous\n# term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n# Note: \n# 1. Collatz(1) is [1].\n# 2. returned list sorted in increasing order.\n# For example:\n# get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n# >>> get_odd_collatz(5)\n# c(1, 5)\nget_odd_collatz <- function(n) {\n collatz <- c(n)\n while (n != 1) {\n if (n %% 2 == 0) {\n n <- n / 2\n } else {\n n <- 3 * n + 1\n }\n collatz <- c(collatz, n)\n }\n return(sort(unique(collatz[collatz %% 2 != 0])))\n}\n"], ["# You have to write a function which validates a given date string and\n# returns TRUE if the date is valid otherwise FALSE.\n# The date is valid if all of the following rules are satisfied:\n# 1. The date string is not empty.\n# 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n# 3. The months should not be less than 1 or higher than 12.\n# 4. The date should be in the format: mm-dd-yyyy\n# >>> valid_date('03-11-2000')\n# TRUE\n# >>> valid_date('15-01-2012')\n# FALSE\n# >>> valid_date('04-0-2040')\n# FALSE\n# >>> valid_date('06-04-2020')\n# TRUE\n# >>> valid_date('06/04/2020')\n# FALSE\nvalid_date <- function(date) {\n # Check if the date string is not empty\n if (date == \"\") {\n return(FALSE)\n }\n \n # Split the date string into month, day, and year\n date_parts <- strsplit(date, \"-\")[[1]]\n month <- as.integer(date_parts[1])\n day <- as.integer(date_parts[2])\n year <- as.integer(date_parts[3])\n \n # Check if the number of days is valid for the given month\n if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)) {\n return(FALSE)\n } else if ((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)) {\n return(FALSE)\n } else if (month == 2 && (day < 1 || day > 29)) {\n return(FALSE)\n }\n \n # Check if the month is valid\n if (month < 1 || month > 12) {\n return(FALSE)\n }\n \n # Check if the date is in the format mm-dd-yyyy\n if (length(date_parts) != 3 || date_parts[1] != sprintf(\"%02d\", month) || date_parts[2] != sprintf(\"%02d\", day) || date_parts[3] != sprintf(\"%04d\", year)) {\n return(FALSE)\n }\n \n # If all checks pass, return TRUE\n return(TRUE)\n}\n"], ["# Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n# should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n# alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n# Examples\n# >>> split_words('Hello world!')\n# c('Hello', 'world!')\n# >>> split_words('Hello,world!')\n# c('Hello', 'world!')\n# >>> split_words('abcdef')\n# 3\nsplit_words <- function(txt) {\n if (grepl(' ', txt)) {\n return(strsplit(txt, ' ')[[1]])\n } else if (grepl(',', txt)) {\n return(strsplit(txt, ',')[[1]])\n } else {\n return(sum(sapply(strsplit(txt, '')[[1]], function(x) {\n if (x %in% letters[seq(1, 26, 2)]) {\n return(1)\n } else {\n return(0)\n }\n })))\n }\n}\n"], ["# Given a list of numbers, return whether or not they are sorted\n# in ascending order. If list has more than 1 duplicate of the same\n# number, return FALSE. Assume no negative numbers and only integers.\n# Examples\n# >>> is_sorted(c(5))\n# TRUE\n# >>> is_sorted(c(1, 2, 3, 4, 5))\n# TRUE\n# >>> is_sorted(c(1, 3, 2, 4, 5))\n# FALSE\n# >>> is_sorted(c(1, 2, 3, 4, 5, 6))\n# TRUE\n# >>> is_sorted(c(1, 2, 3, 4, 5, 6, 7))\n# TRUE\n# >>> is_sorted(c(1, 3, 2, 4, 5, 6, 7))\n# FALSE\n# >>> is_sorted(c(1, 2, 2, 3, 3, 4))\n# TRUE\n# >>> is_sorted(c(1, 2, 2, 2, 3, 4))\n# FALSE\nis_sorted <- function(lst) {\n # Check if list has more than 1 duplicate of the same number\n if (length(unique(lst)) != length(lst)) {\n return(FALSE)\n }\n # Check if list is sorted in ascending order\n for (i in 1:(length(lst)-1)) {\n if (lst[i] > lst[i+1]) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# You are given two intervals,\n# where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n# The given intervals are closed which means that the interval (start, end)\n# includes both start and end.\n# For each given interval, it is assumed that its start is less or equal its end.\n# Your task is to determine whether the length of intersection of these two \n# intervals is a prime number.\n# Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n# which its length is 1, which not a prime number.\n# If the length of the intersection is a prime number, return \"YES\",\n# otherwise, return \"NO\".\n# If the two intervals don't intersect, return \"NO\".\n# [input/output] samples:\n# >>> intersection(c(1, 2), c(2, 3))\n# 'NO'\n# >>> intersection(c(-1, 1), c(0, 4))\n# 'NO'\n# >>> intersection(c(-3, -1), c(-5, 5))\n# 'YES'\nintersection <- function(interval1, interval2) {\n start1 <- interval1[1]\n end1 <- interval1[2]\n start2 <- interval2[1]\n end2 <- interval2[2]\n \n if (end1 < start2 || end2 < start1) {\n return(\"NO\")\n }\n \n start <- max(start1, start2)\n end <- min(end1, end2)\n \n length <- end - start + 1\n \n if (length == 1) {\n return(\"NO\")\n }\n \n for (i in 2:(length-1)) {\n if (length %% i == 0) {\n return(\"NO\")\n }\n }\n \n return(\"YES\")\n}\n"], ["# You are given a vector arr of integers and you need to return\n# sum of magnitudes of integers multiplied by product of all signs\n# of each number in the vector, represented by 1, -1 or 0.\n# Note: return NULL for empty arr.\n# Example:\n# >>> prod_signs(c(1, 2, 2, -4))\n# 9\n# >>> prod_signs(c(0, 1))\n# 0\n# >>> prod_signs(c())\n# NULL\nprod_signs <- function(arr) {\n if (length(arr) == 0) {\n return(NULL)\n }\n prod_sign <- prod(sign(arr))\n sum_magnitudes <- sum(abs(arr))\n return(prod_sign * sum_magnitudes)\n}\n"], ["# Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n# each cell of the grid contains a value. Every integer in the range [1, N * N]\n# inclusive appears exactly once on the cells of the grid.\n# You have to find the minimum path of length k in the grid. You can start\n# from any cell, and in each step you can move to any of the neighbor cells,\n# in other words, you can go to cells which share an edge with you current\n# cell.\n# Please note that a path of length k means visiting exactly k cells (not\n# necessarily distinct).\n# You CANNOT go off the grid.\n# A path A (of length k) is considered less than a path B (of length k) if\n# after making the ordered lists of the values on the cells that A and B go\n# through (let's call them lst_A and lst_B), lst_A is lexicographically less\n# than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n# such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n# lst_A[j] = lst_B[j].\n# It is guaranteed that the answer is unique.\n# Return an ordered list of the values on the cells that the minimum path go through.\n# Examples: \n# >>> minPath(list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9)), 3)\n# c(1, 2, 1)\n# >>> minPath(list(c(5, 9, 3), c(4, 1, 6), c(7, 8, 2)), 1)\n# c(1)\nminPath <- function(grid, k) {\n n <- nrow(grid)\n m <- ncol(grid)\n dp <- array(Inf, c(n, m, k + 1))\n dp[, , 1] <- grid\n for (l in 2:k) {\n for (i in 1:n) {\n for (j in 1:m) {\n dp[i, j, l] <- min(dp[i, j, l], dp[i, j, l - 1])\n if (i > 1) {\n dp[i, j, l] <- min(dp[i, j, l], dp[i - 1, j, l - 1])\n }\n if (i < n) {\n dp[i, j, l] <- min(dp[i, j, l], dp[i + 1, j, l - 1])\n }\n if (j > 1) {\n dp[i, j, l] <- min(dp[i, j, l], dp[i, j - 1, l - 1])\n }\n if (j < m) {\n dp[i, j, l] <- min(dp[i, j, l], dp[i, j + 1, l - 1])\n }\n }\n }\n }\n path <- numeric(k)\n i <- which.min(dp[, , k])\n j <- (i - 1) %% m + 1\n i <- ((i - 1) %/% m) + 1\n path[k] <- grid[i, j]\n for (l in (k - 1):1) {\n if (i > 1 && dp[i - 1, j, l] == dp[i, j, l + 1] - grid[i, j]) {\n i <- i - 1\n } else if (i < n && dp[i + 1, j, l] == dp[i, j, l + 1] - grid[i, j]) {\n i <- i + 1\n } else if (j > 1 && dp[i, j - 1, l] == dp[i, j, l + 1] - grid[i, j]) {\n j <- j - 1\n } else if (j < m && dp[i, j + 1, l] == dp[i, j, l + 1] - grid[i, j]) {\n j <- j + 1\n }\n path[l] <- grid[i, j]\n }\n path\n}\n"], ["# Out of list of strings, return the longest one. Return the first one in case of multiple\n# strings of the same length. Return NULL in case the input list is empty.\n# >>> longest(c())\n# NULL\n# >>> longest(c('a', 'b', 'c'))\n# 'a'\n# >>> longest(c('a', 'bb', 'ccc'))\n# 'ccc'\nlongest <- function(strings) {\n if (length(strings) == 0) {\n return(NULL)\n } else {\n max_length <- max(nchar(strings))\n longest_string <- strings[nchar(strings) == max_length][1]\n return(longest_string)\n }\n}\n"], ["# Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n# the last couple centuries. However, what people don't know is Tribonacci sequence.\n# Tribonacci sequence is defined by the recurrence:\n# tri(1) = 3\n# tri(n) = 1 + n / 2, if n is even.\n# tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n# For example:\n# tri(2) = 1 + (2 / 2) = 2\n# tri(4) = 3\n# tri(3) = tri(2) + tri(1) + tri(4)\n# = 2 + 3 + 3 = 8 \n# You are given a non-negative integer number n, you have to a return a list of the \n# first n + 1 numbers of the Tribonacci sequence.\n# Examples:\n# >>> tri(3)\n# c(1, 3, 2, 8)\ntri <- function(n) {\n if (n == 0) {\n return(numeric(0))\n } else if (n == 1) {\n return(3)\n } else {\n seq <- numeric(n + 1)\n seq[1] <- 1\n seq[2] <- 3\n for (i in 3:n) {\n if (i %% 2 == 0) {\n seq[i] <- 1 + i / 2\n } else {\n seq[i] <- seq[i - 1] + seq[i - 2] + seq[i + 1]\n }\n }\n return(seq)\n }\n}\n"], ["# Given a positive integer n, return the product of the odd digits.\n# Return 0 if all digits are even.\n# For example:\n# >>> digits(1)\n# 1\n# >>> digits(4)\n# 0\n# >>> digits(235)\n# 15\ndigits <- function(n) {\n # Convert the number to a string\n n_str <- as.character(n)\n \n # Initialize the product to 1\n product <- 1\n \n # Loop through each digit in the string\n for (i in 1:nchar(n_str)) {\n # Get the current digit\n digit <- as.numeric(substr(n_str, i, i))\n \n # If the digit is odd, multiply it into the product\n if (digit %% 2 != 0) {\n product <- product * digit\n }\n }\n \n # If the product is still 1, that means all digits were even\n if (product == 1) {\n return(0)\n } else {\n return(product)\n }\n}\n"], ["# Create a function that takes a string as input which contains only square brackets.\n# The function should return TRUE if and only if there is a valid subsequence of brackets \n# where at least one bracket in the subsequence is nested.\n# >>> is_nested('[[]]')\n# TRUE\n# >>> is_nested('[]]]]]]][[[[[]')\n# FALSE\n# >>> is_nested('[][]')\n# FALSE\n# >>> is_nested('[]')\n# FALSE\n# >>> is_nested('[[][]]')\n# TRUE\n# >>> is_nested('[[]][[')\n# TRUE\nis_nested <- function(string) {\n # Initialize a stack to keep track of the brackets\n stack <- c()\n \n # Iterate through each character in the string\n for (char in string) {\n # If the character is an opening bracket, push it onto the stack\n if (char == '[') {\n stack <- c(stack, char)\n }\n # If the character is a closing bracket, check if there is an opening bracket on the stack\n else if (char == ']') {\n # If there is an opening bracket on the stack, pop it off and continue\n if (length(stack) > 0 && stack[length(stack)] == '[') {\n stack <- stack[-length(stack)]\n }\n # If there is not an opening bracket on the stack, return FALSE\n else {\n return(FALSE)\n }\n }\n }\n \n # If there are any opening brackets left on the stack, return TRUE\n if (length(stack) > 0) {\n return(TRUE)\n }\n # If there are no opening brackets left on the stack, return FALSE\n else {\n return(FALSE)\n }\n}\n"], ["# You are given a list of numbers.\n# You need to return the sum of squared numbers in the given list,\n# round each element in the list to the upper int(Ceiling) first.\n# Examples:\n# >>> lst(c(1.0, 2.0, 3.0))\n# 14\n# >>> lst(c(1.0, 4.0, 9.0))\n# 98\n# >>> lst(c(1.0, 3.0, 5.0, 7.0))\n# 84\n# >>> lst(c(1.4, 4.2, 0.0))\n# 29\n# >>> lst(c(-2.4, 1.0, 1.0))\n# 6\nsum_squares <- function(lst) {\n # Round each element in the list to the upper int(Ceiling)\n lst <- ceiling(lst)\n # Calculate the sum of squared numbers in the list\n sum(lst^2)\n}\n"], ["# Create a function that returns TRUE if the last character\n# of a given string is an alphabetical character and is not\n# a part of a word, and FALSE otherwise.\n# Note: \"word\" is a group of characters separated by space.\n# Examples:\n# >>> check_if_last_char_is_a_letter('apple pie')\n# FALSE\n# >>> check_if_last_char_is_a_letter('apple pi e')\n# TRUE\n# >>> check_if_last_char_is_a_letter('apple pi e ')\n# FALSE\n# >>> check_if_last_char_is_a_letter('')\n# FALSE\ncheck_if_last_char_is_a_letter <- function(txt) {\n # Split the text into words\n words <- strsplit(txt, \" \")[[1]]\n # Check if the last character of the last word is an alphabetical character\n last_char <- substr(words[length(words)], nchar(words[length(words)])-1, nchar(words[length(words)]))\n return(grepl(\"[a-zA-Z]\", last_char) && !grepl(\"[a-zA-Z]\", substr(words[length(words)], 1, nchar(words[length(words)])-2)))\n}\n"], ["# Create a function which returns the largest index of an element which\n# is not greater than or equal to the element immediately preceding it. If\n# no such element exists then return -1. The given vector will not contain\n# duplicate values.\n# Examples:\n# >>> can_arrange(c(1, 2, 4, 3, 5))\n# 3\n# >>> can_arrange(c(1, 2, 3))\n# -1\ncan_arrange <- function(arr) {\n for (i in 2:length(arr)) {\n if (arr[i] <= arr[i-1]) {\n return(i-1)\n }\n }\n return(-1)\n}\n"], ["# Create a function that returns a list (a, b), where 'a' is\n# the largest of negative integers, and 'b' is the smallest\n# of positive integers in a list.\n# If there is no negative or positive integers, return them as NULL.\n# Examples:\n# >>> largest_smallest_integers(c(2, 4, 1, 3, 5, 7))\n# list(NULL, 1)\n# >>> largest_smallest_integers(c())\n# list(NULL, NULL)\n# >>> largest_smallest_integers(c(0))\n# list(NULL, NULL)\nlargest_smallest_integers <- function(lst) {\n neg_ints <- lst[lst < 0]\n pos_ints <- lst[lst > 0]\n if (length(neg_ints) == 0 && length(pos_ints) == 0) {\n return(list(NULL, NULL))\n } else if (length(neg_ints) == 0) {\n return(list(NULL, min(pos_ints)))\n } else if (length(pos_ints) == 0) {\n return(list(max(neg_ints), NULL))\n } else {\n return(list(max(neg_ints), min(pos_ints)))\n }\n}\n"], ["# Create a function that takes integers, floats, or strings representing\n# real numbers, and returns the larger variable in its given variable type.\n# Return NULL if the values are equal.\n# Note: If a real number is represented as a string, the floating point might be . or ,\n# >>> compare_one(1, 2.5)\n# 2.5\n# >>> compare_one(1, '2,3')\n# '2,3'\n# >>> compare_one('5,1', '6')\n# '6'\n# >>> compare_one('1', 1)\n# NULL\ncompare_one <- function(a, b) {\n if (class(a) == \"character\") {\n a <- as.numeric(gsub(\",\", \".\", a))\n }\n if (class(b) == \"character\") {\n b <- as.numeric(gsub(\",\", \".\", b))\n }\n if (a > b) {\n return(a)\n } else if (b > a) {\n return(b)\n } else {\n return(NULL)\n }\n}\n"], ["# Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n# Example\n# >>> is_equal_to_sum_even(4)\n# FALSE\n# >>> is_equal_to_sum_even(6)\n# FALSE\n# >>> is_equal_to_sum_even(8)\n# TRUE\nis_equal_to_sum_even <- function(n) {\n if (n %% 2 != 0) {\n return(FALSE)\n } else {\n return(n %/% 4 == 2)\n }\n}\n"], ["# The Brazilian factorial is defined as:\n# brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n# where n > 0\n# For example:\n# >>> special_factorial(4)\n# 288\n# The function will receive an integer as input and should return the special\n# factorial of this integer.\nspecial_factorial <- function(n) {\n if (n <= 0) {\n return(1)\n } else {\n result <- 1\n for (i in 1:n) {\n result <- result * factorial(i)\n }\n return(result)\n }\n}\n"], ["# Return a greatest common divisor of two integers a and b\n# >>> greatest_common_divisor(3, 5)\n# 1\n# >>> greatest_common_divisor(25, 15)\n# 5\ngreatest_common_divisor <- function(a, b) {\n if (b == 0) {\n return(a)\n } else {\n return(greatest_common_divisor(b, a %% b))\n }\n}\n"], ["# Given a string text, replace all spaces in it with underscores, \n# and if a string has more than 2 consecutive spaces, \n# then replace all consecutive spaces with - \n# >>> fix_spaces(' Example')\n# 'Example'\n# >>> fix_spaces(' Example 1')\n# 'Example_1'\n# >>> fix_spaces(' Example 2')\n# '_Example_2'\n# >>> fix_spaces(' Example 3')\n# '_Example-3'\nfix_spaces <- function(text) {\n # Replace all spaces with underscores\n text <- gsub(\" \", \"_\", text)\n \n # Replace all consecutive spaces with -\n text <- gsub(\"_{2,}\", \"-\", text)\n \n return(text)\n}\n"], ["# Create a function which takes a string representing a file's name, and returns\n# 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n# A file's name is considered to be valid if and only if all the following conditions \n# are met:\n# - There should not be more than three digits ('0'-'9') in the file's name.\n# - The file's name contains exactly one dot '.'\n# - The substring before the dot should not be empty, and it starts with a letter from \n# the latin alphapet ('a'-'z' and 'A'-'Z').\n# - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n# Examples:\n# >>> file_name_check('example.txt')\n# 'Yes'\n# >>> file_name_check('1example.dll')\n# 'No'\nfile_name_check <- function(file_name) {\n # Check if the file's name contains exactly one dot '.'\n if (length(grep('\\\\.', file_name)) != 1) {\n return('No')\n }\n \n # Split the file's name into two parts: before the dot and after the dot\n parts <- strsplit(file_name, '\\\\.')[[1]]\n before_dot <- parts[1]\n after_dot <- parts[2]\n \n # Check if the substring before the dot is not empty and starts with a letter\n if (nchar(before_dot) == 0 || !grepl('^[a-zA-Z]', before_dot)) {\n return('No')\n }\n \n # Check if the substring after the dot is one of ['txt', 'exe', 'dll']\n if (!after_dot %in% c('txt', 'exe', 'dll')) {\n return('No')\n }\n \n # Check if there are more than three digits in the file's name\n if (length(grep('[0-9]{4,}', file_name)) > 0) {\n return('No')\n }\n \n # If all conditions are met, return 'Yes'\n return('Yes')\n}\n"], ["# \"\n# This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n# multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n# change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n# Examples:\n# >>> lst\n# c(1, 2, 3)\n# >>> lst\n# c()\n# >>> lst\n# c(-1, -5, 2, -1, -5)\nsum_squares <- function(lst) {\n for (i in 1:length(lst)) {\n if (i %% 3 == 0) {\n lst[i] <- lst[i]^2\n } else if (i %% 4 == 0) {\n lst[i] <- lst[i]^3\n }\n }\n return(sum(lst))\n}\n"], ["# You are given a string representing a sentence,\n# the sentence contains some words separated by a space,\n# and you have to return a string that contains the words from the original sentence,\n# whose lengths are prime numbers,\n# the order of the words in the new string should be the same as the original one.\n# Example 1:\n# >>> words_in_sentence('This is a test')\n# 'is'\n# Example 2:\n# >>> words_in_sentence('lets go for swimming')\n# 'go for'\n# Constraints:\n# * 1 <= len(sentence) <= 100\n# * sentence contains only letters\nwords_in_sentence <- function(sentence) {\n words <- strsplit(sentence, \" \")[[1]]\n prime_words <- words[sapply(nchar(words), is_prime)]\n return(paste(prime_words, collapse = \" \"))\n}\n\nis_prime <- function(n) {\n if (n <= 1) {\n return(FALSE)\n }\n for (i in 2:sqrt(n)) {\n if (n %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# Your task is to implement a function that will simplify the expression\n# x * n. The function returns TRUE if x * n evaluates to a whole number and FALSE\n# otherwise. Both x and n, are string representation of a fraction, and have the following format,\n# / where both numerator and denominator are positive whole numbers.\n# You can assume that x, and n are valid fractions, and do not have zero as denominator.\n# >>> simplify('1/5', '5/1')\n# TRUE\n# >>> simplify('1/6', '2/1')\n# FALSE\n# >>> simplify('7/10', '10/2')\n# FALSE\nsimplify <- function(x, n) {\n # Convert the fractions to decimal numbers\n x_decimal <- as.numeric(strsplit(x, \"/\")[[1]][1]) / as.numeric(strsplit(x, \"/\")[[1]][2])\n n_decimal <- as.numeric(strsplit(n, \"/\")[[1]][1]) / as.numeric(strsplit(n, \"/\")[[1]][2])\n \n # Multiply the decimal numbers and check if the result is a whole number\n result <- x_decimal * n_decimal\n return(result == as.integer(result))\n}\n"], ["# Write a function which sorts the given list of integers\n# in ascending order according to the sum of their digits.\n# Note: if there are several items with similar sum of their digits,\n# order them based on their index in original list.\n# For example:\n# >>> order_by_points(c(1, 11, -1, -11, -12))\n# c(-1, -11, 1, -12, 11)\n# >>> order_by_points(c())\n# c()\norder_by_points <- function(nums) {\n # Helper function to calculate the sum of digits of a number\n sum_digits <- function(num) {\n sum(as.integer(strsplit(as.character(abs(num)), \"\")[[1]]))\n }\n \n # Calculate the sum of digits for each number in the list\n sums <- sapply(nums, sum_digits)\n \n # Sort the list based on the sums of digits and their original index\n nums[order(sums, seq_along(nums))]\n}\n"], ["# Write a function that takes a vector of numbers as input and returns \n# the number of elements in the vector that are greater than 10 and both \n# first and last digits of a number are odd (1, 3, 5, 7, 9).\n# For example:\n# >>> specialFilter(c(15, -73, 14, -15))\n# 1\n# >>> specialFilter(c(33, -2, -3, 45, 21, 109))\n# 2\nspecialFilter <- function(nums) {\n count <- 0\n for (num in nums) {\n if (num > 10 && abs(num %% 10) %in% c(1, 3, 5, 7, 9) && abs(num %/% 10^(nchar(abs(num))-1)) %in% c(1, 3, 5, 7, 9)) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# You are given a positive integer n. You have to create an integer vector a of length n.\n# For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n# Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n# and a[i] + a[j] + a[k] is a multiple of 3.\n# Example :\n# >>> get_max_triples(5)\n# 1\n# Explanation: \n# a = [1, 3, 7, 13, 21]\n# The only valid triple is (1, 7, 13).\nget_max_triples <- function(n) {\n a <- (1:n)^2 - (1:n) + 1\n count <- 0\n for (i in 1:(n-2)) {\n for (j in (i+1):(n-1)) {\n for (k in (j+1):n) {\n if ((a[i] + a[j] + a[k]) %% 3 == 0) {\n count <- count + 1\n }\n }\n }\n }\n return(count)\n}\n"], ["# There are eight planets in our solar system: the closerst to the Sun \n# is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n# Uranus, Neptune.\n# Write a function that takes two planet names as strings planet1 and planet2. \n# The function should return a list containing all planets whose orbits are \n# located between the orbit of planet1 and the orbit of planet2, sorted by \n# the proximity to the sun. \n# The function should return an empty list if planet1 or planet2\n# are not correct planet names. \n# Examples\n# >>> bf('Jupiter', 'Neptune')\n# c('Saturn', 'Uranus')\n# >>> bf('Earth', 'Mercury')\n# 'Venus'\n# >>> bf('Mercury', 'Uranus')\n# c('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')\nbf <- function(planet1, planet2) {\n planets <- c('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')\n if (!(planet1 %in% planets) || !(planet2 %in% planets)) {\n return(list())\n }\n start <- which(planets == planet1)\n end <- which(planets == planet2)\n if (start > end) {\n temp <- start\n start <- end\n end <- temp\n }\n return(planets[(start+1):(end-1)])\n}\n"], ["# Write a function that accepts a list of strings as a parameter,\n# deletes the strings that have odd lengths from it,\n# and returns the resulted list with a sorted order,\n# The list is always a list of strings and never a vector of numbers,\n# and it may contain duplicates.\n# The order of the list should be ascending by length of each word, and you\n# should return the list sorted by that rule.\n# If two words have the same length, sort the list alphabetically.\n# The function should return a list of strings in sorted order.\n# You may assume that all words will have the same length.\n# For example:\n# >>> list_sort(c('aa', 'a', 'aaa'))\n# c('aa')\n# >>> list_sort(c('ab', 'a', 'aaa', 'cd'))\n# c('ab', 'cd')\nsorted_list_sum <- function(lst) {\n # Filter out strings with odd lengths\n lst <- lst[nchar(lst) %% 2 == 0]\n \n # Sort the list by length and alphabetically\n lst <- lst[order(nchar(lst), lst)]\n \n return(lst)\n}\n"], ["# Return list of all prefixes from shortest to longest of the input string\n# >>> all_prefixes('abc')\n# c('a', 'ab', 'abc')\nall_prefixes <- function(string) {\n n <- nchar(string)\n prefixes <- character(n)\n for (i in 1:n) {\n prefixes[i] <- substr(string, 1, i)\n }\n return(prefixes)\n}\n"], ["# A simple program which should return the value of x if n is \n# a prime number and should return the value of y otherwise.\n# Examples:\n# >>> x_or_y(7, 34, 12)\n# 34\n# >>> x_or_y(15, 8, 5)\n# 5\nx_or_y <- function(n, x, y) {\n if (isPrime(n)) {\n return(x)\n } else {\n return(y)\n }\n}\n\nisPrime <- function(n) {\n if (n <= 1) {\n return(FALSE)\n }\n for (i in 2:(n-1)) {\n if (n %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# Given a list of numbers, return the sum of squares of the numbers\n# in the list that are odd. Ignore numbers that are negative or not integers.\n# >>> double_the_difference(c(1, 3, 2, 0))\n# 10\n# >>> double_the_difference(c(-1, -2, 0))\n# 0\n# >>> double_the_difference(c(9, -2))\n# 81\n# >>> double_the_difference(c(0))\n# 0\n# If the input list is empty, return 0.\ndouble_the_difference <- function(lst) {\n if (length(lst) == 0) {\n return(0)\n }\n odd_nums <- lst[lst %% 2 != 0 & lst >= 0 & lst == round(lst)]\n return(sum(odd_nums^2))\n}\n"], ["# I think we all remember that feeling when the result of some long-awaited\n# event is finally known. The feelings and thoughts you have at that moment are\n# definitely worth noting down and comparing.\n# Your task is to determine if a person correctly guessed the results of a number of matches.\n# You are given two vectors of scores and guesses of equal length, where each index shows a match. \n# Return a vector of the same length denoting how far off each guess was. If they have guessed correctly,\n# the value is 0, and if not, the value is the absolute difference between the guess and the score.\n# example:\n# >>> compare(c(1, 2, 3, 4, 5, 1), c(1, 2, 3, 4, 2, -2))\n# c(0, 0, 0, 0, 3, 3)\n# >>> compare(c(0, 5, 0, 0, 0, 4), c(4, 1, 1, 0, 0, -2))\n# c(4, 4, 1, 0, 0, 6)\ncompare <- function(game, guess) {\n abs(game - guess)\n}\n"], ["# You will be given the name of a class (a string) and a list of extensions.\n# The extensions are to be used to load additional classes to the class. The\n# strength of the extension is as follows: Let CAP be the number of the uppercase\n# letters in the extension's name, and let SM be the number of lowercase letters \n# in the extension's name, the strength is given by the fraction CAP - SM. \n# You should find the strongest extension and return a string in this \n# format: ClassName.StrongestExtensionName.\n# If there are two or more extensions with the same strength, you should\n# choose the one that comes first in the list.\n# For example, if you are given \"Slices\" as the class and a list of the\n# extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n# return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n# (its strength is -1).\n# Example:\n# >>> Strongest_Extension('my_class', c('AA', 'Be', 'CC'))\n# 'my_class.AA'\nStrongest_Extension <- function(class_name, extensions) {\n # Initialize variables\n strongest_extension <- \"\"\n strongest_strength <- -Inf\n \n # Loop through each extension\n for (extension in extensions) {\n # Calculate strength of extension\n CAP <- sum(gregexpr(\"[A-Z]\", extension)[[1]])\n SM <- sum(gregexpr(\"[a-z]\", extension)[[1]])\n strength <- CAP - SM\n \n # Check if this extension is stronger than the current strongest\n if (strength > strongest_strength) {\n strongest_extension <- extension\n strongest_strength <- strength\n }\n }\n \n # Return the strongest extension\n paste0(class_name, \".\", strongest_extension)\n}\n"], ["# You are given 2 words. You need to return TRUE if the second word or any of its rotations is a substring in the first word\n# >>> cycpattern_check('abcd', 'abd')\n# FALSE\n# >>> cycpattern_check('hello', 'ell')\n# TRUE\n# >>> cycpattern_check('whassup', 'psus')\n# FALSE\n# >>> cycpattern_check('abab', 'baa')\n# TRUE\n# >>> cycpattern_check('efef', 'eeff')\n# FALSE\n# >>> cycpattern_check('himenss', 'simen')\n# TRUE\ncycpattern_check <- function(a, b) {\n n <- nchar(a)\n m <- nchar(b)\n if (m > n) {\n return(FALSE)\n }\n for (i in 1:(n-m+1)) {\n if (a[i:(i+m-1)] == b) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n"], ["# Given an integer. return a list that has the number of even and odd digits respectively.\n# Example:\n# >>> even_odd_count(-12)\n# c(1, 1)\n# >>> even_odd_count(123)\n# c(1, 2)\neven_odd_count <- function(num) {\n num <- abs(num)\n digits <- as.integer(strsplit(as.character(num), \"\")[[1]])\n even_count <- sum(digits %% 2 == 0)\n odd_count <- sum(digits %% 2 != 0)\n return(c(even_count, odd_count))\n}\n"], ["# Given a positive integer, obtain its roman numeral equivalent as a string,\n# and return it in lowercase.\n# Restrictions: 1 <= num <= 1000\n# Examples:\n# >>> int_to_mini_roman(19)\n# 'xix'\n# >>> int_to_mini_roman(152)\n# 'clii'\n# >>> int_to_mini_roman(426)\n# 'cdxxvi'\nint_to_mini_roman <- function(number) {\n if (number < 1 || number > 1000) {\n stop(\"Number must be between 1 and 1000\")\n }\n roman_numerals <- c(\"i\", \"ii\", \"iii\", \"iv\", \"v\", \"vi\", \"vii\", \"viii\", \"ix\", \"x\", \"xx\", \"xxx\", \"xl\", \"l\", \"lx\", \"lxx\", \"lxxx\", \"xc\", \"c\", \"cc\", \"ccc\", \"cd\", \"d\", \"dc\", \"dcc\", \"dccc\", \"cm\", \"m\", \"mm\", \"mmm\")\n values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000)\n result <- \"\"\n for (i in rev(seq_along(values))) {\n while (number >= values[i]) {\n result <- paste0(result, roman_numerals[i])\n number <- number - values[i]\n }\n }\n tolower(result)\n}\n"], ["# Given the lengths of the three sides of a triangle. Return TRUE if the three\n# sides form a right-angled triangle, FALSE otherwise.\n# A right-angled triangle is a triangle in which one angle is right angle or \n# 90 degree.\n# Example:\n# >>> right_angle_triangle(3, 4, 5)\n# TRUE\n# >>> right_angle_triangle(1, 2, 3)\n# FALSE\nright_angle_triangle <- function(a, b, c) {\n # Check if the triangle is right-angled\n if (a^2 + b^2 == c^2 || a^2 + c^2 == b^2 || b^2 + c^2 == a^2) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n}\n"], ["# Write a function that accepts a list of strings.\n# The list contains different words. Return the word with maximum number\n# of unique characters. If multiple strings have maximum number of unique\n# characters, return the one which comes first in lexicographical order.\n# >>> find_max(c('name', 'of', 'string'))\n# 'string'\n# >>> find_max(c('name', 'enam', 'game'))\n# 'enam'\n# >>> find_max(c('aaaaaaa', 'bb', 'cc'))\n# 'aaaaaaa'\nfind_max <- function(words) {\n # Initialize variables\n max_unique <- 0\n max_word <- \"\"\n \n # Loop through each word in the list\n for (word in words) {\n # Get the number of unique characters in the word\n unique_chars <- length(unique(strsplit(word, \"\")[[1]]))\n \n # If the number of unique characters is greater than the current maximum,\n # update the maximum and the corresponding word\n if (unique_chars > max_unique) {\n max_unique <- unique_chars\n max_word <- word\n }\n # If the number of unique characters is equal to the current maximum,\n # compare the current word with the current maximum word in lexicographical order\n else if (unique_chars == max_unique && word < max_word) {\n max_word <- word\n }\n }\n \n # Return the word with the maximum number of unique characters\n return(max_word)\n}\n"], ["# You're a hungry rabbit, and you already have eaten a certain number of carrots,\n# but now you need to eat more carrots to complete the day's meals.\n# you should return a vector of [ total number of eaten carrots after your meals,\n# the number of carrots left after your meals ]\n# if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n# Example:\n# >>> eat(5, 6, 10)\n# c(11, 4)\n# >>> eat(4, 8, 9)\n# c(12, 1)\n# >>> eat(1, 10, 10)\n# c(11, 0)\n# >>> eat(2, 11, 5)\n# c(7, 0)\n# Variables:\n# @number : integer\n# the number of carrots that you have eaten.\n# @need : integer\n# the number of carrots that you need to eat.\n# @remaining : integer\n# the number of remaining carrots thet exist in stock\n# Constrain:\n# * 0 <= number <= 1000\n# * 0 <= need <= 1000\n# * 0 <= remaining <= 1000\n# Have fun :)\neat <- function(number, need, remaining) {\n total <- number + need\n left <- remaining - need\n if (left < 0) {\n left <- 0\n }\n return(c(total, left))\n}\n"], ["# Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n# >>> string_sequence(0)\n# '0'\n# >>> string_sequence(5)\n# '0 1 2 3 4 5'\nstring_sequence <- function(n) {\n paste(0:n, collapse=\" \")\n}\n"], ["# Given two lists operator, and operand. The first list has basic algebra operations, and \n# the second list is a list of integers. Use the two given lists to build the algebric \n# expression and return the evaluation of this expression.\n# The basic algebra operations:\n# Addition ( + ) \n# Subtraction ( - ) \n# Multiplication ( * ) \n# Floor division ( // ) \n# Exponentiation ( ** ) \n# Example:\n# operator['+', '*', '-']\n# vector = [2, 3, 4, 5]\n# result = 2 + 3 * 4 - 5\n# => result = 9\n# Note:\n# The length of operator list is equal to the length of operand list minus one.\n# Operand is a list of of non-negative integers.\n# Operator list has at least one operator, and operand list has at least two operands.\ndo_algebra <- function(operator, operand) {\n # Build the algebraic expression\n expression <- paste(operand, collapse = paste(operator, collapse = \"\"))\n \n # Evaluate the expression and return the result\n return(eval(parse(text = expression)))\n}\n"], ["# You are given a string s.\n# if s[i] is a letter, reverse its case from lower to upper or vise versa, \n# otherwise keep it as it is.\n# If the string contains no letters, reverse the string.\n# The function should return the resulted string.\n# Examples\n# >>> solve('1234')\n# '4321'\n# >>> solve('ab')\n# 'AB'\n# >>> solve('#a@C')\n# '#A@c'\nsolve <- function(s) {\n if (grepl('[a-zA-Z]', s)) {\n s <- chartr('a-zA-Z', 'A-Za-z', s)\n } else {\n s <- rev(s)\n }\n return(s)\n}\n"], ["# Given a string 'text', return its md5 hash equivalent string.\n# If 'text' is an empty string, return NULL.\n# >>> string_to_md5('Hello world')\n# '3e25960a79dbc69b674cd4ec67a72c62'\nstring_to_md5 <- function(text) {\n if (text == \"\") {\n return(NULL)\n } else {\n return(digest::md5(text, serialize = FALSE))\n }\n}\n"], ["# Given two positive integers a and b, return the even digits between a\n# and b, in ascending order.\n# For example:\n# >>> generate_integers(2, 8)\n# c(2, 4, 6, 8)\n# >>> generate_integers(8, 2)\n# c(2, 4, 6, 8)\n# >>> generate_integers(10, 14)\n# c()\ngenerate_integers <- function(a, b) {\n # Ensure a is less than or equal to b\n if (a > b) {\n temp <- a\n a <- b\n b <- temp\n }\n \n # Initialize an empty vector to store the even digits\n even_digits <- c()\n \n # Loop through all integers between a and b\n for (i in a:b) {\n # Convert the integer to a string\n digits <- strsplit(as.character(i), \"\")[[1]]\n \n # Loop through each digit in the string\n for (digit in digits) {\n # If the digit is even, add it to the vector\n if (as.integer(digit) %% 2 == 0) {\n even_digits <- c(even_digits, as.integer(digit))\n }\n }\n }\n \n # Sort the vector in ascending order and return it\n sort(even_digits)\n}\n"], ["# Given a string, find out how many distinct characters (regardless of case) does it consist of\n# >>> count_distinct_characters('xyzXYZ')\n# 3\n# >>> count_distinct_characters('Jerry')\n# 4\ncount_distinct_characters <- function(string) {\n return(length(unique(tolower(string))))\n}\n"], ["# Input to this function is a string representing musical notes in a special ASCII format.\n# Your task is to parse this string and return list of integers corresponding to how many beats does each\n# not last.\n# Here is a legend:\n# 'o' - whole note, lasts four beats\n# 'o|' - half note, lasts two beats\n# '.|' - quater note, lasts one beat\n# >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n# c(4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4)\nparse_music <- function(music_string) {\n notes <- strsplit(music_string, \" \")[[1]]\n beats <- c()\n for (note in notes) {\n if (note == \"o\") {\n beats <- c(beats, 4)\n } else if (note == \"o|\") {\n beats <- c(beats, 2)\n } else if (note == \".|\") {\n beats <- c(beats, 1)\n }\n }\n return(beats)\n}\n"], ["# Find how many times a given substring can be found in the original string. Count overlaping cases.\n# >>> how_many_times('', 'a')\n# 0\n# >>> how_many_times('aaa', 'a')\n# 3\n# >>> how_many_times('aaaa', 'aa')\n# 3\nhow_many_times <- function(string, substring) {\n count <- 0\n start <- 1\n while (TRUE) {\n index <- regexpr(substring, string, start)\n if (index == -1) {\n break\n }\n count <- count + 1\n start <- index + attr(index, \"match.length\")\n }\n return(count)\n}\n"], ["# Input is a space-delimited string of numberals from 'zero' to 'nine'.\n# Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n# Return the string with numbers sorted from smallest to largest\n# >>> sort_numbers('three one five')\n# 'one three five'\nsort_numbers <- function(numbers) {\n # Convert the string to a vector of numbers\n num_vec <- sapply(strsplit(numbers, \" \")[[1]], function(x) {\n switch(x,\n \"zero\" = 0,\n \"one\" = 1,\n \"two\" = 2,\n \"three\" = 3,\n \"four\" = 4,\n \"five\" = 5,\n \"six\" = 6,\n \"seven\" = 7,\n \"eight\" = 8,\n \"nine\" = 9)\n })\n \n # Sort the vector of numbers\n sorted_num_vec <- sort(num_vec)\n \n # Convert the sorted vector of numbers back to a string\n sorted_numbers <- paste(sapply(sorted_num_vec, function(x) {\n switch(x,\n 0 = \"zero\",\n 1 = \"one\",\n 2 = \"two\",\n 3 = \"three\",\n 4 = \"four\",\n 5 = \"five\",\n 6 = \"six\",\n 7 = \"seven\",\n 8 = \"eight\",\n 9 = \"nine\")\n }), collapse = \" \")\n \n return(sorted_numbers)\n}\n"], ["# Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n# separate those group into separate strings and return the list of those.\n# Separate groups are balanced (each open brace is properly closed) and not nested within each other\n# Ignore any spaces in the input string.\n# >>> separate_paren_groups('( ) (( )) (( )( ))')\n# c('()', '(())', '(()())')\nseparate_paren_groups <- function(paren_string) {\n # Remove spaces from the input string\n paren_string <- gsub(\" \", \"\", paren_string)\n \n # Initialize an empty list to store the separated groups\n groups <- list()\n \n # Initialize a counter to keep track of the current group level\n level <- 0\n \n # Initialize a string to store the current group\n current_group <- \"\"\n \n # Loop through each character in the input string\n for (char in strsplit(paren_string, \"\")[[1]]) {\n # If the character is an open brace, increment the level counter\n if (char == \"(\") {\n level <- level + 1\n }\n # If the character is a close brace, decrement the level counter\n else if (char == \")\") {\n level <- level - 1\n }\n \n # If the level counter is 0, we have reached the end of a group\n if (level == 0) {\n # Add the current group to the list of groups\n groups <- c(groups, current_group)\n # Reset the current group string\n current_group <- \"\"\n }\n # Otherwise, add the character to the current group string\n else {\n current_group <- paste0(current_group, char)\n }\n }\n \n # Return the list of separated groups\n return(groups)\n}\n"], ["# From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n# other and return them in order (smaller number, larger number).\n# >>> find_closest_elements(c(1.0, 2.0, 3.0, 4.0, 5.0, 2.2))\n# c(2.0, 2.2)\n# >>> find_closest_elements(c(1.0, 2.0, 3.0, 4.0, 5.0, 2.0))\n# c(2.0, 2.0)\nfind_closest_elements <- function(numbers) {\n sorted_numbers <- sort(numbers)\n min_diff <- Inf\n closest_elements <- c()\n for (i in 1:(length(sorted_numbers) - 1)) {\n diff <- sorted_numbers[i + 1] - sorted_numbers[i]\n if (diff < min_diff) {\n min_diff <- diff\n closest_elements <- c(sorted_numbers[i], sorted_numbers[i + 1])\n }\n }\n return(closest_elements)\n}\n"], ["# Given list of numbers (of at least two elements), apply a linear transform to that list,\n# such that the smallest number will become 0 and the largest will become 1\n# >>> rescale_to_unit(c(1.0, 2.0, 3.0, 4.0, 5.0))\n# c(0.0, 0.25, 0.5, 0.75, 1.0)\nrescale_to_unit <- function(numbers) {\n min_num <- min(numbers)\n max_num <- max(numbers)\n range_num <- max_num - min_num\n rescaled_numbers <- (numbers - min_num) / range_num\n return(rescaled_numbers)\n}\n"], ["# Filter given list of any rthon values only for integers\n# >>> filter_integers(list('a', 3.14, 5))\n# c(5)\n# >>> filter_integers(list(1, 2, 3, 'abc', list(), c()))\n# c(1, 2, 3)\nfilter_integers <- function(values) {\n values[sapply(values, is.integer)]\n}\n"], ["# Return length of given string\n# >>> strlen('')\n# 0\n# >>> strlen('abc')\n# 3\nstrlen <- function(string) {\n return(nchar(string))\n}\n"], ["# For a given number n, find the largest number that divides n evenly, smaller than n\n# >>> largest_divisor(15)\n# 5\nlargest_divisor <- function(n) {\n divisors <- seq(1, n-1)\n largest <- divisors[n %% divisors == 0][length(divisors[n %% divisors == 0])]\n return(largest)\n}\n\nlargest_divisor(15)\n"], ["# Return list of prime factors of given integer in the order from smallest to largest.\n# Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n# Input number should be equal to the product of all factors\n# >>> factorize(8)\n# c(2, 2, 2)\n# >>> factorize(25)\n# c(5, 5)\n# >>> factorize(70)\n# c(2, 5, 7)\nfactorize <- function(n) {\n factors <- c()\n i <- 2\n while (i <= n) {\n if (n %% i == 0) {\n factors <- c(factors, i)\n n <- n / i\n } else {\n i <- i + 1\n }\n }\n return(factors)\n}\n"], ["# From a list of integers, remove all elements that occur more than once.\n# Keep order of elements left the same as in the input.\n# >>> remove_duplicates(c(1, 2, 3, 2, 4))\n# c(1, 3, 4)\nremove_duplicates <- function(numbers) {\n unique_numbers <- unique(numbers)\n numbers[match(unique_numbers, numbers)]\n}\n"], ["# For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n# >>> flip_case('Hello')\n# 'hELLO'\nflip_case <- function(string) {\n # Convert string to character vector\n chars <- strsplit(string, \"\")[[1]]\n \n # Flip case of each character\n flipped_chars <- sapply(chars, function(char) {\n if (char %in% letters) {\n if (char %in% toupper(letters)) {\n tolower(char)\n } else {\n toupper(char)\n }\n } else {\n char\n }\n })\n \n # Join flipped characters back into a string\n paste(flipped_chars, collapse = \"\")\n}\n"], ["# Concatenate list of strings into a single string\n# >>> concatenate(c())\n# ''\n# >>> concatenate(c('a', 'b', 'c'))\n# 'abc'\nconcatenate <- function(strings) {\n paste(strings, collapse=\"\")\n}\n"], ["# Filter an input list of strings only for ones that start with a given prefix.\n# >>> filter_by_prefix(c(), 'a')\n# c()\n# >>> filter_by_prefix(c('abc', 'bcd', 'cde', 'array'), 'a')\n# c('abc', 'array')\nfilter_by_prefix <- function(strings, prefix) {\n strings[startsWith(strings, prefix)]\n}\n"], ["# Given a positive floating point number, it can be decomposed into\n# and integer part (largest integer smaller than given number) and decimals\n# (leftover part always smaller than 1).\n# Return the decimal part of the number.\n# >>> truncate_number(3.5)\n# 0.5\ntruncate_number <- function(number) {\n return(number - floor(number))\n}\n"], ["# Return only positive numbers in the list.\n# >>> get_positive(c(-1, 2, -4, 5, 6))\n# c(2, 5, 6)\n# >>> get_positive(c(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))\n# c(5, 3, 2, 3, 9, 123, 1)\nget_positive <- function(l) {\n l[l > 0]\n}\n"], ["# Return true if a given number is prime, and false otherwise.\n# >>> is_prime(6)\n# FALSE\n# >>> is_prime(101)\n# TRUE\n# >>> is_prime(11)\n# TRUE\n# >>> is_prime(13441)\n# TRUE\n# >>> is_prime(61)\n# TRUE\n# >>> is_prime(4)\n# FALSE\n# >>> is_prime(1)\n# FALSE\nis_prime <- function(n) {\n if (n <= 1) {\n return(FALSE)\n }\n for (i in 2:(n-1)) {\n if (n %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# This function takes a list l and returns a list l' such that\n# l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n# to the values of the corresponding indicies of l, but sorted.\n# >>> sort_third(c(1, 2, 3))\n# c(1, 2, 3)\n# >>> sort_third(c(5, 6, 3, 4, 8, 9, 2))\n# c(2, 6, 3, 4, 8, 9, 5)\nsort_third <- function(l) {\n # Extract the values at indices divisible by three\n divisible_by_three <- l[seq(from = 3, to = length(l), by = 3)]\n \n # Sort the values at indices divisible by three\n divisible_by_three_sorted <- sort(divisible_by_three)\n \n # Create a new list with the same values as l, but with the values at indices divisible by three replaced by the sorted values\n l_sorted <- l\n l_sorted[seq(from = 3, to = length(l), by = 3)] <- divisible_by_three_sorted\n \n # Return the new list\n l_sorted\n}\n"], ["# Return sorted unique elements in a list\n# >>> unique(c(5, 3, 5, 2, 3, 3, 9, 0, 123))\n# c(0, 2, 3, 5, 9, 123)\nunique <- function(l) {\n sort(unique(l))\n}\n\nunique(c(5, 3, 5, 2, 3, 3, 9, 0, 123))\n"], ["# Return maximum element in the list.\n# >>> max_element(c(1, 2, 3))\n# 3\n# >>> max_element(c(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))\n# 123\nmax_element <- function(l) {\n return(max(l))\n}\n"], ["# Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n# >>> fizz_buzz(50)\n# 0\n# >>> fizz_buzz(78)\n# 2\n# >>> fizz_buzz(79)\n# 3\nfizz_buzz <- function(n) {\n count <- 0\n for (i in 1:n) {\n if (i %% 11 == 0 || i %% 13 == 0) {\n count <- count + str_count(i, \"7\")\n }\n }\n return(count)\n}\n"], ["# This function takes a list l and returns a list l' such that\n# l' is identical to l in the odd indicies, while its values at the even indicies are equal\n# to the values of the even indicies of l, but sorted.\n# >>> sort_even(c(1, 2, 3))\n# c(1, 2, 3)\n# >>> sort_even(c(5, 6, 3, 4))\n# c(3, 6, 5, 4)\nsort_even <- function(l) {\n even_values <- sort(l[seq(2, length(l), 2)])\n l[seq(2, length(l), 2)] <- even_values\n return(l)\n}\n"], ["# prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n# >>> prime_fib(1)\n# 2\n# >>> prime_fib(2)\n# 3\n# >>> prime_fib(3)\n# 5\n# >>> prime_fib(4)\n# 13\n# >>> prime_fib(5)\n# 89\nprime_fib <- function(n) {\n fib <- c(0, 1)\n i <- 2\n while (length(fib) < n) {\n fib[i+1] <- fib[i] + fib[i-1]\n i <- i + 1\n }\n prime <- c()\n for (j in 1:length(fib)) {\n if (isPrime(fib[j])) {\n prime <- c(prime, fib[j])\n }\n }\n return(prime[n])\n}\n\nisPrime <- function(n) {\n if (n <= 1) {\n return(FALSE)\n }\n for (i in 2:sqrt(n)) {\n if (n %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# You're given a list of deposit and withdrawal operations on a bank account that starts with\n# zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n# at that point function should return TRUE. Otherwise it should return FALSE.\n# >>> below_zero(c(1, 2, 3))\n# FALSE\n# >>> below_zero(c(1, 2, -4, 5))\n# TRUE\nbelow_zero <- function(operations) {\n balance <- 0\n for (i in operations) {\n balance <- balance + i\n if (balance < 0) {\n return(TRUE)\n }\n }\n return(FALSE)\n}\n"], ["# triples_sum_to_zero takes a list of integers as an input.\n# it returns TRUE if there are three distinct elements in the list that\n# sum to zero, and FALSE otherwise.\n# >>> triples_sum_to_zero(c(1, 3, 5, 0))\n# FALSE\n# >>> triples_sum_to_zero(c(1, 3, -2, 1))\n# TRUE\n# >>> triples_sum_to_zero(c(1, 2, 3, 7))\n# FALSE\n# >>> triples_sum_to_zero(c(2, 4, -5, 3, 9, 7))\n# TRUE\n# >>> triples_sum_to_zero(c(1))\n# FALSE\ntriples_sum_to_zero <- function(l) {\n n <- length(l)\n for (i in 1:(n-2)) {\n for (j in (i+1):(n-1)) {\n for (k in (j+1):n) {\n if (l[i] + l[j] + l[k] == 0) {\n return(TRUE)\n }\n }\n }\n }\n return(FALSE)\n}\n"], ["# Imagine a road that's a perfectly straight infinitely long line.\n# n cars are driving left to right; simultaneously, a different set of n cars\n# are driving right to left. The two sets of cars start out being very far from\n# each other. All cars move in the same speed. Two cars are said to collide\n# when a car that's moving left to right hits a car that's moving right to left.\n# However, the cars are infinitely sturdy and strong; as a result, they continue moving\n# in their trajectory as if they did not collide.\n# This function outputs the number of such collisions.\ncar_race_collision <- function(n) {\n # Since the cars are moving in the same speed, they will collide exactly n times.\n return(n)\n}\n"], ["# Return list with elements incremented by 1.\n# >>> incr_list(c(1, 2, 3))\n# c(2, 3, 4)\n# >>> incr_list(c(5, 3, 5, 2, 3, 3, 9, 0, 123))\n# c(6, 4, 6, 3, 4, 4, 10, 1, 124)\nincr_list <- function(l) {\n l + 1\n}\n"], ["# pairs_sum_to_zero takes a list of integers as an input.\n# it returns TRUE if there are two distinct elements in the list that\n# sum to zero, and FALSE otherwise.\n# >>> pairs_sum_to_zero(c(1, 3, 5, 0))\n# FALSE\n# >>> pairs_sum_to_zero(c(1, 3, -2, 1))\n# FALSE\n# >>> pairs_sum_to_zero(c(1, 2, 3, 7))\n# FALSE\n# >>> pairs_sum_to_zero(c(2, 4, -5, 3, 5, 7))\n# TRUE\n# >>> pairs_sum_to_zero(c(1))\n# FALSE\npairs_sum_to_zero <- function(l) {\n for (i in 1:(length(l)-1)) {\n for (j in (i+1):length(l)) {\n if (l[i] + l[j] == 0) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n}\n"], ["# Change numerical base of input number x to base.\n# return string representation after the conversion.\n# base numbers are less than 10.\n# >>> change_base(8, 3)\n# '22'\n# >>> change_base(8, 2)\n# '1000'\n# >>> change_base(7, 2)\n# '111'\nchange_base <- function(x, base) {\n return(as.character(as.integer(x, base=base)))\n}\n"], ["# Given length of a side and high return area for a triangle.\n# >>> triangle_area(5, 3)\n# 7.5\ntriangle_area <- function(a, h) {\n return(0.5 * a * h)\n}\n"], ["# The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n# fib4(0) -> 0\n# fib4(1) -> 0\n# fib4(2) -> 2\n# fib4(3) -> 0\n# fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n# Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n# >>> fib4(5)\n# 4\n# >>> fib4(6)\n# 8\n# >>> fib4(7)\n# 14\nfib4 <- function(n) {\n if (n < 4) {\n return(0)\n } else if (n == 4) {\n return(2)\n } else {\n fib_seq <- c(0, 0, 2, 0)\n for (i in 5:n) {\n fib_seq[i] <- sum(fib_seq[(i-4):(i-1)])\n }\n return(fib_seq[n])\n }\n}\n"], ["# Return median of elements in the list l.\n# >>> median(c(3, 1, 2, 4, 5))\n# 3\n# >>> median(c(-10, 4, 6, 1000, 10, 20))\n# 15.0\nmedian <- function(l) {\n l <- sort(l)\n n <- length(l)\n if (n %% 2 == 0) {\n return((l[n/2] + l[n/2 + 1]) / 2)\n } else {\n return(l[ceiling(n/2)])\n }\n}\n"], ["# Checks if given string is a palindrome\n# >>> is_palindrome('')\n# TRUE\n# >>> is_palindrome('aba')\n# TRUE\n# >>> is_palindrome('aaaaa')\n# TRUE\n# >>> is_palindrome('zbcd')\n# FALSE\nis_palindrome <- function(text) {\n text <- tolower(text)\n return(text == rev(text))\n}\n"], ["# Return 2^n modulo p (be aware of numerics).\n# >>> modp(3, 5)\n# 3\n# >>> modp(1101, 101)\n# 2\n# >>> modp(0, 101)\n# 1\n# >>> modp(3, 11)\n# 8\n# >>> modp(100, 101)\n# 1\nmodp <- function(n, p) {\n return((2^n) %% p)\n}\n"], ["# For a given list of input numbers, calculate Mean Absolute Deviation\n# around the mean of this dataset.\n# Mean Absolute Deviation is the average absolute difference between each\n# element and a centerpoint (mean in this case):\n# MAD = average | x - x_mean |\n# >>> mean_absolute_deviation(c(1.0, 2.0, 3.0, 4.0))\n# 1.0\nmean_absolute_deviation <- function(numbers) {\n x_mean <- mean(numbers)\n absolute_differences <- abs(numbers - x_mean)\n MAD <- mean(absolute_differences)\n return(MAD)\n}\n"], ["# remove_vowels is a function that takes string and returns string without vowels.\n# >>> remove_vowels('')\n# ''\n# >>> remove_vowels('abcdef')\n# 'bcdf'\n# >>> remove_vowels('aaaaa')\n# ''\n# >>> remove_vowels('aaBAA')\n# 'B'\n# >>> remove_vowels('zbcd')\n# 'zbcd'\nremove_vowels <- function(text) {\n gsub(\"[aeiouAEIOU]\", \"\", text)\n}\n"], ["# Return TRUE if all numbers in the list l are below threshold t.\n# >>> below_threshold(c(1, 2, 4, 10), 100)\n# TRUE\n# >>> below_threshold(c(1, 20, 4, 10), 5)\n# FALSE\nbelow_threshold <- function(l, t) {\n all(l < t)\n}\n"], ["# Add two numbers x and y\n# >>> add(2, 3)\n# 5\n# >>> add(5, 7)\n# 12\nadd <- function(x, y) {\n return(x + y)\n}\n"], ["# Check if two words have the same characters.\n# >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n# TRUE\n# >>> same_chars('abcd', 'dddddddabc')\n# TRUE\n# >>> same_chars('dddddddabc', 'abcd')\n# TRUE\n# >>> same_chars('eabcd', 'dddddddabc')\n# FALSE\n# >>> same_chars('abcd', 'dddddddabce')\n# FALSE\n# >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n# FALSE\nsame_chars <- function(s0, s1) {\n # Convert the strings to character vectors\n c0 <- strsplit(s0, \"\")[[1]]\n c1 <- strsplit(s1, \"\")[[1]]\n \n # Sort the character vectors\n c0 <- sort(c0)\n c1 <- sort(c1)\n \n # Compare the sorted character vectors\n identical(c0, c1)\n}\n"], ["# Return n-th Fibonacci number.\n# >>> fib(10)\n# 55\n# >>> fib(1)\n# 1\n# >>> fib(8)\n# 21\nfib <- function(n) {\n if (n <= 1) {\n return(n)\n } else {\n return(fib(n-1) + fib(n-2))\n }\n}\n"], ["# brackets is a string of \"<\" and \">\".\n# return TRUE if every opening bracket has a corresponding closing bracket.\n# >>> correct_bracketing('<')\n# FALSE\n# >>> correct_bracketing('<>')\n# TRUE\n# >>> correct_bracketing('<<><>>')\n# TRUE\n# >>> correct_bracketing('><<>')\n# FALSE\ncorrect_bracketing <- function(brackets) {\n stack <- c()\n for (bracket in strsplit(brackets, \"\")[[1]]) {\n if (bracket == \"<\") {\n stack <- c(stack, \"<\")\n } else if (bracket == \">\") {\n if (length(stack) == 0) {\n return(FALSE)\n } else {\n stack <- stack[-1]\n }\n }\n }\n return(length(stack) == 0)\n}\n"], ["# Return TRUE is list elements are monotonically increasing or decreasing.\n# >>> monotonic(c(1, 2, 4, 20))\n# TRUE\n# >>> monotonic(c(1, 20, 4, 10))\n# FALSE\n# >>> monotonic(c(4, 1, 0, -10))\n# TRUE\nmonotonic <- function(l) {\n diffs <- diff(l)\n all(diffs >= 0) || all(diffs <= 0)\n}\n"], ["# Return sorted unique common elements for two lists.\n# >>> common(c(1, 4, 3, 34, 653, 2, 5), c(5, 7, 1, 5, 9, 653, 121))\n# c(1, 5, 653)\n# >>> common(c(5, 3, 2, 8), c(3, 2))\n# c(2, 3)\ncommon <- function(l1, l2) {\n # Find the intersection of the two lists\n intersection <- intersect(l1, l2)\n \n # Sort and return the unique elements of the intersection\n return(sort(unique(intersection)))\n}\n"], ["# Return the largest prime factor of n. Assume n > 1 and is not a prime.\n# >>> largest_prime_factor(13195)\n# 29\n# >>> largest_prime_factor(2048)\n# 2\nlargest_prime_factor <- function(n) {\n i <- 2\n while (i * i <= n) {\n if (n %% i == 0) {\n n <- n / i\n } else {\n i <- i + 1\n }\n }\n return(n)\n}\n\nlargest_prime_factor(13195)\nlargest_prime_factor(2048)\n"], ["# Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n# >>> intersperse(c(), 4)\n# c()\n# >>> intersperse(c(1, 2, 3), 4)\n# c(1, 4, 2, 4, 3)\nintersperse <- function(numbers, delimeter) {\n if (length(numbers) == 0) {\n return(c())\n }\n result <- c(numbers[1])\n for (i in 2:length(numbers)) {\n result <- c(result, delimeter, numbers[i])\n }\n return(result)\n}\n"], ["# sum_to_n is a function that sums numbers from 1 to n.\n# >>> sum_to_n(30)\n# 465\n# >>> sum_to_n(100)\n# 5050\n# >>> sum_to_n(5)\n# 15\n# >>> sum_to_n(10)\n# 55\n# >>> sum_to_n(1)\n# 1\nsum_to_n <- function(n) {\n return(n*(n+1)/2)\n}\n"], ["# brackets is a string of \"(\" and \")\".\n# return TRUE if every opening bracket has a corresponding closing bracket.\n# >>> correct_bracketing('(')\n# FALSE\n# >>> correct_bracketing('()')\n# TRUE\n# >>> correct_bracketing('(()())')\n# TRUE\n# >>> correct_bracketing(')(()')\n# FALSE\ncorrect_bracketing <- function(brackets) {\n stack <- c()\n for (i in 1:nchar(brackets)) {\n if (substr(brackets, i, i) == \"(\") {\n stack <- c(stack, \"(\")\n } else if (substr(brackets, i, i) == \")\") {\n if (length(stack) == 0) {\n return(FALSE)\n } else {\n stack <- stack[-length(stack)]\n }\n }\n }\n return(length(stack) == 0)\n}\n"], ["# xs represent coefficients of a polynomial.\n# xs[0] + xs[1] * x + xs[2] * x^2 + ....\n# Return derivative of this polynomial in the same form.\n# >>> derivative(c(3, 1, 2, 4, 5))\n# c(1, 4, 12, 20)\n# >>> derivative(c(1, 2, 3))\n# c(2, 6)\nderivative <- function(xs) {\n n <- length(xs)\n if (n == 1) {\n return(0)\n } else {\n return(seq(2, n) * xs[2:n])\n }\n}\n"], ["# The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n# fibfib(0) == 0\n# fibfib(1) == 0\n# fibfib(2) == 1\n# fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n# Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n# >>> fibfib(1)\n# 0\n# >>> fibfib(5)\n# 4\n# >>> fibfib(8)\n# 24\nfibfib <- function(n) {\n if (n == 0 || n == 1) {\n return(0)\n } else if (n == 2) {\n return(1)\n } else {\n a <- 0\n b <- 0\n c <- 1\n for (i in 3:n) {\n temp <- a + b + c\n a <- b\n b <- c\n c <- temp\n }\n return(c)\n }\n}\n"], ["# Write a function vowels_count which takes a string representing\n# a word as input and returns the number of vowels in the string.\n# Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n# vowel, but only when it is at the end of the given word.\n# Example:\n# >>> vowels_count('abcde')\n# 2\n# >>> vowels_count('ACEDY')\n# 3\nvowels_count <- function(s) {\n vowels <- c('a', 'e', 'i', 'o', 'u', 'y')\n count <- 0\n for (i in 1:nchar(s)) {\n if (tolower(substr(s, i, i)) %in% vowels) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# Circular shift the digits of the integer x, shift the digits right by shift\n# and return the result as a string.\n# If shift > number of digits, return digits reversed.\n# >>> circular_shift(12, 1)\n# '21'\n# >>> circular_shift(12, 2)\n# '12'\ncircular_shift <- function(x, shift) {\n # Convert x to a string\n x_str <- as.character(x)\n \n # If shift is greater than the number of digits, reverse the digits\n if (shift > nchar(x_str)) {\n return(paste(rev(strsplit(x_str, \"\")[[1]]), collapse = \"\"))\n }\n \n # Circularly shift the digits\n shifted_str <- paste(c(substr(x_str, shift + 1, nchar(x_str)), substr(x_str, 1, shift)), collapse = \"\")\n \n return(shifted_str)\n}\n"], ["# Task\n# Write a function that takes a string as input and returns the sum of the upper characters only'\n# ASCII codes.\n# Examples:\n# >>> digitSum('')\n# 0\n# >>> digitSum('abAB')\n# 131\n# >>> digitSum('abcCd')\n# 67\n# >>> digitSum('helloE')\n# 69\n# >>> digitSum('woArBld')\n# 131\n# >>> digitSum('aAaaaXa')\n# 153\ndigitSum <- function(s) {\n sum(as.integer(strsplit(s, \"\")[[1]][which(grepl(\"[A-Z]\", s))]))\n}\n"], ["# In this task, you will be given a string that represents a number of apples and oranges \n# that are distributed in a basket of fruit this basket contains \n# apples, oranges, and mango fruits. Given the string that represents the total number of \n# the oranges and apples and an integer that represent the total number of the fruits \n# in the basket return the number of the mango fruits in the basket.\n# for examble:\n# >>> fruit_distribution('5 apples and 6 oranges', 19)\n# 8\n# >>> fruit_distribution('0 apples and 1 oranges', 3)\n# 2\n# >>> fruit_distribution('2 apples and 3 oranges', 100)\n# 95\n# >>> fruit_distribution('100 apples and 1 oranges', 120)\n# 19\nfruit_distribution <- function(s, n) {\n # Split the string into two parts\n parts <- strsplit(s, \" and \")[[1]]\n \n # Extract the number of apples and oranges\n apples <- as.numeric(gsub(\" apples\", \"\", parts[1]))\n oranges <- as.numeric(gsub(\" oranges\", \"\", parts[2]))\n \n # Calculate the number of mango fruits\n mangoes <- n - apples - oranges\n \n # Return the result\n return(mangoes)\n}\n"], ["# \"Given a vector representing a branch of a tree that has non-negative integer nodes\n# your task is to pluck one of the nodes and return it.\n# The plucked node should be the node with the smallest even value.\n# If multiple nodes with the same smallest even value are found return the node that has smallest index.\n# The plucked node should be returned in a list, [ smalest_value, its index ],\n# If there are no even values or the given vector is empty, return [].\n# Example 1:\n# >>> pluck(c(4, 2, 3))\n# c(2, 1)\n# Explanation: 2 has the smallest even value, and 2 has the smallest index.\n# Example 2:\n# >>> pluck(c(1, 2, 3))\n# c(2, 1)\n# Explanation: 2 has the smallest even value, and 2 has the smallest index.\n# Example 3:\n# >>> pluck(c())\n# c()\n# Example 4:\n# >>> pluck(c(5, 0, 3, 0, 4, 2))\n# c(0, 1)\n# Explanation: 0 is the smallest value, but there are two zeros,\n# so we will choose the first zero, which has the smallest index.\n# Constraints:\n# * 1 <= nodes.length <= 10000\n# * 0 <= node.value\npluck <- function(arr) {\n # Filter out even values\n even_values <- arr[arr %% 2 == 0]\n \n # If there are no even values, return an empty list\n if (length(even_values) == 0) {\n return(list())\n }\n \n # Find the smallest even value\n smallest_even <- min(even_values)\n \n # Find the index of the smallest even value\n smallest_index <- which(arr == smallest_even)[1]\n \n # Return the smallest even value and its index\n return(list(smallest_even, smallest_index))\n}\n"], ["# You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n# zero, and has a frequency greater than or equal to the value of the integer itself. \n# The frequency of an integer is the number of times it appears in the list.\n# If no such a value exist, return -1.\n# Examples:\n# >>> search(c(4, 1, 2, 2, 3, 1))\n# 2\n# >>> search(c(1, 2, 2, 3, 3, 3, 4, 4, 4))\n# 3\n# >>> search(c(5, 5, 4, 4, 4))\n# -1\nsearch <- function(lst) {\n freq <- table(lst)\n max_freq <- max(freq)\n for (i in max_freq:1) {\n if (i <= length(freq) && freq[i] >= i) {\n return(i)\n }\n }\n return(-1)\n}\n"], ["# Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n# For each of the group, output the deepest level of nesting of parentheses.\n# E.g. (()()) has maximum two levels of nesting while ((())) has three.\n# >>> parse_nested_parens('(()()) ((())) () ((())()())')\n# c(2, 3, 1, 3)\nparse_nested_parens <- function(paren_string) {\n # Split the string into individual groups\n groups <- strsplit(paren_string, ' ')[[1]]\n \n # Initialize an empty vector to store the results\n results <- c()\n \n # Loop through each group\n for (group in groups) {\n # Initialize a counter for the current level of nesting\n level <- 0\n \n # Initialize a counter for the maximum level of nesting\n max_level <- 0\n \n # Loop through each character in the group\n for (char in strsplit(group, '')[[1]]) {\n # If the character is an opening parenthesis, increment the level counter\n if (char == '(') {\n level <- level + 1\n }\n \n # If the character is a closing parenthesis, decrement the level counter\n if (char == ')') {\n level <- level - 1\n }\n \n # If the level counter is greater than the maximum level counter, update the maximum level counter\n if (level > max_level) {\n max_level <- level\n }\n }\n \n # Append the maximum level of nesting to the results vector\n results <- c(results, max_level)\n }\n \n # Return the results vector\n return(results)\n}\n"], ["# Given list of integers, return list in strange order.\n# Strange sorting, is when you start with the minimum value,\n# then maximum of the remaining integers, then minimum and so on.\n# Examples:\n# >>> strange_sort_list(c(1, 2, 3, 4))\n# c(1, 4, 2, 3)\n# >>> strange_sort_list(c(5, 5, 5, 5))\n# c(5, 5, 5, 5)\n# >>> strange_sort_list(c())\n# c()\nstrange_sort_list <- function(lst) {\n sorted_lst <- sort(lst)\n result <- c()\n while (length(sorted_lst) > 0) {\n result <- c(result, sorted_lst[1])\n sorted_lst <- sorted_lst[-1]\n if (length(sorted_lst) > 0) {\n result <- c(result, sorted_lst[length(sorted_lst)])\n sorted_lst <- sorted_lst[-length(sorted_lst)]\n }\n }\n return(result)\n}\n"], ["# Given the lengths of the three sides of a triangle. Return the area of\n# the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n# Otherwise return -1\n# Three sides make a valid triangle when the sum of any two sides is greater \n# than the third side.\n# Example:\n# >>> triangle_area(3, 4, 5)\n# 6.0\n# >>> triangle_area(1, 2, 10)\n# -1\ntriangle_area <- function(a, b, c) {\n if (a + b > c && a + c > b && b + c > a) {\n s <- (a + b + c) / 2\n area <- sqrt(s * (s - a) * (s - b) * (s - c))\n return(round(area, 2))\n } else {\n return(-1)\n }\n}\n"], ["# Write a function that returns TRUE if the object q will fly, and FALSE otherwise.\n# The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n# Example:\n# >>> will_it_fly(c(1, 2), 5)\n# FALSE\n# # 1+2 is less than the maximum possible weight, but it's unbalanced.\n# >>> will_it_fly(c(3, 2, 3), 1)\n# FALSE\n# # it's balanced, but 3+2+3 is more than the maximum possible weight.\n# >>> will_it_fly(c(3, 2, 3), 9)\n# TRUE\n# # 3+2+3 is less than the maximum possible weight, and it's balanced.\n# >>> will_it_fly(c(3), 5)\n# TRUE\n# # 3 is less than the maximum possible weight, and it's balanced.\nwill_it_fly <- function(q, w) {\n # Check if the list is balanced (palindromic)\n is_balanced <- all(q == rev(q))\n \n # Check if the sum of the elements is less than or equal to the maximum possible weight\n is_weight_ok <- sum(q) <= w\n \n # Return TRUE if both conditions are met, FALSE otherwise\n return(is_balanced & is_weight_ok)\n}\n"], ["# Given a vector arr of integers, find the minimum number of elements that\n# need to be changed to make the vector palindromic. A palindromic vector is a vector that\n# is read the same backwards and forwards. In one change, you can change one element to any other element.\n# For example:\n# >>> smallest_change(c(1, 2, 3, 5, 4, 7, 9, 6))\n# 4\n# >>> smallest_change(c(1, 2, 3, 4, 3, 2, 2))\n# 1\n# >>> smallest_change(c(1, 2, 3, 2, 1))\n# 0\nsmallest_change <- function(arr) {\n n <- length(arr)\n count <- 0\n for (i in 1:(n/2)) {\n if (arr[i] != arr[n-i+1]) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# Write a function that accepts two lists of strings and returns the list that has \n# total number of chars in the all strings of the list less than the other list.\n# if the two lists have the same number of chars, return the first list.\n# Examples\n# >>> total_match(c(), c())\n# c()\n# >>> total_match(c('hi', 'admin'), c('hI', 'Hi'))\n# c('hI', 'Hi')\n# >>> total_match(c('hi', 'admin'), c('hi', 'hi', 'admin', 'project'))\n# c('hi', 'admin')\n# >>> total_match(c('hi', 'admin'), c('hI', 'hi', 'hi'))\n# c('hI', 'hi', 'hi')\n# >>> total_match(c('4'), c('1', '2', '3', '4', '5'))\n# c('4')\ntotal_match <- function(lst1, lst2) {\n len1 <- sum(nchar(lst1))\n len2 <- sum(nchar(lst2))\n if (len1 < len2) {\n return(lst1)\n } else if (len1 > len2) {\n return(lst2)\n } else {\n return(lst1)\n }\n}\n"], ["# Write a function that returns true if the given number is the multiplication of 3 prime numbers\n# and false otherwise.\n# Knowing that (a) is less then 100. \n# Example:\n# >>> is_multiply_prime(30)\n# TRUE\n# 30 = 2 * 3 * 5\nis_multiply_prime <- function(a) {\n if (a < 100) {\n primes <- c(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)\n for (i in 1:length(primes)) {\n for (j in 1:length(primes)) {\n for (k in 1:length(primes)) {\n if (primes[i] * primes[j] * primes[k] == a) {\n return(TRUE)\n }\n }\n }\n }\n }\n return(FALSE)\n}\n"], ["# Your task is to write a function that returns true if a number x is a simple\n# power of n and false in other cases.\n# x is a simple power of n if n**int=x\n# For example:\n# >>> is_simple_power(1, 4)\n# TRUE\n# >>> is_simple_power(2, 2)\n# TRUE\n# >>> is_simple_power(8, 2)\n# TRUE\n# >>> is_simple_power(3, 2)\n# FALSE\n# >>> is_simple_power(3, 1)\n# FALSE\n# >>> is_simple_power(5, 3)\n# FALSE\nis_simple_power <- function(x, n) {\n # Check if x is a positive integer\n if (x <= 0 || x != as.integer(x)) {\n return(FALSE)\n }\n \n # Check if n is a positive integer\n if (n <= 0 || n != as.integer(n)) {\n return(FALSE)\n }\n \n # Check if x is a simple power of n\n int <- log(x, base=n)\n if (int == as.integer(int)) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n}\n"], ["# Write a function that takes an integer a and returns TRUE \n# if this ingeger is a cube of some integer number.\n# Note: you may assume the input is always valid.\n# Examples:\n# >>> iscube(1)\n# TRUE\n# >>> iscube(2)\n# FALSE\n# >>> iscube(-1)\n# TRUE\n# >>> iscube(64)\n# TRUE\n# >>> iscube(0)\n# TRUE\n# >>> iscube(180)\n# FALSE\niscube <- function(a) {\n # Calculate the cube root of a\n cube_root <- round(abs(a)^(1/3))\n \n # Check if the cube root is equal to a\n if (cube_root^3 == abs(a)) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n}\n"], ["# You have been tasked to write a function that receives \n# a hexadecimal number as a string and counts the number of hexadecimal \n# digits that are primes (prime number, or a prime, is a natural number \n# greater than 1 that is not a product of two smaller natural numbers).\n# Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n# Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n# So you have to determine a number of the following digits: 2, 3, 5, 7, \n# B (=decimal 11), D (=decimal 13).\n# Note: you may assume the input is always correct or empty string, \n# and symbols A,B,C,D,E,F are always uppercase.\n# Examples:\n# >>> hex_key('AB')\n# 1\n# >>> hex_key('1077E')\n# 2\n# >>> hex_key('ABED1A33')\n# 4\n# >>> hex_key('123456789ABCDEF0')\n# 6\n# >>> hex_key('2020')\n# 2\nhex_key <- function(num) {\n primes <- c(2, 3, 5, 7, 11, 13)\n count <- 0\n for (i in 1:nchar(num)) {\n if (toupper(substr(num, i, i)) %in% c('2', '3', '5', '7', 'B', 'D')) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# You will be given a number in decimal form and your task is to convert it to\n# binary format. The function should return a string, with each character representing a binary\n# number. Each character in the string will be '0' or '1'.\n# There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n# The extra characters are there to help with the format.\n# Examples:\n# >>> decimal_to_binary(15)\n# 'db1111db'\n# >>> decimal_to_binary(32)\n# 'db100000db'\ndecimal_to_binary <- function(decimal) {\n binary <- paste0(\"db\", intToBin(decimal), \"db\")\n return(binary)\n}\n"], ["# Filter an input list of strings only for ones that contain given substring\n# >>> filter_by_substring(c(), 'a')\n# c()\n# >>> filter_by_substring(c('abc', 'bacd', 'cde', 'array'), 'a')\n# c('abc', 'bacd', 'array')\nfilter_by_substring <- function(strings, substring) {\n strings[grepl(substring, strings)]\n}\n"], ["# You are given a string s.\n# Your task is to check if the string is hapr or not.\n# A string is hapr if its length is at least 3 and every 3 consecutive letters are distinct\n# For example:\n# >>> is_happy('a')\n# FALSE\n# >>> is_happy('aa')\n# FALSE\n# >>> is_happy('abcd')\n# TRUE\n# >>> is_happy('aabb')\n# FALSE\n# >>> is_happy('adb')\n# TRUE\n# >>> is_happy('xyy')\n# FALSE\nis_happy <- function(s) {\n if (nchar(s) < 3) {\n return(FALSE)\n }\n for (i in 1:(nchar(s) - 2)) {\n if (substr(s, i, i + 2) %in% substr(s, i + 1, nchar(s))) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# It is the last week of the semester and the teacher has to give the grades\n# to students. The teacher has been making her own algorithm for grading.\n# The only problem is, she has lost the code she used for grading.\n# She has given you a list of GPAs for some students and you have to write \n# a function that can output a list of letter grades using the following table:\n# GPA | Letter grade\n# 4.0 A+\n# > 3.7 A \n# > 3.3 A- \n# > 3.0 B+\n# > 2.7 B \n# > 2.3 B-\n# > 2.0 C+\n# > 1.7 C\n# > 1.3 C-\n# > 1.0 D+ \n# > 0.7 D \n# > 0.0 D-\n# 0.0 E\n# Example:\n# >>> grade_equation(c(4.0, 3, 1.7, 2, 3.5))\n# c('A+', 'B', 'C-', 'C', 'A-')\nnumerical_letter_grade <- function(grades) {\n letter_grades <- c()\n for (i in 1:length(grades)) {\n if (grades[i] == 4.0) {\n letter_grades <- c(letter_grades, \"A+\")\n } else if (grades[i] > 3.7) {\n letter_grades <- c(letter_grades, \"A\")\n } else if (grades[i] > 3.3) {\n letter_grades <- c(letter_grades, \"A-\")\n } else if (grades[i] > 3.0) {\n letter_grades <- c(letter_grades, \"B+\")\n } else if (grades[i] > 2.7) {\n letter_grades <- c(letter_grades, \"B\")\n } else if (grades[i] > 2.3) {\n letter_grades <- c(letter_grades, \"B-\")\n } else if (grades[i] > 2.0) {\n letter_grades <- c(letter_grades, \"C+\")\n } else if (grades[i] > 1.7) {\n letter_grades <- c(letter_grades, \"C\")\n } else if (grades[i] > 1.3) {\n letter_grades <- c(letter_grades, \"C-\")\n } else if (grades[i] > 1.0) {\n letter_grades <- c(letter_grades, \"D+\")\n } else if (grades[i] > 0.7) {\n letter_grades <- c(letter_grades, \"D\")\n } else if (grades[i] > 0.0) {\n letter_grades <- c(letter_grades, \"D-\")\n } else {\n letter_grades <- c(letter_grades, \"E\")\n }\n }\n return(letter_grades)\n}\n\ngrades <- c(4.0, 3, 1.7, 2, 3.5)\nnumerical_letter_grade(grades)\n"], ["# Write a function that takes a string and returns TRUE if the string\n# length is a prime number or FALSE otherwise\n# Examples\n# >>> prime_length('Hello')\n# TRUE\n# >>> prime_length('abcdcba')\n# TRUE\n# >>> prime_length('kittens')\n# TRUE\n# >>> prime_length('orange')\n# FALSE\nprime_length <- function(string) {\n length <- nchar(string)\n if (length == 1) {\n return(FALSE)\n }\n for (i in 2:(length-1)) {\n if (length %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n"], ["# Given a positive integer n, return the count of the numbers of n-digit\n# positive integers that start or end with 1.\nstarts_one_ends <- function(n) {\n if (n == 1) {\n return(2)\n } else {\n return(2 * starts_one_ends(n-1))\n }\n}\n"], ["# Given a positive integer N, return the total sum of its digits in binary.\n# Example\n# >>> solve(1000)\n# '1'\n# >>> solve(150)\n# '110'\n# >>> solve(147)\n# '1100'\n# Variables:\n# @N integer\n# Constraints: 0 \u2264 N \u2264 10000.\n# Output:\n# a string of binary number\nsolve <- function(N) {\n binary <- \"\"\n while (N > 0) {\n binary <- as.character(N %% 2) %>% paste(binary, sep = \"\")\n N <- N %/% 2\n }\n return(binary)\n}\n"], ["# Given a non-empty list of integers lst. add the even elements that are at odd indices..\n# Examples:\n# >>> add(c(4, 2, 6, 7))\n# 2\nadd <- function(lst) {\n sum(lst[seq(1, length(lst), 2)][lst[seq(1, length(lst), 2)] %% 2 == 0])\n}\n"], ["# Write a function that takes a string and returns an ordered version of it.\n# Ordered version of string, is a string where all words (separated by space)\n# are replaced by a new word where all the characters arranged in\n# ascending order based on ascii value.\n# Note: You should keep the order of words and blank spaces in the sentence.\n# For example:\n# >>> anti_shuffle('Hi')\n# 'Hi'\n# >>> anti_shuffle('hello')\n# 'ehllo'\n# >>> anti_shuffle('Hello World!!!')\n# 'Hello !!!Wdlor'\nanti_shuffle <- function(s) {\n # Split the string into words\n words <- strsplit(s, ' ')[[1]]\n \n # For each word, sort the characters in ascending order\n sorted_words <- sapply(words, function(x) paste(sort(strsplit(x, '')[[1]]), collapse=''))\n \n # Join the sorted words back into a string, with spaces between them\n return(paste(sorted_words, collapse=' '))\n}\n"], ["# You are given a 2 dimensional data, as a nested lists,\n# which is similar to matrix, however, unlike matrices,\n# each row may contain a different number of columns.\n# Given lst, and integer x, find integers x in the list,\n# and return list of lists, [(x1, y1), (x2, y2) ...] such that\n# each list is a coordinate - (row, columns), starting with 0.\n# Sort coordinates initially by rows in ascending order.\n# Also, sort coordinates of the row by columns in descending order.\n# Examples:\n# >>> get_row(list(c(1, 2, 3, 4, 5, 6), c(1, 2, 3, 4, 1, 6), c(1, 2, 3, 4, 5, 1)), 1)\n# list(c(0, 0), c(1, 4), c(1, 0), c(2, 5), c(2, 0))\n# >>> get_row(c(), 1)\n# c()\n# >>> get_row(list(c(), c(1), c(1, 2, 3)), 3)\n# list(c(2, 2))\nget_row <- function(lst, x) {\n coords <- list()\n for (i in 1:length(lst)) {\n row <- lst[[i]]\n for (j in 1:length(row)) {\n if (row[[j]] == x) {\n coords <- c(coords, list(c(i-1, j-1)))\n }\n }\n }\n coords <- coords[order(sapply(coords, function(x) x[[1]]))]\n for (i in 1:length(coords)) {\n coords[[i]] <- coords[[i]][order(coords[[i]], decreasing=TRUE)]\n }\n return(coords)\n}\n"], ["# Given a vector of non-negative integers, return a cor of the given vector after sorting,\n# you will sort the given vector in ascending order if the sum( first index value, last index value) is odd,\n# or sort it in descending order if the sum( first index value, last index value) is even.\n# Note:\n# * don't change the given vector.\n# Examples:\n# >>> sort_array(c())\n# c()\n# >>> sort_array(c(5))\n# c(5)\n# >>> sort_array(c(2, 4, 3, 0, 1, 5))\n# c(0, 1, 2, 3, 4, 5)\n# >>> sort_array(c(2, 4, 3, 0, 1, 5, 6))\n# c(6, 5, 4, 3, 2, 1, 0)\nsort_array <- function(array) {\n if (length(array) == 0) {\n return(array)\n }\n if ((array[1] + array[length(array)]) %% 2 == 1) {\n return(sort(array))\n } else {\n return(sort(array, decreasing = TRUE))\n }\n}\n"], ["# Create a function encrypt that takes a string as an argument and\n# returns a string encrypted with the alphabet being rotated. \n# The alphabet should be rotated in a manner such that the letters \n# shift down by two multiplied to two places.\n# For example:\n# >>> encrypt('hi')\n# 'lm'\n# >>> encrypt('asdfghjkl')\n# 'ewhjklnop'\n# >>> encrypt('gf')\n# 'kj'\n# >>> encrypt('et')\n# 'ix'\nencrypt <- function(s) {\n # Define the alphabet\n alphabet <- c(letters, letters)\n \n # Rotate the alphabet by two multiplied to two places\n rotated_alphabet <- alphabet[seq(2*2, length(alphabet), by=2*2)]\n \n # Encrypt the string\n encrypted_string <- sapply(strsplit(s, '')[[1]], function(x) {\n if (x %in% alphabet) {\n rotated_alphabet[which(alphabet == x)]\n } else {\n x\n }\n })\n \n # Return the encrypted string\n paste(encrypted_string, collapse='')\n}\n"], ["# For a given list of integers, return a list consisting of a sum and a product of all the integers in a list.\n# Empty sum should be equal to 0 and empty product should be equal to 1.\n# >>> sum_product(c())\n# c(0, 1)\n# >>> sum_product(c(1, 2, 3, 4))\n# c(10, 24)\nsum_product <- function(numbers) {\n if (length(numbers) == 0) {\n return(c(0, 1))\n } else {\n return(c(sum(numbers), prod(numbers)))\n }\n}\n"], ["# You are given a list of integers.\n# Write a function next_smallest() that returns the 2nd smallest element of the list.\n# Return NULL if there is no such element.\n# >>> next_smallest(c(1, 2, 3, 4, 5))\n# 2\n# >>> next_smallest(c(5, 1, 4, 3, 2))\n# 2\n# >>> next_smallest(c())\n# NULL\n# >>> next_smallest(c(1, 1))\n# NULL\nnext_smallest <- function(lst) {\n if (length(lst) < 2) {\n return(NULL)\n }\n sorted_lst <- sort(lst)\n if (sorted_lst[1] == sorted_lst[2]) {\n return(NULL)\n }\n return(sorted_lst[2])\n}\n"], ["# You'll be given a string of words, and your task is to count the number\n# of boredoms. A boredom is a sentence that starts with the word \"I\".\n# Sentences are delimited by '.', '?' or '!'.\n# For example:\n# >>> is_bored('Hello world')\n# 0\n# >>> is_bored('The sky is blue. The sun is shining. I love this weather')\n# 1\nis_bored <- function(S) {\n # Split the string into sentences\n sentences <- unlist(strsplit(S, '[.!?]'))\n \n # Count the number of sentences that start with \"I\"\n boredom_count <- sum(grepl('^I', sentences))\n \n return(boredom_count)\n}\n"], ["# Create a function that takes 3 numbers.\n# Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n# Returns false in any other cases.\n# Examples\n# >>> any_int(5, 2, 7)\n# TRUE\n# >>> any_int(3, 2, 2)\n# FALSE\n# >>> any_int(3, -2, 1)\n# TRUE\n# >>> any_int(3.6, -2.2, 2)\n# FALSE\nany_int <- function(x, y, z) {\n if (is.integer(x) && is.integer(y) && is.integer(z)) {\n if (x == y + z || y == x + z || z == x + y) {\n return(TRUE)\n } else {\n return(FALSE)\n }\n } else {\n return(FALSE)\n }\n}\n"], ["# Write a function that takes a message, and encodes in such a \n# way that it swaps case of all letters, replaces all vowels in \n# the message with the letter that appears 2 places ahead of that \n# vowel in the english alphabet. \n# Assume only letters. \n# Examples:\n# >>> encode('test')\n# 'TGST'\n# >>> encode('This is a message')\n# 'tHKS KS C MGSSCGG'\nencode <- function(message) {\n vowels <- c('a', 'e', 'i', 'o', 'u')\n consonants <- c('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z')\n message <- tolower(message)\n for (i in 1:nchar(message)) {\n if (message[i] %in% vowels) {\n message[i] <- consonants[match(message[i], vowels) + 2]\n }\n }\n return(toupper(message))\n}\n"], ["# You are given a list of integers.\n# You need to find the largest prime value and return the sum of its digits.\n# Examples:\n# >>> skjkasdkd(c(0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3))\n# 10\n# >>> skjkasdkd(c(1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1))\n# 25\n# >>> skjkasdkd(c(1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3))\n# 13\n# >>> skjkasdkd(c(0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6))\n# 11\n# >>> skjkasdkd(c(0, 81, 12, 3, 1, 21))\n# 3\n# >>> skjkasdkd(c(0, 8, 1, 2, 1, 7))\n# 7\nskjkasdkd <- function(lst) {\n # Find the largest prime value\n largest_prime <- max(lst[lst %in% primes(max(lst))])\n \n # Sum the digits of the largest prime value\n sum_digits <- sum(as.integer(strsplit(as.character(largest_prime), \"\")[[1]]))\n \n return(sum_digits)\n}\n"], ["# Given a named list, return TRUE if all keys are strings in lower \n# case or all keys are strings in upper case, else return FALSE.\n# The function should return FALSE is the given named list is empty.\n# Examples:\n# >>> check_dict_case(list('a' = 'apple', 'b' = 'banana'))\n# TRUE\n# >>> check_dict_case(list('a' = 'apple', 'A' = 'banana', 'B' = 'banana'))\n# FALSE\n# >>> check_dict_case(list('a' = 'apple', 8 = 'banana', 'a' = 'apple'))\n# FALSE\n# >>> check_dict_case(list('Name' = 'John', 'Age' = '36', 'City' = 'Houston'))\n# FALSE\n# >>> check_dict_case(list('STATE' = 'NC', 'ZIP' = '12345'))\n# TRUE\ncheck_dict_case <- function(dict) {\n if (length(dict) == 0) {\n return(FALSE)\n }\n all_lower <- all(grepl('^[a-z]+$', names(dict)))\n all_upper <- all(grepl('^[A-Z]+$', names(dict)))\n return(all_lower || all_upper)\n}\n"], ["# Implement a function that takes an non-negative integer and returns a vector of the first n\n# integers that are prime numbers and less than n.\n# for example:\n# >>> count_up_to(5)\n# c(2, 3)\n# >>> count_up_to(11)\n# c(2, 3, 5, 7)\n# >>> count_up_to(0)\n# c()\n# >>> count_up_to(20)\n# c(2, 3, 5, 7, 11, 13, 17, 19)\n# >>> count_up_to(1)\n# c()\n# >>> count_up_to(18)\n# c(2, 3, 5, 7, 11, 13, 17)\ncount_up_to <- function(n) {\n primes <- c()\n for (i in 2:n) {\n is_prime <- TRUE\n for (j in 2:(i-1)) {\n if (i %% j == 0) {\n is_prime <- FALSE\n break\n }\n }\n if (is_prime) {\n primes <- c(primes, i)\n }\n }\n return(primes)\n}\n"], ["# Complete the function that takes two integers and returns \n# the product of their unit digits.\n# Assume the input is always valid.\n# Examples:\n# >>> multiply(148, 412)\n# 16\n# >>> multiply(19, 28)\n# 72\n# >>> multiply(2020, 1851)\n# 0\n# >>> multiply(14, -15)\n# 20\nmultiply <- function(a, b) {\n return((a %% 10) * (b %% 10))\n}\n"], ["# Given a string s, count the number of uppercase vowels in even indices.\n# For example:\n# >>> count_upper('aBCdEf')\n# 1\n# >>> count_upper('abcdefg')\n# 0\n# >>> count_upper('dBBE')\n# 0\ncount_upper <- function(s) {\n upper_vowels <- c('A', 'E', 'I', 'O', 'U')\n count <- 0\n for (i in seq(1, nchar(s), 2)) {\n if (substr(s, i, i) %in% upper_vowels) {\n count <- count + 1\n }\n }\n return(count)\n}\n"], ["# Create a function that takes a value (string) representing a number\n# and returns the closest integer to it. If the number is equidistant\n# from two integers, round it away from zero.\n# Examples\n# >>> closest_integer('10')\n# 10\n# >>> closest_integer('15.3')\n# 15\n# Note:\n# Rounding away from zero means that if the given number is equidistant\n# from two integers, the one you should return is the one that is the\n# farthest from zero. For example closest_integer(\"14.5\") should\n# return 15 and closest_integer(\"-14.5\") should return -15.\nclosest_integer <- function(value) {\n # Convert the value to a numeric\n num_value <- as.numeric(value)\n \n # Calculate the difference between the value and its floor\n diff <- num_value - floor(num_value)\n \n # If the difference is greater than or equal to 0.5, round up\n if (diff >= 0.5) {\n return(ceiling(num_value))\n } else {\n # Otherwise, round down\n return(floor(num_value))\n }\n}\n"], ["# From a given list of integers, generate a list of rolling maximum element found until given moment\n# in the sequence.\n# >>> rolling_max(c(1, 2, 3, 2, 3, 4, 2))\n# c(1, 2, 3, 3, 3, 4, 4)\nrolling_max <- function(numbers) {\n max_values <- c()\n for (i in 1:length(numbers)) {\n max_values <- c(max_values, max(numbers[1:i]))\n }\n return(max_values)\n}\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rkt_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rkt_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..3b65f959f5723ca29ef00902da64c2ccf5dc9e9a --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rkt_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["#lang racket\n;; Check if in given list of numbers, are any two numbers closer to each other than\n;; given threshold.\n;; >>> (has_close_elements (list 1.0 2.0 3.0) 0.5)\n;; #f\n;; >>> (has_close_elements (list 1.0 2.8 3.0 4.0 5.0 2.0) 0.3)\n;; #t\n(define (has_close_elements numbers threshold)\n (let loop ((nums numbers))\n (cond\n [(empty? nums) #f]\n [(empty? (rest nums)) #f]\n [(<= (abs (- (first nums) (second nums))) threshold) #t]\n [else (loop (rest nums))])))\n"], ["#lang racket\n;; Given a positive integer n, you have to make a pile of n levels of stones.\n;; The first level has n stones.\n;; The number of stones in the next level is:\n;; - the next odd number if n is odd.\n;; - the next even number if n is even.\n;; Return the number of stones in each level in a list, where element at index\n;; i represents the number of stones in the level (i+1).\n;; Examples:\n;; >>> (make_a_pile 3)\n;; (list 3 5 7)\n(define (make_a_pile n)\n (let loop ((level 1) (stones n) (result '()))\n (if (> level n)\n (reverse result)\n (loop (+ level 1) (if (odd? stones) (+ stones 2) (+ stones 1)) (cons stones result)))))\n"], ["#lang racket\n;; You will be given a string of words separated by commas or spaces. Your task is\n;; to split the string into words and return a list of the words.\n;; For example:\n;; >>> (words_string \"Hi, my name is John\")\n;; (list \"Hi\" \"my\" \"name\" \"is\" \"John\")\n;; >>> (words_string \"One, two, three, four, five, six\")\n;; (list \"One\" \"two\" \"three\" \"four\" \"five\" \"six\")\n(define (words_string s)\n (regexp-split #rx\"[, ]+\" s))\n"], ["#lang racket\n;; This function takes two positive numbers x and y and returns the\n;; biggest even integer number that is in the range [x, y] inclusive. If \n;; there's no such number, then the function should return -1.\n;; For example:\n;; >>> (choose_num 12 15)\n;; 14\n;; >>> (choose_num 13 12)\n;; -1\n(define (choose_num x y)\n (let loop ((n y))\n (cond\n [(<= x n y) (if (even? n) n (loop (- n 1)))]\n [else -1])))\n"], ["#lang racket\n;; You are given two positive integers n and m, and your task is to compute the\n;; average of the integers from n through m (including n and m). \n;; Round the answer to the nearest integer and convert that to binary.\n;; If n is greater than m, return -1.\n;; Example:\n;; >>> (rounded_avg 1 5)\n;; \"0b11\"\n;; >>> (rounded_avg 7 5)\n;; -1\n;; >>> (rounded_avg 10 20)\n;; \"0b1111\"\n;; >>> (rounded_avg 20 33)\n;; \"0b11010\"\n(define (rounded_avg n m)\n (if (> n m)\n -1\n (number->string (round (/ (+ n m) 2)) 2)))\n"], ["#lang racket\n;; Given a list of positive integers x. return a sorted list of all \n;; elements that hasn't any even digit.\n;; Note: Returned list should be sorted in increasing order.\n;; For example:\n;; >>> (unique_digits (list 15 33 1422 1))\n;; (list 1 15 33)\n;; >>> (unique_digits (list 152 323 1422 10))\n;; (list )\n(define (unique_digits x)\n (filter (lambda (n)\n (not (ormap (lambda (d) (even? d))\n (map (lambda (c) (- (char->integer c) (char->integer #\\0)))\n (string->list (number->string n))))))\n (sort x <)))\n"], ["#lang racket\n;; Given a list of integers, sort the integers that are between 1 and 9 inclusive,\n;; reverse the resulting list, and then replace each digit by its corresponding name from\n;; \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n;; For example:\n;; >>> (by_length (list 2 1 1 4 5 8 2 3))\n;; (list \"Eight\" \"Five\" \"Four\" \"Three\" \"Two\" \"Two\" \"One\" \"One\")\n;; If the list is empty, return an empty list:\n;; >>> (by_length (list ))\n;; (list )\n;; If the list has any strange number ignore it:\n;; >>> (by_length (list 1 -1 55))\n;; (list \"One\")\n(define (by_length arr)\n (let ((numbers (filter (lambda (x) (and (>= x 1) (<= x 9))) arr)))\n (if (empty? numbers)\n '()\n (map (lambda (x)\n (cond ((= x 1) \"One\")\n ((= x 2) \"Two\")\n ((= x 3) \"Three\")\n ((= x 4) \"Four\")\n ((= x 5) \"Five\")\n ((= x 6) \"Six\")\n ((= x 7) \"Seven\")\n ((= x 8) \"Eight\")\n ((= x 9) \"Nine\")))\n (reverse (sort numbers <))))))\n"], ["#lang racket\n;; Implement the function f that takes n as a parameter,\n;; and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n;; or the sum of numbers from 1 to i otherwise.\n;; i starts from 1.\n;; the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n;; Example:\n;; >>> (f 5)\n;; (list 1 2 6 24 15)\n(define (f n)\n (define (factorial x)\n (if (= x 0)\n 1\n (* x (factorial (- x 1)))))\n (define (sum-to-n x)\n (/ (* x (+ x 1)) 2))\n (define (get-value i)\n (if (even? i)\n (factorial i)\n (sum-to-n i)))\n (map get-value (range 1 (+ n 1))))\n"], ["#lang racket\n;; Given a positive integer n, return a list that has the number of even and odd\n;; integer palindromes that fall within the range(1, n), inclusive.\n;; Example 1:\n;; >>> (even_odd_palindrome 3)\n;; (list 1 2)\n;; Explanation:\n;; Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n;; Example 2:\n;; >>> (even_odd_palindrome 12)\n;; (list 4 6)\n;; Explanation:\n;; Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n;; Note:\n;; 1. 1 <= n <= 10^3\n;; 2. returned list has the number of even and odd integer palindromes respectively.\n(define (even_odd_palindrome n)\n (define (palindrome? num)\n (let ((str (number->string num)))\n (equal? str (string-reverse str))))\n (define (count-palindromes n)\n (let loop ((i 1) (even 0) (odd 0))\n (if (> i n)\n (list even odd)\n (if (palindrome? i)\n (if (even? i)\n (loop (+ i 1) (+ even 1) odd)\n (loop (+ i 1) even (+ odd 1)))\n (loop (+ i 1) even odd)))))\n (count-palindromes n))\n"], ["#lang racket\n;; Write a function count_nums which takes a list of integers and returns\n;; the number of elements which has a sum of digits > 0.\n;; If a number is negative, then its first signed digit will be negative:\n;; e.g. -123 has signed digits -1, 2, and 3.\n;; >>> (count_nums (list ))\n;; 0\n;; >>> (count_nums (list -1 11 -11))\n;; 1\n;; >>> (count_nums (list 1 1 2))\n;; 3\n(define (count_nums arr)\n (define (sum_digits num)\n (if (< num 0)\n (sum_digits (- num))\n (let loop ((n num) (sum 0))\n (if (= n 0)\n sum\n (loop (quotient n 10) (+ sum (remainder n 10)))))))\n (length (filter (lambda (x) (> (sum_digits x) 0)) arr)))\n"], ["#lang racket\n;; We have a list 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n;; numbers in the list will be randomly ordered. Your task is to determine if\n;; it is possible to get a list sorted in non-decreasing order by performing \n;; the following operation on the given list:\n;; You are allowed to perform right shift operation any number of times.\n;; One right shift operation means shifting all elements of the list by one\n;; position in the right direction. The last element of the list will be moved to\n;; the starting position in the list i.e. 0th index. \n;; If it is possible to obtain the sorted list by performing the above operation\n;; then return #t else return #f.\n;; If the given list is empty then return #t.\n;; Note: The given list is guaranteed to have unique elements.\n;; For Example:\n;; >>> (move_one_ball (list 3 4 5 1 2))\n;; #t\n;; Explanation: By performin 2 right shift operations, non-decreasing order can\n;; be achieved for the given list.\n;; >>> (move_one_ball (list 3 5 4 1 2))\n;; #f\n;; Explanation:It is not possible to get non-decreasing order for the given\n;; list by performing any number of right shift operations.\n(define (move_one_ball arr)\n (if (null? arr)\n #t\n (let ((sorted-arr (sort arr <)))\n (or (equal? arr sorted-arr)\n (equal? (cdr arr) (append (list (car arr)) (cdr sorted-arr)))))))\n"], ["#lang racket\n;; Find the shortest palindrome that begins with a supplied string.\n;; Algorithm idea is simple:\n;; - Find the longest postfix of supplied string that is a palindrome.\n;; - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n;; >>> (make_palindrome \"\")\n;; \"\"\n;; >>> (make_palindrome \"cat\")\n;; \"catac\"\n;; >>> (make_palindrome \"cata\")\n;; \"catac\"\n(define (make_palindrome string)\n (let loop ((i 0))\n (if (>= i (string-length string))\n string\n (let ((prefix (substring string 0 i))\n (suffix (substring string i)))\n (if (string=? prefix (string-reverse suffix))\n (string-append string (string-reverse prefix))\n (loop (+ i 1)))))))\n"], ["#lang racket\n;; In this problem, you will implement a function that takes two lists of numbers,\n;; and determines whether it is possible to perform an exchange of elements\n;; between them to make lst1 a list of only even numbers.\n;; There is no limit on the number of exchanged elements between lst1 and lst2.\n;; If it is possible to exchange elements between the lst1 and lst2 to make\n;; all the elements of lst1 to be even, return \"YES\".\n;; Otherwise, return \"NO\".\n;; For example:\n;; >>> (exchange (list 1 2 3 4) (list 1 2 3 4))\n;; \"YES\"\n;; >>> (exchange (list 1 2 3 4) (list 1 5 3 4))\n;; \"NO\"\n;; It is assumed that the input lists will be non-empty.\n(define (exchange lst1 lst2)\n (let ((sum1 (apply + lst1))\n (sum2 (apply + lst2)))\n (if (even? sum1)\n \"YES\"\n (if (even? sum2)\n \"YES\"\n \"NO\"))))\n"], ["#lang racket\n;; Given a string representing a space separated lowercase letters, return a hash\n;; of the letter with the most repetition and containing the corresponding count.\n;; If several letters have the same occurrence, return all of them.\n;; Example:\n;; >>> (histogram \"a b c\")\n;; #hash((\"a\" . 1) (\"b\" . 1) (\"c\" . 1))\n;; >>> (histogram \"a b b a\")\n;; #hash((\"a\" . 2) (\"b\" . 2))\n;; >>> (histogram \"a b c a b\")\n;; #hash((\"a\" . 2) (\"b\" . 2))\n;; >>> (histogram \"b b b b a\")\n;; #hash((\"b\" . 4))\n;; >>> (histogram \"\")\n;; #hash()\n(define (histogram test)\n (define letter-counts (make-hash))\n (define words (string-split test))\n (for ([word words])\n (for ([letter (string->list word)])\n (hash-update letter-counts letter add1 0)))\n (define max-count (apply max (hash-values letter-counts)))\n (define result (make-hash))\n (for ([letter (hash-keys letter-counts)])\n (when (= (hash-ref letter-counts letter) max-count)\n (hash-set result letter max-count)))\n result)\n"], ["#lang racket\n;; Task\n;; We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n;; then check if the result string is palindrome.\n;; A string is called palindrome if it reads the same backward as forward.\n;; You should return a list containing the result string and #t/#f for the check.\n;; Example\n;; >>> (reverse_delete \"abcde\" \"ae\")\n;; (list \"bcd\" #f)\n;; >>> (reverse_delete \"abcdef\" \"b\")\n;; (list \"acdef\" #f)\n;; >>> (reverse_delete \"abcdedcba\" \"ab\")\n;; (list \"cdedc\" #t)\n(define (reverse_delete s c)\n (let* ((s-filtered (filter (lambda (ch) (not (member ch (string->list c)))) (string->list s)))\n (s-reversed (list->string (reverse s-filtered)))\n (is-palindrome? (equal? s-filtered s-reversed)))\n (list s-reversed is-palindrome?)))\n"], ["#lang racket\n;; Given a list of strings, where each string consists of only digits, return a list.\n;; Each element i of the output should be \"the number of odd elements in the\n;; string i of the input.\" where all the i's should be replaced by the number\n;; of odd digits in the i'th string of the input.\n;; >>> (odd_count (list \"1234567\"))\n;; (list \"the number of odd elements 4n the str4ng 4 of the 4nput.\")\n;; >>> (odd_count (list \"3\" \"11111111\"))\n;; (list \"the number of odd elements 1n the str1ng 1 of the 1nput.\" \"the number of odd elements 8n the str8ng 8 of the 8nput.\")\n(define (odd_count lst)\n (map (lambda (str)\n (let ((num-odds (length (filter odd? (map string->number (string->list str))))))\n (string-append \"the number of odd elements \" (number->string num-odds) \"n the str\" (number->string (string-length str)) \"ng \" (number->string (string-length str)) \" of the \" (number->string (string-length str)) \"nput.\")))\n lst))\n"], ["#lang racket\n;; Given a list of integers nums, find the minimum sum of any non-empty sub-list\n;; of nums.\n;; Example\n;; >>> (minSubArraySum (list 2 3 4 1 2 4))\n;; 1\n;; >>> (minSubArraySum (list -1 -2 -3))\n;; -6\n(define (minSubArraySum nums)\n (let loop ((nums nums) (min-sum (car nums)) (curr-sum 0))\n (if (null? nums)\n min-sum\n (let ((num (car nums)))\n (loop (cdr nums)\n (min min-sum (+ curr-sum num))\n (min (+ curr-sum num) num))))))\n"], ["#lang racket\n;; You are given a rectangular grid of wells. Each row represents a single well,\n;; and each 1 in a row represents a single unit of water.\n;; Each well has a corresponding bucket that can be used to extract water from it, \n;; and all buckets have the same capacity.\n;; Your task is to use the buckets to empty the wells.\n;; Output the number of times you need to lower the buckets.\n;; Example 1:\n;; >>> (max_fill (list (list 0 0 1 0) (list 0 1 0 0) (list 1 1 1 1)) 1)\n;; 6\n;; Example 2:\n;; >>> (max_fill (list (list 0 0 1 1) (list 0 0 0 0) (list 1 1 1 1) (list 0 1 1 1)) 2)\n;; 5\n;; Example 3:\n;; >>> (max_fill (list (list 0 0 0) (list 0 0 0)) 5)\n;; 0\n;; Constraints:\n;; * all wells have the same length\n;; * 1 <= grid.length <= 10^2\n;; * 1 <= grid[:,1].length <= 10^2\n;; * grid[i][j] -> 0 | 1\n;; * 1 <= capacity <= 10\n(define (max_fill grid capacity)\n (let* ((rows (length grid))\n (cols (length (first grid)))\n (total-water (apply + (map (lambda (row) (apply + row)) grid)))\n (buckets-needed (ceiling (/ total-water capacity))))\n (if (> buckets-needed rows)\n (- buckets-needed rows)\n 0)))\n"], ["#lang racket\n;; In this Kata, you have to sort a list of non-negative integers according to\n;; number of ones in their binary representation in ascending order.\n;; For similar number of ones, sort based on decimal value.\n;; It must be implemented like this:\n;; >>> (sort_array (list 1 5 2 3 4))\n;; (list 1 2 3 4 5)\n;; >>> (sort_array (list -2 -3 -4 -5 -6))\n;; (list -6 -5 -4 -3 -2)\n;; >>> (sort_array (list 1 0 2 3 4))\n;; (list 0 1 2 3 4)\n(define (sort_array arr)\n (sort arr\n (lambda (x y)\n (cond\n [(< (count-ones x) (count-ones y)) #t]\n [(> (count-ones x) (count-ones y)) #f]\n [else (< x y)]))))\n"], ["#lang racket\n;; Given a string s and a natural number n, you have been tasked to implement \n;; a function that returns a list of all words from string s that contain exactly \n;; n consonants, in order these words appear in the string s.\n;; If the string s is empty then the function should return an empty list.\n;; Note: you may assume the input string contains only letters and spaces.\n;; Examples:\n;; >>> (select_words \"Mary had a little lamb\" 4)\n;; (list \"little\")\n;; >>> (select_words \"Mary had a little lamb\" 3)\n;; (list \"Mary\" \"lamb\")\n;; >>> (select_words \"simple white space\" 2)\n;; (list )\n;; >>> (select_words \"Hello world\" 4)\n;; (list \"world\")\n;; >>> (select_words \"Uncle sam\" 3)\n;; (list \"Uncle\")\n(define (select_words s n)\n (let ((words (regexp-split #rx\" \" s)))\n (filter (lambda (word)\n (= n (length (filter (lambda (c)\n (not (member c '(#\\a #\\e #\\i #\\o #\\u)))\n (string->list word))))))\n words)))\n"], ["#lang racket\n;; You are given a word. Your task is to find the closest vowel that stands between \n;; two consonants from the right side of the word (case sensitive).\n;; Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n;; find any vowel met the above condition. \n;; You may assume that the given string contains English letter only.\n;; Example:\n;; >>> (get_closest_vowel \"yogurt\")\n;; \"u\"\n;; >>> (get_closest_vowel \"FULL\")\n;; \"U\"\n;; >>> (get_closest_vowel \"quick\")\n;; \"\"\n;; >>> (get_closest_vowel \"ab\")\n;; \"\"\n(define (get_closest_vowel word)\n (let loop ((i (- (string-length word) 2)) (vowel #f))\n (if (< i 1)\n (if vowel (string vowel) \"\")\n (if (and (not (member (string-ref word i) '(#\\a #\\e #\\i #\\o #\\u)))\n (member (string-ref word (+ i 1)) '(#\\a #\\e #\\i #\\o #\\u))\n (member (string-ref word (+ i 2)) '(#\\a #\\e #\\i #\\o #\\u)))\n (loop (- i 1) (string-ref word (+ i 1)))\n (loop (- i 1) vowel)))))\n"], ["#lang racket\n;; You are given a list of two strings, both strings consist of open\n;; parentheses '(' or close parentheses ')' only.\n;; Your job is to check if it is possible to concatenate the two strings in\n;; some order, that the resulting string will be good.\n;; A string S is considered to be good if and only if all parentheses in S\n;; are balanced. For example: the string '(())()' is good, while the string\n;; '())' is not.\n;; Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n;; Examples:\n;; >>> (match_parens (list \"()(\" \")\"))\n;; \"Yes\"\n;; >>> (match_parens (list \")\" \")\"))\n;; \"No\"\n(define (match_parens lst)\n (let ((s1 (car lst))\n (s2 (cadr lst)))\n (if (= (string-count s1 #\\() (string-count s1 #\\)))\n (if (= (string-count s2 #\\() (string-count s2 #\\)))\n \"Yes\"\n \"No\")\n \"No\")))\n"], ["#lang racket\n;; Input are two strings a and b consisting only of 1s and 0s.\n;; Perform binary XOR on these inputs and return result also as a string.\n;; >>> (string_xor \"010\" \"110\")\n;; \"100\"\n(define (string_xor a b)\n (let ((result \"\"))\n (for ((i (in-range (string-length a))))\n (set! result (string-append result (if (equal? (string-ref a i) (string-ref b i)) \"0\" \"1\"))))\n result))\n"], ["#lang racket\n;; Given a list arr of integers and a positive integer k, return a sorted list \n;; of length k with the maximum k numbers in arr.\n;; Example 1:\n;; >>> (maximum (list -3 -4 5) 3)\n;; (list -4 -3 5)\n;; Example 2:\n;; >>> (maximum (list 4 -4 4) 2)\n;; (list 4 4)\n;; Example 3:\n;; >>> (maximum (list -3 2 1 2 -1 -2 1) 1)\n;; (list 2)\n;; Note:\n;; 1. The length of the list will be in the range of [1, 1000].\n;; 2. The elements in the list will be in the range of [-1000, 1000].\n;; 3. 0 <= k <= len(arr)\n(define (maximum arr k)\n (sort arr >)\n (take arr k))\n"], ["#lang racket\n;; Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n;; Examples\n;; >>> (solution (list 5 8 7 1))\n;; 12\n;; >>> (solution (list 3 3 3 3 3))\n;; 9\n;; >>> (solution (list 30 13 24 321))\n;; 0\n(define (solution lst)\n (let loop ((lst lst) (sum 0) (index 0))\n (cond\n ((null? lst) sum)\n ((and (odd? (car lst)) (even? index))\n (loop (cdr lst) (+ sum (car lst)) (+ index 1)))\n (else\n (loop (cdr lst) sum (+ index 1))))))\n"], ["#lang racket\n;; Given a non-empty list of integers arr and an integer k, return\n;; the sum of the elements with at most two digits from the first k elements of arr.\n;; Example:\n;; >>> (add_elements (list 111 21 3 4000 5 6 7 8 9) 4)\n;; 24\n;; Constraints:\n;; 1. 1 <= len(arr) <= 100\n;; 2. 1 <= k <= len(arr)\n(define (add_elements arr k)\n (let loop ([i 0] [sum 0])\n (if (= i k)\n sum\n (let ([num (list-ref arr i)])\n (if (< num 100)\n (loop (+ i 1) (+ sum num))\n (loop (+ i 1) sum))))))\n"], ["#lang racket\n;; Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n;; The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n;; as follows: start with any positive integer n. Then each term is obtained from the \n;; previous term as follows: if the previous term is even, the next term is one half of \n;; the previous term. If the previous term is odd, the next term is 3 times the previous\n;; term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n;; Note: \n;; 1. Collatz(1) is [1].\n;; 2. returned list sorted in increasing order.\n;; For example:\n;; get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n;; >>> (get_odd_collatz 5)\n;; (list 1 5)\n(define (get_odd_collatz n)\n (let loop ((num n) (lst '()))\n (cond\n ((= num 1) (sort lst <))\n ((odd? num) (loop (+ 1 (* 3 num)) (cons num lst)))\n (else (loop (/ num 2) lst)))))\n"], ["#lang racket\n;; You have to write a function which validates a given date string and\n;; returns #t if the date is valid otherwise #f.\n;; The date is valid if all of the following rules are satisfied:\n;; 1. The date string is not empty.\n;; 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n;; 3. The months should not be less than 1 or higher than 12.\n;; 4. The date should be in the format: mm-dd-yyyy\n;; >>> (valid_date \"03-11-2000\")\n;; #t\n;; >>> (valid_date \"15-01-2012\")\n;; #f\n;; >>> (valid_date \"04-0-2040\")\n;; #f\n;; >>> (valid_date \"06-04-2020\")\n;; #t\n;; >>> (valid_date \"06/04/2020\")\n;; #f\n(define (valid_date date)\n (and (not (string-empty? date))\n (regexp-match #rx\"^(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-[0-9]{4}$\" date)\n (let ([month (string->number (substring date 0 2))]\n [day (string->number (substring date 3 5))]\n [year (string->number (substring date 6 10))])\n (and (<= 1 month 12)\n (cond\n [(member month '(1 3 5 7 8 10 12)) (<= 1 day 31)]\n [(member month '(4 6 9 11)) (<= 1 day 30)]\n [(= month 2) (if (leap-year? year)\n (<= 1 day 29)\n (<= 1 day 28))]\n [else #f])))))\n"], ["#lang racket\n;; Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n;; should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n;; alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n;; Examples\n;; >>> (split_words \"Hello world!\")\n;; (list \"Hello\" \"world!\")\n;; >>> (split_words \"Hello,world!\")\n;; (list \"Hello\" \"world!\")\n;; >>> (split_words \"abcdef\")\n;; 3\n(define (split_words txt)\n (cond\n [(regexp-match #rx\" \" txt) (string-split txt)]\n [(regexp-match #rx\",\" txt) (string-split txt #\\,)]\n [else\n (let loop ([i 0] [count 0])\n (if (= i (string-length txt))\n count\n (loop (+ i 1) (if (odd? (- (char->integer (string-ref txt i)) (char->integer #\\a)) 2))\n (+ count 1)\n count)))]))\n"], ["#lang racket\n;; Given a list of numbers, return whether or not they are sorted\n;; in ascending order. If list has more than 1 duplicate of the same\n;; number, return #f. Assume no negative numbers and only integers.\n;; Examples\n;; >>> (is_sorted (list 5))\n;; #t\n;; >>> (is_sorted (list 1 2 3 4 5))\n;; #t\n;; >>> (is_sorted (list 1 3 2 4 5))\n;; #f\n;; >>> (is_sorted (list 1 2 3 4 5 6))\n;; #t\n;; >>> (is_sorted (list 1 2 3 4 5 6 7))\n;; #t\n;; >>> (is_sorted (list 1 3 2 4 5 6 7))\n;; #f\n;; >>> (is_sorted (list 1 2 2 3 3 4))\n;; #t\n;; >>> (is_sorted (list 1 2 2 2 3 4))\n;; #f\n(define (is_sorted lst)\n (cond\n [(null? lst) #t]\n [(null? (cdr lst)) #t]\n [(> (car lst) (cadr lst)) #f]\n [else (is_sorted (cdr lst))]))\n"], ["#lang racket\n;; You are given two intervals,\n;; where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n;; The given intervals are closed which means that the interval (start, end)\n;; includes both start and end.\n;; For each given interval, it is assumed that its start is less or equal its end.\n;; Your task is to determine whether the length of intersection of these two \n;; intervals is a prime number.\n;; Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n;; which its length is 1, which not a prime number.\n;; If the length of the intersection is a prime number, return \"YES\",\n;; otherwise, return \"NO\".\n;; If the two intervals don't intersect, return \"NO\".\n;; [input/output] samples:\n;; >>> (intersection (list 1 2) (list 2 3))\n;; \"NO\"\n;; >>> (intersection (list -1 1) (list 0 4))\n;; \"NO\"\n;; >>> (intersection (list -3 -1) (list -5 5))\n;; \"YES\"\n(define (intersection interval1 interval2)\n (let ((start1 (car interval1))\n (end1 (cadr interval1))\n (start2 (car interval2))\n (end2 (cadr interval2)))\n (if (or (< end1 start2) (< end2 start1))\n \"NO\"\n (let ((intersection-start (max start1 start2))\n (intersection-end (min end1 end2)))\n (if (<= intersection-start intersection-end)\n (let ((intersection-length (- intersection-end intersection-start)))\n (if (prime? intersection-length)\n \"YES\"\n \"NO\"))\n \"NO\")))))\n"], ["#lang racket\n;; You are given a list arr of integers and you need to return\n;; sum of magnitudes of integers multiplied by product of all signs\n;; of each number in the list, represented by 1, -1 or 0.\n;; Note: return #f for empty arr.\n;; Example:\n;; >>> (prod_signs (list 1 2 2 -4))\n;; 9\n;; >>> (prod_signs (list 0 1))\n;; 0\n;; >>> (prod_signs (list ))\n;; #f\n(define (prod_signs arr)\n (if (empty? arr)\n #f\n (let ((signs (map (lambda (x) (cond ((> x 0) 1)\n ((< x 0) -1)\n (else 0)))\n arr)))\n (* (apply + (map abs arr))\n (apply * signs)))))\n"], ["#lang racket\n;; Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n;; each cell of the grid contains a value. Every integer in the range [1, N * N]\n;; inclusive appears exactly once on the cells of the grid.\n;; You have to find the minimum path of length k in the grid. You can start\n;; from any cell, and in each step you can move to any of the neighbor cells,\n;; in other words, you can go to cells which share an edge with you current\n;; cell.\n;; Please note that a path of length k means visiting exactly k cells (not\n;; necessarily distinct).\n;; You CANNOT go off the grid.\n;; A path A (of length k) is considered less than a path B (of length k) if\n;; after making the ordered lists of the values on the cells that A and B go\n;; through (let's call them lst_A and lst_B), lst_A is lexicographically less\n;; than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n;; such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n;; lst_A[j] = lst_B[j].\n;; It is guaranteed that the answer is unique.\n;; Return an ordered list of the values on the cells that the minimum path go through.\n;; Examples: \n;; >>> (minPath (list (list 1 2 3) (list 4 5 6) (list 7 8 9)) 3)\n;; (list 1 2 1)\n;; >>> (minPath (list (list 5 9 3) (list 4 1 6) (list 7 8 2)) 1)\n;; (list 1)\n(define (minPath grid k)\n (let* ((n (length grid))\n (visited (make-vector (* n n) #f))\n (path (make-vector k #f))\n (min-path (make-vector k #f)))\n (define (dfs i j k)\n (when (and (>= i 0) (< i n) (>= j 0) (< j n) (not (vector-ref visited (+ (* i n) j))))\n (vector-set visited (+ (* i n) j) #t)\n (vector-set path k (vector-ref (list-ref grid i) j))\n (when (= k (- k 1))\n (if (or (not (vector-ref min-path 0)) (< (vector-ref path 0) (vector-ref min-path 0)))\n (begin\n (vector-copy path 0 min-path 0 k)\n (vector-copy path 0 min-path 0 k))))\n (for ([dx (in-list '(-1 0 1))] [dy (in-list '(-1 0 1))])\n (when (and (not (= dx 0)) (not (= dy 0)))\n (dfs (+ i dx) (+ j dy) (- k 1))))\n (vector-set visited (+ (* i n) j) #f)))\n (for ([i (in-range n)] [j (in-range n)])\n (dfs i j (- k 1)))\n (vector->list min-path)))\n"], ["#lang racket\n;; Out of list of strings, return the longest one. Return the first one in case of multiple\n;; strings of the same length. Return #f in case the input list is empty.\n;; >>> (longest (list ))\n;; #f\n;; >>> (longest (list \"a\" \"b\" \"c\"))\n;; \"a\"\n;; >>> (longest (list \"a\" \"bb\" \"ccc\"))\n;; \"ccc\"\n(define (longest strings)\n (cond\n [(empty? strings) #f]\n [else (foldr (lambda (x y) (if (> (string-length x) (string-length y)) x y)) (car strings) (cdr strings))]))\n"], ["#lang racket\n;; Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n;; the last couple centuries. However, what people don't know is Tribonacci sequence.\n;; Tribonacci sequence is defined by the recurrence:\n;; tri(1) = 3\n;; tri(n) = 1 + n / 2, if n is even.\n;; tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n;; For example:\n;; tri(2) = 1 + (2 / 2) = 2\n;; tri(4) = 3\n;; tri(3) = tri(2) + tri(1) + tri(4)\n;; = 2 + 3 + 3 = 8 \n;; You are given a non-negative integer number n, you have to a return a list of the \n;; first n + 1 numbers of the Tribonacci sequence.\n;; Examples:\n;; >>> (tri 3)\n;; (list 1 3 2 8)\n(define (tri n)\n (define (tri-helper n)\n (cond\n ((= n 1) 3)\n ((even? n) (+ 1 (/ n 2)))\n (else (+ (tri-helper (- n 1)) (tri-helper (- n 2)) (tri-helper (+ n 1))))))\n (map tri-helper (range (+ n 1))))\n"], ["#lang racket\n;; Given a positive integer n, return the product of the odd digits.\n;; Return 0 if all digits are even.\n;; For example:\n;; >>> (digits 1)\n;; 1\n;; >>> (digits 4)\n;; 0\n;; >>> (digits 235)\n;; 15\n(define (digits n)\n (let loop ((n n) (product 1))\n (if (= n 0)\n (if (= product 1) 0 product)\n (let ((digit (remainder n 10)))\n (loop (quotient n 10)\n (if (odd? digit) (* product digit) product))))))\n"], ["#lang racket\n;; Create a function that takes a string as input which contains only square brackets.\n;; The function should return #t if and only if there is a valid subsequence of brackets \n;; where at least one bracket in the subsequence is nested.\n;; >>> (is_nested \"[[]]\")\n;; #t\n;; >>> (is_nested \"[]]]]]]][[[[[]\")\n;; #f\n;; >>> (is_nested \"[][]\")\n;; #f\n;; >>> (is_nested \"[]\")\n;; #f\n;; >>> (is_nested \"[[][]]\")\n;; #t\n;; >>> (is_nested \"[[]][[\")\n;; #t\n(define (is_nested string)\n (let loop ((stack '()) (chars (string->list string)))\n (cond\n ((null? chars) #f)\n ((char=? (car chars) #\\[) (loop (cons #\\[ stack) (cdr chars)))\n ((char=? (car chars) #\\])\n (if (null? stack)\n #f\n (loop (cdr stack) (cdr chars))))\n (else (loop stack (cdr chars))))))\n"], ["#lang racket\n;; You are given a list of numbers.\n;; You need to return the sum of squared numbers in the given list,\n;; round each element in the list to the upper int(Ceiling) first.\n;; Examples:\n;; >>> (lst (list 1.0 2.0 3.0))\n;; 14\n;; >>> (lst (list 1.0 4.0 9.0))\n;; 98\n;; >>> (lst (list 1.0 3.0 5.0 7.0))\n;; 84\n;; >>> (lst (list 1.4 4.2 0.0))\n;; 29\n;; >>> (lst (list -2.4 1.0 1.0))\n;; 6\n(define (sum_squares lst)\n (apply + (map (lambda (x) (expt (ceiling x) 2)) lst)))\n"], ["#lang racket\n;; Create a function that returns #t if the last character\n;; of a given string is an alphabetical character and is not\n;; a part of a word, and #f otherwise.\n;; Note: \"word\" is a group of characters separated by space.\n;; Examples:\n;; >>> (check_if_last_char_is_a_letter \"apple pie\")\n;; #f\n;; >>> (check_if_last_char_is_a_letter \"apple pi e\")\n;; #t\n;; >>> (check_if_last_char_is_a_letter \"apple pi e \")\n;; #f\n;; >>> (check_if_last_char_is_a_letter \"\")\n;; #f\n(define (check_if_last_char_is_a_letter txt)\n (let ((last-char (string-ref txt (- (string-length txt) 1))))\n (and (char-alphabetic? last-char)\n (or (= (string-length txt) 0)\n (char-whitespace? (string-ref txt (- (string-length txt) 2)))))))\n"], ["#lang racket\n;; Create a function which returns the largest index of an element which\n;; is not greater than or equal to the element immediately preceding it. If\n;; no such element exists then return -1. The given list will not contain\n;; duplicate values.\n;; Examples:\n;; >>> (can_arrange (list 1 2 4 3 5))\n;; 3\n;; >>> (can_arrange (list 1 2 3))\n;; -1\n(define (can_arrange arr)\n (let loop ((i 1) (max_index -1))\n (if (= i (length arr))\n max_index\n (if (< (list-ref arr i) (list-ref arr (- i 1)))\n (loop (+ i 1) i)\n (loop (+ i 1) max_index)))))\n"], ["#lang racket\n;; Create a function that returns a list (a, b), where 'a' is\n;; the largest of negative integers, and 'b' is the smallest\n;; of positive integers in a list.\n;; If there is no negative or positive integers, return them as #f.\n;; Examples:\n;; >>> (largest_smallest_integers (list 2 4 1 3 5 7))\n;; (list #f 1)\n;; >>> (largest_smallest_integers (list ))\n;; (list #f #f)\n;; >>> (largest_smallest_integers (list 0))\n;; (list #f #f)\n(define (largest_smallest_integers lst)\n (let ((negatives (filter negative? lst))\n (positives (filter positive? lst)))\n (if (and (empty? negatives) (empty? positives))\n (list #f #f)\n (list (if (empty? negatives) #f (apply max negatives))\n (if (empty? positives) #f (apply min positives))))))\n"], ["#lang racket\n;; Create a function that takes integers, floats, or strings representing\n;; real numbers, and returns the larger variable in its given variable type.\n;; Return #f if the values are equal.\n;; Note: If a real number is represented as a string, the floating point might be . or ,\n;; >>> (compare_one 1 2.5)\n;; 2.5\n;; >>> (compare_one 1 \"2,3\")\n;; \"2,3\"\n;; >>> (compare_one \"5,1\" \"6\")\n;; \"6\"\n;; >>> (compare_one \"1\" 1)\n;; #f\n(define (compare_one a b)\n (cond\n [(and (number? a) (number? b)) (if (> a b) a (if (< a b) b #f))]\n [(and (string? a) (string? b)) (if (> (string->number a) (string->number b)) a (if (< (string->number a) (string->number b)) b #f))]\n [else #f]))\n"], ["#lang racket\n;; Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n;; Example\n;; >>> (is_equal_to_sum_even 4)\n;; #f\n;; >>> (is_equal_to_sum_even 6)\n;; #f\n;; >>> (is_equal_to_sum_even 8)\n;; #t\n(define (is_equal_to_sum_even n)\n (if (and (even? n) (>= n 8))\n #t\n #f))\n"], ["#lang racket\n;; The Brazilian factorial is defined as:\n;; brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n;; where n > 0\n;; For example:\n;; >>> (special_factorial 4)\n;; 288\n;; The function will receive an integer as input and should return the special\n;; factorial of this integer.\n(define (special_factorial n)\n (if (= n 1)\n 1\n (* n (special_factorial (- n 1)))))\n"], ["#lang racket\n;; Return a greatest common divisor of two integers a and b\n;; >>> (greatest_common_divisor 3 5)\n;; 1\n;; >>> (greatest_common_divisor 25 15)\n;; 5\n(define (greatest_common_divisor a b)\n (cond\n [(= b 0) a]\n [else (greatest_common_divisor b (modulo a b))]))\n"], ["#lang racket\n;; Given a string text, replace all spaces in it with underscores, \n;; and if a string has more than 2 consecutive spaces, \n;; then replace all consecutive spaces with - \n;; >>> (fix_spaces \" Example\")\n;; \"Example\"\n;; >>> (fix_spaces \" Example 1\")\n;; \"Example_1\"\n;; >>> (fix_spaces \" Example 2\")\n;; \"_Example_2\"\n;; >>> (fix_spaces \" Example 3\")\n;; \"_Example-3\"\n(define (fix_spaces text)\n (let ((new-text (regexp-replace* #rx\" +\" text \"-\")))\n (regexp-replace* #rx\" \" new-text \"_\")))\n"], ["#lang racket\n;; Create a function which takes a string representing a file's name, and returns\n;; 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n;; A file's name is considered to be valid if and only if all the following conditions \n;; are met:\n;; - There should not be more than three digits ('0'-'9') in the file's name.\n;; - The file's name contains exactly one dot '.'\n;; - The substring before the dot should not be empty, and it starts with a letter from \n;; the latin alphapet ('a'-'z' and 'A'-'Z').\n;; - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n;; Examples:\n;; >>> (file_name_check \"example.txt\")\n;; \"Yes\"\n;; >>> (file_name_check \"1example.dll\")\n;; \"No\"\n(define (file_name_check file_name)\n (let* ((dot_index (string-index file_name #\\.))\n (before_dot (substring file_name 0 dot_index))\n (after_dot (substring file_name (+ dot_index 1)))\n (digit_count (string-count file_name char-numeric?))\n (valid_extensions '(\"txt\" \"exe\" \"dll\")))\n (if (and (<= digit_count 3)\n (string-index before_dot char-alphabetic?)\n (string-index after_dot char-alphabetic?)\n (member after_dot valid_extensions))\n \"Yes\"\n \"No\")))\n"], ["#lang racket\n;; \"\n;; This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n;; multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n;; change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n;; Examples:\n;; >>> lst\n;; (list 1 2 3)\n;; >>> lst\n;; (list )\n;; >>> lst\n;; (list -1 -5 2 -1 -5)\n(define (sum_squares lst)\n (define (helper lst index sum)\n (cond\n [(empty? lst) sum]\n [(and (= (modulo index 3) 0) (not (= (modulo index 4) 0))) (helper (rest lst) (+ index 1) (+ sum (* (first lst) (first lst))))]\n [(= (modulo index 4) 0) (helper (rest lst) (+ index 1) (+ sum (* (first lst) (first lst) (first lst))))]\n [else (helper (rest lst) (+ index 1) (+ sum (first lst)))]))\n (helper lst 0 0))\n"], ["#lang racket\n;; You are given a string representing a sentence,\n;; the sentence contains some words separated by a space,\n;; and you have to return a string that contains the words from the original sentence,\n;; whose lengths are prime numbers,\n;; the order of the words in the new string should be the same as the original one.\n;; Example 1:\n;; >>> (words_in_sentence \"This is a test\")\n;; \"is\"\n;; Example 2:\n;; >>> (words_in_sentence \"lets go for swimming\")\n;; \"go for\"\n;; Constraints:\n;; * 1 <= len(sentence) <= 100\n;; * sentence contains only letters\n(define (words_in_sentence sentence)\n (let ((words (string-split sentence)))\n (string-join (filter prime-length? words) \" \")))\n"], ["#lang racket\n;; Your task is to implement a function that will simplify the expression\n;; x * n. The function returns #t if x * n evaluates to a whole number and #f\n;; otherwise. Both x and n, are string representation of a fraction, and have the following format,\n;; / where both numerator and denominator are positive whole numbers.\n;; You can assume that x, and n are valid fractions, and do not have zero as denominator.\n;; >>> (simplify \"1/5\" \"5/1\")\n;; #t\n;; >>> (simplify \"1/6\" \"2/1\")\n;; #f\n;; >>> (simplify \"7/10\" \"10/2\")\n;; #f\n(define (simplify x n)\n (let ((x-num (string->number (car (string-split x \"/\"))))\n (x-den (string->number (cadr (string-split x \"/\"))))\n (n-num (string->number (car (string-split n \"/\"))))\n (n-den (string->number (cadr (string-split n \"/\")))))\n (let ((product (* x-num n-num)))\n (if (integer? (/ product (* x-den n-den)))\n #t\n #f))))\n"], ["#lang racket\n;; Write a function which sorts the given list of integers\n;; in ascending order according to the sum of their digits.\n;; Note: if there are several items with similar sum of their digits,\n;; order them based on their index in original list.\n;; For example:\n;; >>> (order_by_points (list 1 11 -1 -11 -12))\n;; (list -1 -11 1 -12 11)\n;; >>> (order_by_points (list ))\n;; (list )\n(define (order_by_points nums)\n (sort nums\n (lambda (x y)\n (let ((x-sum (apply + (map (lambda (c) (- (char->integer c) 48))\n (string->list (number->string x)))))\n (y-sum (apply + (map (lambda (c) (- (char->integer c) 48))\n (string->list (number->string y))))))\n (if (= x-sum y-sum)\n (< (index-of nums x) (index-of nums y))\n (< x-sum y-sum))))))\n"], ["#lang racket\n;; Write a function that takes a list of numbers as input and returns \n;; the number of elements in the list that are greater than 10 and both \n;; first and last digits of a number are odd (1, 3, 5, 7, 9).\n;; For example:\n;; >>> (specialFilter (list 15 -73 14 -15))\n;; 1\n;; >>> (specialFilter (list 33 -2 -3 45 21 109))\n;; 2\n(define (specialFilter nums)\n (count (filter (lambda (x)\n (and (> x 10)\n (odd? (string->number (string (string-ref (number->string x) 0))))\n (odd? (string->number (string (string-ref (number->string x) (- (string-length (number->string x)) 1)))))))\n nums)))\n"], ["#lang racket\n;; You are given a positive integer n. You have to create an integer list a of length n.\n;; For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n;; Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n;; and a[i] + a[j] + a[k] is a multiple of 3.\n;; Example :\n;; >>> (get_max_triples 5)\n;; 1\n;; Explanation: \n;; a = [1, 3, 7, 13, 21]\n;; The only valid triple is (1, 7, 13).\n(define (get_max_triples n)\n (let ((a (map (lambda (i) (+ (* i i) (- i) 1)) (range 1 (+ n 1)))))\n (count (lambda (triple) (= (modulo (apply + triple) 3) 0))\n (combinations a 3))))\n"], ["#lang racket\n;; There are eight planets in our solar system: the closerst to the Sun \n;; is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n;; Uranus, Neptune.\n;; Write a function that takes two planet names as strings planet1 and planet2. \n;; The function should return a list containing all planets whose orbits are \n;; located between the orbit of planet1 and the orbit of planet2, sorted by \n;; the proximity to the sun. \n;; The function should return an empty list if planet1 or planet2\n;; are not correct planet names. \n;; Examples\n;; >>> (bf \"Jupiter\" \"Neptune\")\n;; (list \"Saturn\" \"Uranus\")\n;; >>> (bf \"Earth\" \"Mercury\")\n;; \"Venus\"\n;; >>> (bf \"Mercury\" \"Uranus\")\n;; (list \"Venus\" \"Earth\" \"Mars\" \"Jupiter\" \"Saturn\")\n(define (bf planet1 planet2)\n (let ((planets '(\"Mercury\" \"Venus\" \"Earth\" \"Mars\" \"Jupiter\" \"Saturn\" \"Uranus\" \"Neptune\")))\n (cond\n ((not (member planet1 planets)) '())\n ((not (member planet2 planets)) '())\n (else\n (let ((start-index (add1 (list-index planets planet1)))\n (end-index (list-index planets planet2)))\n (if (< end-index start-index)\n (reverse (sublist planets end-index start-index))\n (sublist planets start-index end-index)))))))\n"], ["#lang racket\n;; Write a function that accepts a list of strings as a parameter,\n;; deletes the strings that have odd lengths from it,\n;; and returns the resulted list with a sorted order,\n;; The list is always a list of strings and never a list of numbers,\n;; and it may contain duplicates.\n;; The order of the list should be ascending by length of each word, and you\n;; should return the list sorted by that rule.\n;; If two words have the same length, sort the list alphabetically.\n;; The function should return a list of strings in sorted order.\n;; You may assume that all words will have the same length.\n;; For example:\n;; >>> (list_sort (list \"aa\" \"a\" \"aaa\"))\n;; (list \"aa\")\n;; >>> (list_sort (list \"ab\" \"a\" \"aaa\" \"cd\"))\n;; (list \"ab\" \"cd\")\n(define (sorted_list_sum lst)\n (sort lst string>> (all_prefixes \"abc\")\n;; (list \"a\" \"ab\" \"abc\")\n(define (all_prefixes string)\n (let loop ((i 1) (prefixes (list (substring string 0 1))))\n (if (= i (string-length string))\n prefixes\n (loop (+ i 1) (cons (substring string 0 (+ i 1)) prefixes)))))\n"], ["#lang racket\n;; A simple program which should return the value of x if n is \n;; a prime number and should return the value of y otherwise.\n;; Examples:\n;; >>> (x_or_y 7 34 12)\n;; 34\n;; >>> (x_or_y 15 8 5)\n;; 5\n(define (x_or_y n x y)\n (if (prime? n)\n x\n y))\n"], ["#lang racket\n;; Given a list of numbers, return the sum of squares of the numbers\n;; in the list that are odd. Ignore numbers that are negative or not integers.\n;; >>> (double_the_difference (list 1 3 2 0))\n;; 10\n;; >>> (double_the_difference (list -1 -2 0))\n;; 0\n;; >>> (double_the_difference (list 9 -2))\n;; 81\n;; >>> (double_the_difference (list 0))\n;; 0\n;; If the input list is empty, return 0.\n(define (double_the_difference lst)\n (if (empty? lst)\n 0\n (let ((first (first lst)))\n (if (and (integer? first) (odd? first))\n (+ (expt first 2) (double_the_difference (rest lst)))\n (double_the_difference (rest lst))))))\n"], ["#lang racket\n;; I think we all remember that feeling when the result of some long-awaited\n;; event is finally known. The feelings and thoughts you have at that moment are\n;; definitely worth noting down and comparing.\n;; Your task is to determine if a person correctly guessed the results of a number of matches.\n;; You are given two lists of scores and guesses of equal length, where each index shows a match. \n;; Return a list of the same length denoting how far off each guess was. If they have guessed correctly,\n;; the value is 0, and if not, the value is the absolute difference between the guess and the score.\n;; example:\n;; >>> (compare (list 1 2 3 4 5 1) (list 1 2 3 4 2 -2))\n;; (list 0 0 0 0 3 3)\n;; >>> (compare (list 0 5 0 0 0 4) (list 4 1 1 0 0 -2))\n;; (list 4 4 1 0 0 6)\n(define (compare game guess)\n (map (lambda (g s) (abs (- g s))) guess game))\n"], ["#lang racket\n;; You will be given the name of a class (a string) and a list of extensions.\n;; The extensions are to be used to load additional classes to the class. The\n;; strength of the extension is as follows: Let CAP be the number of the uppercase\n;; letters in the extension's name, and let SM be the number of lowercase letters \n;; in the extension's name, the strength is given by the fraction CAP - SM. \n;; You should find the strongest extension and return a string in this \n;; format: ClassName.StrongestExtensionName.\n;; If there are two or more extensions with the same strength, you should\n;; choose the one that comes first in the list.\n;; For example, if you are given \"Slices\" as the class and a list of the\n;; extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n;; return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n;; (its strength is -1).\n;; Example:\n;; >>> (Strongest_Extension \"my_class\" (list \"AA\" \"Be\" \"CC\"))\n;; \"my_class.AA\"\n(define (Strongest_Extension class_name extensions)\n (define (extension_strength extension)\n (let ((uppercase_count (string-count extension char-upper-case?))\n (lowercase_count (string-count extension char-lower-case?)))\n (- uppercase_count lowercase_count)))\n (define (strongest_extension extensions)\n (let ((sorted_extensions (sort extensions > extension_strength)))\n (car sorted_extensions)))\n (string-append class_name \".\" (strongest_extension extensions)))\n"], ["#lang racket\n;; You are given 2 words. You need to return #t if the second word or any of its rotations is a substring in the first word\n;; >>> (cycpattern_check \"abcd\" \"abd\")\n;; #f\n;; >>> (cycpattern_check \"hello\" \"ell\")\n;; #t\n;; >>> (cycpattern_check \"whassup\" \"psus\")\n;; #f\n;; >>> (cycpattern_check \"abab\" \"baa\")\n;; #t\n;; >>> (cycpattern_check \"efef\" \"eeff\")\n;; #f\n;; >>> (cycpattern_check \"himenss\" \"simen\")\n;; #t\n(define (cycpattern_check a b)\n (let ((len (string-length b)))\n (let loop ((i 0))\n (if (= i len)\n #f\n (let ((rotated (substring b i len)))\n (if (string-contains? a rotated)\n #t\n (loop (+ i 1))))))))\n"], ["#lang racket\n;; Given an integer. return a list that has the number of even and odd digits respectively.\n;; Example:\n;; >>> (even_odd_count -12)\n;; (list 1 1)\n;; >>> (even_odd_count 123)\n;; (list 1 2)\n(define (even_odd_count num)\n (let loop ((n num) (even 0) (odd 0))\n (if (= n 0)\n (list even odd)\n (let ((digit (remainder n 10)))\n (if (even? digit)\n (loop (quotient n 10) (+ even 1) odd)\n (loop (quotient n 10) even (+ odd 1)))))))\n"], ["#lang racket\n;; Given a positive integer, obtain its roman numeral equivalent as a string,\n;; and return it in lowercase.\n;; Restrictions: 1 <= num <= 1000\n;; Examples:\n;; >>> (int_to_mini_roman 19)\n;; \"xix\"\n;; >>> (int_to_mini_roman 152)\n;; \"clii\"\n;; >>> (int_to_mini_roman 426)\n;; \"cdxxvi\"\n(define (int_to_mini_roman number)\n (define (roman-digit digit place)\n (cond\n [(= digit 0) \"\"]\n [(<= digit 3) (string-repeat (roman-digit-symbol place) digit)]\n [(= digit 4) (string-append (roman-digit-symbol place) (roman-digit-symbol (+ place 1)))]\n [(= digit 5) (roman-digit-symbol (+ place 1))]\n [(<= digit 8) (string-append (roman-digit-symbol (+ place 1)) (roman-digit-symbol place) (roman-digit-symbol place))]\n [else (string-append (roman-digit-symbol place) (roman-digit-symbol (+ place 2)))]))\n (define (roman-digit-symbol place)\n (case place\n [(0) \"i\"]\n [(1) \"x\"]\n [(2) \"c\"]\n [(3) \"m\"]))\n (string-downcase\n (string-append\n (roman-digit (quotient number 1000) 3)\n (roman-digit (remainder (quotient number 100) 10) 2)\n (roman-digit (remainder (quotient number 10) 10) 1)\n (roman-digit (remainder number 10) 0))))\n"], ["#lang racket\n;; Given the lengths of the three sides of a triangle. Return #t if the three\n;; sides form a right-angled triangle, #f otherwise.\n;; A right-angled triangle is a triangle in which one angle is right angle or \n;; 90 degree.\n;; Example:\n;; >>> (right_angle_triangle 3 4 5)\n;; #t\n;; >>> (right_angle_triangle 1 2 3)\n;; #f\n(define (right_angle_triangle a b c)\n (or (and (= (+ (* a a) (* b b)) (* c c)) (or (= a b) (= a c) (= b c)))\n (and (= (+ (* a a) (* c c)) (* b b)) (or (= a b) (= a c) (= b c)))\n (and (= (+ (* b b) (* c c)) (* a a)) (or (= a b) (= a c) (= b c)))))\n)\n"], ["#lang racket\n;; Write a function that accepts a list of strings.\n;; The list contains different words. Return the word with maximum number\n;; of unique characters. If multiple strings have maximum number of unique\n;; characters, return the one which comes first in lexicographical order.\n;; >>> (find_max (list \"name\" \"of\" \"string\"))\n;; \"string\"\n;; >>> (find_max (list \"name\" \"enam\" \"game\"))\n;; \"enam\"\n;; >>> (find_max (list \"aaaaaaa\" \"bb\" \"cc\"))\n;; \"aaaaaaa\"\n(define (find_max words)\n (define (count-unique-chars word)\n (length (set->list (string->char-set word))))\n (define (compare-words word1 word2)\n (if (> (count-unique-chars word1) (count-unique-chars word2))\n word1\n (if (< (count-unique-chars word1) (count-unique-chars word2))\n word2\n (if (string>> (eat 5 6 10)\n;; (list 11 4)\n;; >>> (eat 4 8 9)\n;; (list 12 1)\n;; >>> (eat 1 10 10)\n;; (list 11 0)\n;; >>> (eat 2 11 5)\n;; (list 7 0)\n;; Variables:\n;; @number : integer\n;; the number of carrots that you have eaten.\n;; @need : integer\n;; the number of carrots that you need to eat.\n;; @remaining : integer\n;; the number of remaining carrots thet exist in stock\n;; Constrain:\n;; * 0 <= number <= 1000\n;; * 0 <= need <= 1000\n;; * 0 <= remaining <= 1000\n;; Have fun :)\n(define (eat number need remaining)\n (let ((eaten (min need remaining)))\n (list (+ number eaten) (- remaining eaten))))\n"], ["#lang racket\n;; Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n;; >>> (string_sequence 0)\n;; \"0\"\n;; >>> (string_sequence 5)\n;; \"0 1 2 3 4 5\"\n(define (string_sequence n)\n (let ((nums (build-list (+ n 1) values)))\n (string-join (map number->string nums) \" \")))\n"], ["#lang racket\n;; Given two lists operator, and operand. The first list has basic algebra operations, and \n;; the second list is a list of integers. Use the two given lists to build the algebric \n;; expression and return the evaluation of this expression.\n;; The basic algebra operations:\n;; Addition ( + ) \n;; Subtraction ( - ) \n;; Multiplication ( * ) \n;; Floor division ( // ) \n;; Exponentiation ( ** ) \n;; Example:\n;; operator['+', '*', '-']\n;; list = [2, 3, 4, 5]\n;; result = 2 + 3 * 4 - 5\n;; => result = 9\n;; Note:\n;; The length of operator list is equal to the length of operand list minus one.\n;; Operand is a list of of non-negative integers.\n;; Operator list has at least one operator, and operand list has at least two operands.\n(define (do_algebra operator operand)\n (let* ((op1 (car operand))\n (op2 (cadr operand))\n (rest (cddr operand))\n (result (case operator\n ((+) (+ op1 op2))\n ((-) (- op1 op2))\n ((*) (* op1 op2))\n ((//) (quotient op1 op2))\n ((**) (expt op1 op2)))))\n (if (null? rest)\n result\n (do_algebra (car rest) (cons result rest)))))\n"], ["#lang racket\n;; You are given a string s.\n;; if s[i] is a letter, reverse its case from lower to upper or vise versa, \n;; otherwise keep it as it is.\n;; If the string contains no letters, reverse the string.\n;; The function should return the resulted string.\n;; Examples\n;; >>> (solve \"1234\")\n;; \"4321\"\n;; >>> (solve \"ab\")\n;; \"AB\"\n;; >>> (solve \"#a@C\")\n;; \"#A@c\"\n(define (solve s)\n (if (string-contains? s #px\"[a-zA-Z]\")\n (string-map (lambda (c)\n (if (char-alphabetic? c)\n (if (char-upper-case? c)\n (char-downcase c)\n (char-upcase c))\n c))\n s)\n (string-reverse s)))\n"], ["#lang racket\n;; Given a string 'text', return its md5 hash equivalent string.\n;; If 'text' is an empty string, return #f.\n;; >>> (string_to_md5 \"Hello world\")\n;; \"3e25960a79dbc69b674cd4ec67a72c62\"\n(define (string_to_md5 text)\n (if (string=? text \"\")\n #f\n (let ((md5 (md5 text)))\n (string-downcase (bytes->hex-string md5)))))\n"], ["#lang racket\n;; Given two positive integers a and b, return the even digits between a\n;; and b, in ascending order.\n;; For example:\n;; >>> (generate_integers 2 8)\n;; (list 2 4 6 8)\n;; >>> (generate_integers 8 2)\n;; (list 2 4 6 8)\n;; >>> (generate_integers 10 14)\n;; (list )\n(define (generate_integers a b)\n (let ((start (if (even? a) a (+ a 1)))\n (end (if (even? b) b (- b 1))))\n (if (> start end)\n '()\n (cons start (generate_integers (+ start 2) end)))))\n"], ["#lang racket\n;; Given a string, find out how many distinct characters (regardless of case) does it consist of\n;; >>> (count_distinct_characters \"xyzXYZ\")\n;; 3\n;; >>> (count_distinct_characters \"Jerry\")\n;; 4\n(define (count_distinct_characters string)\n (length (set->list (string->char-set (string-downcase string)))))\n"], ["#lang racket\n;; Input to this function is a string representing musical notes in a special ASCII format.\n;; Your task is to parse this string and return list of integers corresponding to how many beats does each\n;; not last.\n;; Here is a legend:\n;; 'o' - whole note, lasts four beats\n;; 'o|' - half note, lasts two beats\n;; '.|' - quater note, lasts one beat\n;; >>> (parse_music \"o o| .| o| o| .| .| .| .| o o\")\n;; (list 4 2 1 2 2 1 1 1 1 4 4)\n(define (parse_music music_string)\n (define (parse-note note)\n (cond\n [(string=? note \"o\") 4]\n [(string=? note \"o|\") 2]\n [(string=? note \".|\") 1]\n [else (error \"Invalid note: \" note)]))\n (map parse-note (string-split music_string \" \")))\n"], ["#lang racket\n;; Find how many times a given substring can be found in the original string. Count overlaping cases.\n;; >>> (how_many_times \"\" \"a\")\n;; 0\n;; >>> (how_many_times \"aaa\" \"a\")\n;; 3\n;; >>> (how_many_times \"aaaa\" \"aa\")\n;; 3\n(define (how_many_times string substring)\n (let ((len-str (string-length string))\n (len-sub (string-length substring)))\n (let loop ((i 0)\n (count 0))\n (if (> (+ i len-sub) len-str)\n count\n (if (string=? (substring string i (+ i len-sub)) substring)\n (loop (+ i 1) (+ count 1))\n (loop (+ i 1) count))))))\n"], ["#lang racket\n;; Input is a space-delimited string of numberals from 'zero' to 'nine'.\n;; Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n;; Return the string with numbers sorted from smallest to largest\n;; >>> (sort_numbers \"three one five\")\n;; \"one three five\"\n(define (sort_numbers numbers)\n (let ((numbers-list (string-split numbers)))\n (string-join (sort numbers-list string>> (separate_paren_groups \"( ) (( )) (( )( ))\")\n;; (list \"()\" \"(())\" \"(()())\")\n(define (separate_paren_groups paren_string)\n (let loop ((paren_string paren_string)\n (result '()))\n (cond\n ((string-empty? paren_string) (reverse result))\n (else\n (let ((next-paren-group (find-next-paren-group paren_string)))\n (loop (string-trim (substring paren_string (+ (string-length next-paren-group) 1)))\n (cons next-paren-group result)))))))\n"], ["#lang racket\n;; From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n;; other and return them in order (smaller number, larger number).\n;; >>> (find_closest_elements (list 1.0 2.0 3.0 4.0 5.0 2.2))\n;; (list 2.0 2.2)\n;; >>> (find_closest_elements (list 1.0 2.0 3.0 4.0 5.0 2.0))\n;; (list 2.0 2.0)\n(define (find_closest_elements numbers)\n (let* ((sorted-numbers (sort numbers <))\n (pairs (map list sorted-numbers (cdr sorted-numbers)))\n (differences (map (lambda (pair) (- (cadr pair) (car pair))) pairs))\n (min-difference (apply min differences))\n (closest-pair (findf (lambda (pair) (= (abs (- (cadr pair) (car pair))) min-difference)) pairs)))\n (sort closest-pair <)))\n"], ["#lang racket\n;; Given list of numbers (of at least two elements), apply a linear transform to that list,\n;; such that the smallest number will become 0 and the largest will become 1\n;; >>> (rescale_to_unit (list 1.0 2.0 3.0 4.0 5.0))\n;; (list 0.0 0.25 0.5 0.75 1.0)\n(define (rescale_to_unit numbers)\n (let* ((min_num (apply min numbers))\n (max_num (apply max numbers))\n (range (- max_num min_num)))\n (map (lambda (num) (/ (- num min_num) range)) numbers)))\n"], ["#lang racket\n;; Filter given list of any rktthon values only for integers\n;; >>> (filter_integers (list \"a\" 3.14 5))\n;; (list 5)\n;; >>> (filter_integers (list 1 2 3 \"abc\" #hash() (list )))\n;; (list 1 2 3)\n(define (filter_integers values)\n (filter number? values))\n"], ["#lang racket\n;; Return length of given string\n;; >>> (strlen \"\")\n;; 0\n;; >>> (strlen \"abc\")\n;; 3\n(define (strlen string)\n (string-length string))\n"], ["#lang racket\n;; For a given number n, find the largest number that divides n evenly, smaller than n\n;; >>> (largest_divisor 15)\n;; 5\n(define (largest_divisor n)\n (let loop ((i (- n 1)))\n (if (and (> i 1) (not (zero? (modulo n i))))\n (loop (- i 1))\n i)))\n"], ["#lang racket\n;; Return list of prime factors of given integer in the order from smallest to largest.\n;; Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n;; Input number should be equal to the product of all factors\n;; >>> (factorize 8)\n;; (list 2 2 2)\n;; >>> (factorize 25)\n;; (list 5 5)\n;; >>> (factorize 70)\n;; (list 2 5 7)\n(define (factorize n)\n (define (helper n factors)\n (cond\n [(= n 1) factors]\n [(zero? (modulo n 2)) (helper (/ n 2) (cons 2 factors))]\n [(zero? (modulo n 3)) (helper (/ n 3) (cons 3 factors))]\n [(zero? (modulo n 5)) (helper (/ n 5) (cons 5 factors))]\n [(zero? (modulo n 7)) (helper (/ n 7) (cons 7 factors))]\n [else (helper (/ n (smallest-factor n)) (cons (smallest-factor n) factors))]))\n (define (smallest-factor n)\n (cond\n [(= n 1) 1]\n [(zero? (modulo n 2)) 2]\n [(zero? (modulo n 3)) 3]\n [(zero? (modulo n 5)) 5]\n [(zero? (modulo n 7)) 7]\n [else (smallest-factor (+ n 1))]))\n (helper n '()))\n"], ["#lang racket\n;; From a list of integers, remove all elements that occur more than once.\n;; Keep order of elements left the same as in the input.\n;; >>> (remove_duplicates (list 1 2 3 2 4))\n;; (list 1 3 4)\n(define (remove_duplicates numbers)\n (let loop ((numbers numbers) (seen '()) (result '()))\n (if (null? numbers)\n (reverse result)\n (let ((number (car numbers)))\n (if (member number seen)\n (loop (cdr numbers) seen result)\n (loop (cdr numbers) (cons number seen) (cons number result)))))))\n"], ["#lang racket\n;; For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n;; >>> (flip_case \"Hello\")\n;; \"hELLO\"\n(define (flip_case string)\n (list->string\n (map (lambda (char)\n (if (char-lower-case? char)\n (char-upcase char)\n (char-downcase char)))\n (string->list string))))\n"], ["#lang racket\n;; Concatenate list of strings into a single string\n;; >>> (concatenate (list ))\n;; \"\"\n;; >>> (concatenate (list \"a\" \"b\" \"c\"))\n;; \"abc\"\n(define (concatenate strings)\n (apply string-append strings))\n"], ["#lang racket\n;; Filter an input list of strings only for ones that start with a given prefix.\n;; >>> (filter_by_prefix (list ) \"a\")\n;; (list )\n;; >>> (filter_by_prefix (list \"abc\" \"bcd\" \"cde\" \"array\") \"a\")\n;; (list \"abc\" \"array\")\n(define (filter_by_prefix strings prefix)\n (filter (lambda (s) (string-prefix? prefix s)) strings))\n"], ["#lang racket\n;; Given a positive floating point number, it can be decomposed into\n;; and integer part (largest integer smaller than given number) and decimals\n;; (leftover part always smaller than 1).\n;; Return the decimal part of the number.\n;; >>> (truncate_number 3.5)\n;; 0.5\n(define (truncate_number number)\n (- number (floor number)))\n"], ["#lang racket\n;; Return only positive numbers in the list.\n;; >>> (get_positive (list -1 2 -4 5 6))\n;; (list 2 5 6)\n;; >>> (get_positive (list 5 3 -5 2 -3 3 9 0 123 1 -10))\n;; (list 5 3 2 3 9 123 1)\n(define (get_positive l)\n (filter positive? l))\n"], ["#lang racket\n;; Return true if a given number is prime, and false otherwise.\n;; >>> (is_prime 6)\n;; #f\n;; >>> (is_prime 101)\n;; #t\n;; >>> (is_prime 11)\n;; #t\n;; >>> (is_prime 13441)\n;; #t\n;; >>> (is_prime 61)\n;; #t\n;; >>> (is_prime 4)\n;; #f\n;; >>> (is_prime 1)\n;; #f\n(define (is_prime n)\n (define (helper i)\n (cond\n [(> (* i i) n) #t]\n [(zero? (modulo n i)) #f]\n [else (helper (+ i 1))]))\n (cond\n [(< n 2) #f]\n [else (helper 2)]))\n"], ["#lang racket\n;; This function takes a list l and returns a list l' such that\n;; l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n;; to the values of the corresponding indicies of l, but sorted.\n;; >>> (sort_third (list 1 2 3))\n;; (list 1 2 3)\n;; >>> (sort_third (list 5 6 3 4 8 9 2))\n;; (list 2 6 3 4 8 9 5)\n(define (sort_third l)\n (let* ((divisible-by-three (filter (lambda (x) (zero? (modulo x 3))) l))\n (sorted-divisible-by-three (sort divisible-by-three <))\n (result (map (lambda (x) (if (zero? (modulo x 3)) (car sorted-divisible-by-three) x)) l)))\n result))\n"], ["#lang racket\n;; Return sorted unique elements in a list\n;; >>> (unique (list 5 3 5 2 3 3 9 0 123))\n;; (list 0 2 3 5 9 123)\n(define (unique l)\n (sort (remove-duplicates l) <))\n"], ["#lang racket\n;; Return maximum element in the list.\n;; >>> (max_element (list 1 2 3))\n;; 3\n;; >>> (max_element (list 5 3 -5 2 -3 3 9 0 123 1 -10))\n;; 123\n(define (max_element l)\n (apply max l))\n"], ["#lang racket\n;; Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n;; >>> (fizz_buzz 50)\n;; 0\n;; >>> (fizz_buzz 78)\n;; 2\n;; >>> (fizz_buzz 79)\n;; 3\n(define (fizz_buzz n)\n (let loop ((i 1) (count 0))\n (if (>= i n)\n count\n (if (or (and (< i 11) (= (remainder i 11) 0))\n (and (>= i 11) (= (remainder i 11) 0) (= (remainder i 13) 0)))\n (loop (+ i 1) (+ count (count-digit 7 i)))\n (loop (+ i 1) count)))))\n"], ["#lang racket\n;; This function takes a list l and returns a list l' such that\n;; l' is identical to l in the odd indicies, while its values at the even indicies are equal\n;; to the values of the even indicies of l, but sorted.\n;; >>> (sort_even (list 1 2 3))\n;; (list 1 2 3)\n;; >>> (sort_even (list 5 6 3 4))\n;; (list 3 6 5 4)\n(define (sort_even l)\n (let* ((even-values (filter even? l))\n (sorted-values (sort even-values <))\n (result (make-list (length l) #f)))\n (for ([i (in-range 0 (length l) 2)])\n (set! (list-ref result i) (list-ref l i)))\n (for ([i (in-range 1 (length l) 2)])\n (set! (list-ref result i) (list-ref sorted-values (quotient i 2))))\n result))\n"], ["#lang racket\n;; prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n;; >>> (prime_fib 1)\n;; 2\n;; >>> (prime_fib 2)\n;; 3\n;; >>> (prime_fib 3)\n;; 5\n;; >>> (prime_fib 4)\n;; 13\n;; >>> (prime_fib 5)\n;; 89\n(define (prime_fib n)\n (define (fib n)\n (cond ((= n 0) 0)\n ((= n 1) 1)\n (else (+ (fib (- n 1)) (fib (- n 2))))))\n (define (prime? n)\n (define (helper i)\n (cond ((> (* i i) n) #t)\n ((= (modulo n i) 0) #f)\n (else (helper (+ i 1)))))\n (helper 2))\n (define (prime_fib_helper count n)\n (if (= count n)\n (fib count)\n (if (and (prime? (fib count)) (= (fib count) (fib (+ count 1))))\n (prime_fib_helper (+ count 1) n)\n (prime_fib_helper (+ count 1) n))))\n (prime_fib_helper 0 n))\n"], ["#lang racket\n;; You're given a list of deposit and withdrawal operations on a bank account that starts with\n;; zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n;; at that point function should return #t. Otherwise it should return #f.\n;; >>> (below_zero (list 1 2 3))\n;; #f\n;; >>> (below_zero (list 1 2 -4 5))\n;; #t\n(define (below_zero operations)\n (let loop ((balance 0) (ops operations))\n (cond\n ((null? ops) #f)\n ((< (+ balance (car ops)) 0) #t)\n (else (loop (+ balance (car ops)) (cdr ops))))))\n"], ["#lang racket\n;; triples_sum_to_zero takes a list of integers as an input.\n;; it returns #t if there are three distinct elements in the list that\n;; sum to zero, and #f otherwise.\n;; >>> (triples_sum_to_zero (list 1 3 5 0))\n;; #f\n;; >>> (triples_sum_to_zero (list 1 3 -2 1))\n;; #t\n;; >>> (triples_sum_to_zero (list 1 2 3 7))\n;; #f\n;; >>> (triples_sum_to_zero (list 2 4 -5 3 9 7))\n;; #t\n;; >>> (triples_sum_to_zero (list 1))\n;; #f\n(define (triples_sum_to_zero l)\n (let loop ((i 0) (j 1) (k 2))\n (cond\n ((= i (- (length l) 2)) #f)\n ((= j (- (length l) 1)) (loop (+ i 1) (+ i 2) (+ i 3)))\n ((= k (length l)) (loop i (+ j 1) (+ j 2)))\n ((= (+ (list-ref l i) (list-ref l j) (list-ref l k)) 0) #t)\n (else (loop i j (+ k 1))))))\n"], ["#lang racket\n;; Imagine a road that's a perfectly straight infinitely long line.\n;; n cars are driving left to right; simultaneously, a different set of n cars\n;; are driving right to left. The two sets of cars start out being very far from\n;; each other. All cars move in the same speed. Two cars are said to collide\n;; when a car that's moving left to right hits a car that's moving right to left.\n;; However, the cars are infinitely sturdy and strong; as a result, they continue moving\n;; in their trajectory as if they did not collide.\n;; This function outputs the number of such collisions.\n(define (car_race_collision n)\n (* n 2))\n"], ["#lang racket\n;; Return list with elements incremented by 1.\n;; >>> (incr_list (list 1 2 3))\n;; (list 2 3 4)\n;; >>> (incr_list (list 5 3 5 2 3 3 9 0 123))\n;; (list 6 4 6 3 4 4 10 1 124)\n(define (incr_list l)\n (map add1 l))\n"], ["#lang racket\n;; pairs_sum_to_zero takes a list of integers as an input.\n;; it returns #t if there are two distinct elements in the list that\n;; sum to zero, and #f otherwise.\n;; >>> (pairs_sum_to_zero (list 1 3 5 0))\n;; #f\n;; >>> (pairs_sum_to_zero (list 1 3 -2 1))\n;; #f\n;; >>> (pairs_sum_to_zero (list 1 2 3 7))\n;; #f\n;; >>> (pairs_sum_to_zero (list 2 4 -5 3 5 7))\n;; #t\n;; >>> (pairs_sum_to_zero (list 1))\n;; #f\n(define (pairs_sum_to_zero l)\n (let loop ((lst l))\n (cond\n ((null? lst) #f)\n ((member? (- (car lst)) (cdr lst)) #t)\n (else (loop (cdr lst))))))\n"], ["#lang racket\n;; Change numerical base of input number x to base.\n;; return string representation after the conversion.\n;; base numbers are less than 10.\n;; >>> (change_base 8 3)\n;; \"22\"\n;; >>> (change_base 8 2)\n;; \"1000\"\n;; >>> (change_base 7 2)\n;; \"111\"\n(define (change_base x base)\n (number->string x base))\n"], ["#lang racket\n;; Given length of a side and high return area for a triangle.\n;; >>> (triangle_area 5 3)\n;; 7.5\n(define (triangle_area a h)\n (* 0.5 a h))\n"], ["#lang racket\n;; The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n;; fib4(0) -> 0\n;; fib4(1) -> 0\n;; fib4(2) -> 2\n;; fib4(3) -> 0\n;; fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n;; Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n;; >>> (fib4 5)\n;; 4\n;; >>> (fib4 6)\n;; 8\n;; >>> (fib4 7)\n;; 14\n(define (fib4 n)\n (let loop ((a 0) (b 0) (c 2) (d 0) (count n))\n (if (= count 0)\n a\n (loop b c d (+ a b c d) (- count 1)))))\n"], ["#lang racket\n;; Return median of elements in the list l.\n;; >>> (median (list 3 1 2 4 5))\n;; 3\n;; >>> (median (list -10 4 6 1000 10 20))\n;; 15.0\n(define (median l)\n (let* ((sorted-l (sort l <))\n (n (length sorted-l))\n (mid-index (/ n 2)))\n (if (odd? n)\n (list-ref sorted-l (floor mid-index))\n (/ (+ (list-ref sorted-l (floor mid-index))\n (list-ref sorted-l (ceiling mid-index)))\n 2))))\n"], ["#lang racket\n;; Checks if given string is a palindrome\n;; >>> (is_palindrome \"\")\n;; #t\n;; >>> (is_palindrome \"aba\")\n;; #t\n;; >>> (is_palindrome \"aaaaa\")\n;; #t\n;; >>> (is_palindrome \"zbcd\")\n;; #f\n(define (is_palindrome text)\n (equal? text (string-reverse text)))\n"], ["#lang racket\n;; Return 2^n modulo p (be aware of numerics).\n;; >>> (modp 3 5)\n;; 3\n;; >>> (modp 1101 101)\n;; 2\n;; >>> (modp 0 101)\n;; 1\n;; >>> (modp 3 11)\n;; 8\n;; >>> (modp 100 101)\n;; 1\n(define (modp n p)\n (modulo (expt 2 n) p))\n"], ["#lang racket\n;; For a given list of input numbers, calculate Mean Absolute Deviation\n;; around the mean of this dataset.\n;; Mean Absolute Deviation is the average absolute difference between each\n;; element and a centerpoint (mean in this case):\n;; MAD = average | x - x_mean |\n;; >>> (mean_absolute_deviation (list 1.0 2.0 3.0 4.0))\n;; 1.0\n(define (mean_absolute_deviation numbers)\n (let* ((n (length numbers))\n (mean (/ (apply + numbers) n))\n (deviations (map (lambda (x) (abs (- x mean))) numbers))\n (sum_deviations (apply + deviations)))\n (/ sum_deviations n)))\n"], ["#lang racket\n;; remove_vowels is a function that takes string and returns string without vowels.\n;; >>> (remove_vowels \"\")\n;; \"\"\n;; >>> (remove_vowels \"abcdef\")\n;; \"bcdf\"\n;; >>> (remove_vowels \"aaaaa\")\n;; \"\"\n;; >>> (remove_vowels \"aaBAA\")\n;; \"B\"\n;; >>> (remove_vowels \"zbcd\")\n;; \"zbcd\"\n(define (remove_vowels text)\n (list->string (filter (lambda (c) (not (member c '(#\\a #\\e #\\i #\\o #\\u #\\A #\\E #\\I #\\O #\\U)))) (string->list text))))\n"], ["#lang racket\n;; Return #t if all numbers in the list l are below threshold t.\n;; >>> (below_threshold (list 1 2 4 10) 100)\n;; #t\n;; >>> (below_threshold (list 1 20 4 10) 5)\n;; #f\n(define (below_threshold l t)\n (cond\n [(null? l) #t]\n [(> (car l) t) #f]\n [else (below_threshold (cdr l) t)]))\n"], ["#lang racket\n;; Add two numbers x and y\n;; >>> (add 2 3)\n;; 5\n;; >>> (add 5 7)\n;; 12\n(define (add x y)\n (+ x y))\n"], ["#lang racket\n;; Check if two words have the same characters.\n;; >>> (same_chars \"eabcdzzzz\" \"dddzzzzzzzddeddabc\")\n;; #t\n;; >>> (same_chars \"abcd\" \"dddddddabc\")\n;; #t\n;; >>> (same_chars \"dddddddabc\" \"abcd\")\n;; #t\n;; >>> (same_chars \"eabcd\" \"dddddddabc\")\n;; #f\n;; >>> (same_chars \"abcd\" \"dddddddabce\")\n;; #f\n;; >>> (same_chars \"eabcdzzzz\" \"dddzzzzzzzddddabc\")\n;; #f\n(define (same_chars s0 s1)\n (equal? (sort (string->list s0) charlist s1) char>> (fib 10)\n;; 55\n;; >>> (fib 1)\n;; 1\n;; >>> (fib 8)\n;; 21\n(define (fib n)\n (cond\n [(= n 0) 0]\n [(= n 1) 1]\n [else (+ (fib (- n 1)) (fib (- n 2)))]))\n"], ["#lang racket\n;; brackets is a string of \"<\" and \">\".\n;; return #t if every opening bracket has a corresponding closing bracket.\n;; >>> (correct_bracketing \"<\")\n;; #f\n;; >>> (correct_bracketing \"<>\")\n;; #t\n;; >>> (correct_bracketing \"<<><>>\")\n;; #t\n;; >>> (correct_bracketing \"><<>\")\n;; #f\n(define (correct_bracketing brackets)\n (let loop ((stack '()) (brackets (string->list brackets)))\n (cond\n ((null? brackets) (null? stack))\n ((char=? (car brackets) #\\<) (loop (cons #\\< stack) (cdr brackets)))\n ((char=? (car brackets) #\\>)\n (if (null? stack)\n #f\n (loop (cdr stack) (cdr brackets))))\n (else (loop stack (cdr brackets))))))\n"], ["#lang racket\n;; Return #t is list elements are monotonically increasing or decreasing.\n;; >>> (monotonic (list 1 2 4 20))\n;; #t\n;; >>> (monotonic (list 1 20 4 10))\n;; #f\n;; >>> (monotonic (list 4 1 0 -10))\n;; #t\n(define (monotonic l)\n (cond\n [(null? l) #t]\n [(null? (cdr l)) #t]\n [(< (car l) (cadr l)) (monotonic (cdr l))]\n [(> (car l) (cadr l)) (monotonic (cdr l))]\n [else #f]))\n"], ["#lang racket\n;; Return sorted unique common elements for two lists.\n;; >>> (common (list 1 4 3 34 653 2 5) (list 5 7 1 5 9 653 121))\n;; (list 1 5 653)\n;; >>> (common (list 5 3 2 8) (list 3 2))\n;; (list 2 3)\n(define (common l1 l2)\n (sort (remove-duplicates (filter (lambda (x) (member x l2)) l1)) <))\n"], ["#lang racket\n;; Return the largest prime factor of n. Assume n > 1 and is not a prime.\n;; >>> (largest_prime_factor 13195)\n;; 29\n;; >>> (largest_prime_factor 2048)\n;; 2\n(define (largest_prime_factor n)\n (let loop ((i 2) (largest 1))\n (cond\n ((> i n) largest)\n ((and (= (modulo n i) 0) (prime? i)) (loop (+ i 1) i))\n (else (loop (+ i 1) largest)))))\n"], ["#lang racket\n;; Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n;; >>> (intersperse (list ) 4)\n;; (list )\n;; >>> (intersperse (list 1 2 3) 4)\n;; (list 1 4 2 4 3)\n(define (intersperse numbers delimeter)\n (cond\n [(empty? numbers) '()]\n [(empty? (rest numbers)) (list (first numbers))]\n [else (append (list (first numbers) delimeter) (intersperse (rest numbers) delimeter))]))\n"], ["#lang racket\n;; sum_to_n is a function that sums numbers from 1 to n.\n;; >>> (sum_to_n 30)\n;; 465\n;; >>> (sum_to_n 100)\n;; 5050\n;; >>> (sum_to_n 5)\n;; 15\n;; >>> (sum_to_n 10)\n;; 55\n;; >>> (sum_to_n 1)\n;; 1\n(define (sum_to_n n)\n (/ (* n (+ n 1)) 2))\n"], ["#lang racket\n;; brackets is a string of \"(\" and \")\".\n;; return #t if every opening bracket has a corresponding closing bracket.\n;; >>> (correct_bracketing \"(\")\n;; #f\n;; >>> (correct_bracketing \"()\")\n;; #t\n;; >>> (correct_bracketing \"(()())\")\n;; #t\n;; >>> (correct_bracketing \")(()\")\n;; #f\n(define (correct_bracketing brackets)\n (let loop ([stack '()] [brackets (string->list brackets)])\n (cond\n [(null? brackets) (null? stack)]\n [(char=? (car brackets) #\\() (loop (cons #\\( stack) (cdr brackets))]\n [(char=? (car brackets) #\\)) (if (null? stack) #f (loop (cdr stack) (cdr brackets)))])))\n"], ["#lang racket\n;; xs represent coefficients of a polynomial.\n;; xs[0] + xs[1] * x + xs[2] * x^2 + ....\n;; Return derivative of this polynomial in the same form.\n;; >>> (derivative (list 3 1 2 4 5))\n;; (list 1 4 12 20)\n;; >>> (derivative (list 1 2 3))\n;; (list 2 6)\n(define (derivative xs)\n (for/list ([i (in-range 1 (length xs))])\n (* (list-ref xs (- i 1)) i)))\n"], ["#lang racket\n;; The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n;; fibfib(0) == 0\n;; fibfib(1) == 0\n;; fibfib(2) == 1\n;; fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n;; Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n;; >>> (fibfib 1)\n;; 0\n;; >>> (fibfib 5)\n;; 4\n;; >>> (fibfib 8)\n;; 24\n(define (fibfib n)\n (cond\n [(= n 0) 0]\n [(= n 1) 0]\n [(= n 2) 1]\n [else (+ (fibfib (- n 1)) (fibfib (- n 2)) (fibfib (- n 3)))]))\n"], ["#lang racket\n;; Write a function vowels_count which takes a string representing\n;; a word as input and returns the number of vowels in the string.\n;; Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n;; vowel, but only when it is at the end of the given word.\n;; Example:\n;; >>> (vowels_count \"abcde\")\n;; 2\n;; >>> (vowels_count \"ACEDY\")\n;; 3\n(define (vowels_count s)\n (let ((vowels '(#\\a #\\e #\\i #\\o #\\u #\\y)))\n (count (lambda (c) (member c vowels)) (string->list s))))\n"], ["#lang racket\n;; Circular shift the digits of the integer x, shift the digits right by shift\n;; and return the result as a string.\n;; If shift > number of digits, return digits reversed.\n;; >>> (circular_shift 12 1)\n;; \"21\"\n;; >>> (circular_shift 12 2)\n;; \"12\"\n(define (circular_shift x shift)\n (let* ((digits (string->list (number->string x)))\n (n (length digits)))\n (if (> shift n)\n (list->string (reverse digits))\n (list->string (append (drop-right digits shift) (take-right digits shift))))))\n"], ["#lang racket\n;; Task\n;; Write a function that takes a string as input and returns the sum of the upper characters only'\n;; ASCII codes.\n;; Examples:\n;; >>> (digitSum \"\")\n;; 0\n;; >>> (digitSum \"abAB\")\n;; 131\n;; >>> (digitSum \"abcCd\")\n;; 67\n;; >>> (digitSum \"helloE\")\n;; 69\n;; >>> (digitSum \"woArBld\")\n;; 131\n;; >>> (digitSum \"aAaaaXa\")\n;; 153\n(define (digitSum s)\n (let loop ((i 0) (sum 0))\n (if (= i (string-length s))\n sum\n (if (char-upper-case? (string-ref s i))\n (loop (+ i 1) (+ sum (char->integer (string-ref s i))))\n (loop (+ i 1) sum)))))\n"], ["#lang racket\n;; In this task, you will be given a string that represents a number of apples and oranges \n;; that are distributed in a basket of fruit this basket contains \n;; apples, oranges, and mango fruits. Given the string that represents the total number of \n;; the oranges and apples and an integer that represent the total number of the fruits \n;; in the basket return the number of the mango fruits in the basket.\n;; for examble:\n;; >>> (fruit_distribution \"5 apples and 6 oranges\" 19)\n;; 8\n;; >>> (fruit_distribution \"0 apples and 1 oranges\" 3)\n;; 2\n;; >>> (fruit_distribution \"2 apples and 3 oranges\" 100)\n;; 95\n;; >>> (fruit_distribution \"100 apples and 1 oranges\" 120)\n;; 19\n(define (fruit_distribution s n)\n (let* ((apples (string->number (regexp-match #px\"[0-9]+\" (regexp-match #px\"[0-9]+ apples\" s))))\n (oranges (string->number (regexp-match #px\"[0-9]+\" (regexp-match #px\"[0-9]+ oranges\" s))))\n (total-fruits (+ apples oranges)))\n (- n total-fruits)))\n"], ["#lang racket\n;; \"Given a list representing a branch of a tree that has non-negative integer nodes\n;; your task is to pluck one of the nodes and return it.\n;; The plucked node should be the node with the smallest even value.\n;; If multiple nodes with the same smallest even value are found return the node that has smallest index.\n;; The plucked node should be returned in a list, [ smalest_value, its index ],\n;; If there are no even values or the given list is empty, return [].\n;; Example 1:\n;; >>> (pluck (list 4 2 3))\n;; (list 2 1)\n;; Explanation: 2 has the smallest even value, and 2 has the smallest index.\n;; Example 2:\n;; >>> (pluck (list 1 2 3))\n;; (list 2 1)\n;; Explanation: 2 has the smallest even value, and 2 has the smallest index.\n;; Example 3:\n;; >>> (pluck (list ))\n;; (list )\n;; Example 4:\n;; >>> (pluck (list 5 0 3 0 4 2))\n;; (list 0 1)\n;; Explanation: 0 is the smallest value, but there are two zeros,\n;; so we will choose the first zero, which has the smallest index.\n;; Constraints:\n;; * 1 <= nodes.length <= 10000\n;; * 0 <= node.value\n(define (pluck arr)\n (let ((even-nodes (filter even? arr)))\n (if (empty? even-nodes)\n '()\n (let ((min-even (apply min even-nodes)))\n (list min-even (index-of min-even arr))))))\n"], ["#lang racket\n;; You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n;; zero, and has a frequency greater than or equal to the value of the integer itself. \n;; The frequency of an integer is the number of times it appears in the list.\n;; If no such a value exist, return -1.\n;; Examples:\n;; >>> (search (list 4 1 2 2 3 1))\n;; 2\n;; >>> (search (list 1 2 2 3 3 3 4 4 4))\n;; 3\n;; >>> (search (list 5 5 4 4 4))\n;; -1\n(define (search lst)\n (let ((freqs (make-hash)))\n (for ([x lst])\n (hash-set! freqs x (add1 (hash-ref freqs x 0))))\n (for/or ([x (in-range (apply max lst) 0 -1)])\n (when (>= (hash-ref freqs x 0) x)\n (return x)))\n -1))\n"], ["#lang racket\n;; Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n;; For each of the group, output the deepest level of nesting of parentheses.\n;; E.g. (()()) has maximum two levels of nesting while ((())) has three.\n;; >>> (parse_nested_parens \"(()()) ((())) () ((())()())\")\n;; (list 2 3 1 3)\n(define (parse_nested_parens paren_string)\n (define (parse_group group)\n (define (parse_group_helper group level max_level)\n (cond\n ((empty? group) max_level)\n ((char=? (first group) #\\() (parse_group_helper (rest group) (+ level 1) (max level max_level)))\n ((char=? (first group) #\\)) (parse_group_helper (rest group) (- level 1) (max level max_level)))\n (else (parse_group_helper (rest group) level max_level))))\n (parse_group_helper group 0 0))\n (map parse_group (string-split paren_string)))\n"], ["#lang racket\n;; Given list of integers, return list in strange order.\n;; Strange sorting, is when you start with the minimum value,\n;; then maximum of the remaining integers, then minimum and so on.\n;; Examples:\n;; >>> (strange_sort_list (list 1 2 3 4))\n;; (list 1 4 2 3)\n;; >>> (strange_sort_list (list 5 5 5 5))\n;; (list 5 5 5 5)\n;; >>> (strange_sort_list (list ))\n;; (list )\n(define (strange_sort_list lst)\n (if (null? lst)\n '()\n (let ((min-val (apply min lst))\n (max-val (apply max lst)))\n (if (= min-val max-val)\n (list min-val)\n (let ((remaining-lst (remove min-val (remove max-val lst))))\n (cons min-val (cons max-val (strange_sort_list remaining-lst))))))))\n"], ["#lang racket\n;; Given the lengths of the three sides of a triangle. Return the area of\n;; the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n;; Otherwise return -1\n;; Three sides make a valid triangle when the sum of any two sides is greater \n;; than the third side.\n;; Example:\n;; >>> (triangle_area 3 4 5)\n;; 6.0\n;; >>> (triangle_area 1 2 10)\n;; -1\n(define (triangle_area a b c)\n (if (and (> (+ a b) c) (> (+ a c) b) (> (+ b c) a))\n (round (/ (sqrt (* (- (* a a) (* b b)) (* (- a a) (* c c)))) 4) 100)\n -1))\n"], ["#lang racket\n;; Write a function that returns #t if the object q will fly, and #f otherwise.\n;; The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n;; Example:\n;; >>> (will_it_fly (list 1 2) 5)\n;; #f\n;; # 1+2 is less than the maximum possible weight, but it's unbalanced.\n;; >>> (will_it_fly (list 3 2 3) 1)\n;; #f\n;; # it's balanced, but 3+2+3 is more than the maximum possible weight.\n;; >>> (will_it_fly (list 3 2 3) 9)\n;; #t\n;; # 3+2+3 is less than the maximum possible weight, and it's balanced.\n;; >>> (will_it_fly (list 3) 5)\n;; #t\n;; # 3 is less than the maximum possible weight, and it's balanced.\n(define (will_it_fly q w)\n (let ((sum (apply + q)))\n (and (<= sum w) (equal? q (reverse q)))))\n"], ["#lang racket\n;; Given a list arr of integers, find the minimum number of elements that\n;; need to be changed to make the list palindromic. A palindromic list is a list that\n;; is read the same backwards and forwards. In one change, you can change one element to any other element.\n;; For example:\n;; >>> (smallest_change (list 1 2 3 5 4 7 9 6))\n;; 4\n;; >>> (smallest_change (list 1 2 3 4 3 2 2))\n;; 1\n;; >>> (smallest_change (list 1 2 3 2 1))\n;; 0\n(define (smallest_change arr)\n (let loop ((i 0) (j (- (length arr) 1)) (count 0))\n (cond\n ((>= i j) count)\n ((= (list-ref arr i) (list-ref arr j)) (loop (+ i 1) (- j 1) count))\n (else (loop (+ i 1) (- j 1) (+ count 1))))))\n"], ["#lang racket\n;; Write a function that accepts two lists of strings and returns the list that has \n;; total number of chars in the all strings of the list less than the other list.\n;; if the two lists have the same number of chars, return the first list.\n;; Examples\n;; >>> (total_match (list ) (list ))\n;; (list )\n;; >>> (total_match (list \"hi\" \"admin\") (list \"hI\" \"Hi\"))\n;; (list \"hI\" \"Hi\")\n;; >>> (total_match (list \"hi\" \"admin\") (list \"hi\" \"hi\" \"admin\" \"project\"))\n;; (list \"hi\" \"admin\")\n;; >>> (total_match (list \"hi\" \"admin\") (list \"hI\" \"hi\" \"hi\"))\n;; (list \"hI\" \"hi\" \"hi\")\n;; >>> (total_match (list \"4\") (list \"1\" \"2\" \"3\" \"4\" \"5\"))\n;; (list \"4\")\n(define (total_match lst1 lst2)\n (let ((total1 (apply + (map string-length lst1)))\n (total2 (apply + (map string-length lst2))))\n (if (< total1 total2)\n lst1\n lst2)))\n"], ["#lang racket\n;; Write a function that returns true if the given number is the multiplication of 3 prime numbers\n;; and false otherwise.\n;; Knowing that (a) is less then 100. \n;; Example:\n;; >>> (is_multiply_prime 30)\n;; #t\n;; 30 = 2 * 3 * 5\n(define (is_multiply_prime a)\n (define (prime? n)\n (define (helper i)\n (cond ((> (* i i) n) #t)\n ((zero? (modulo n i)) #f)\n (else (helper (+ i 1)))))\n (helper 2))\n (define (multiply-primes n)\n (define (helper i)\n (cond ((> i n) #f)\n ((and (prime? i) (multiply-primes (/ n i))) #t)\n (else (helper (+ i 1)))))\n (cond ((= n 1) #t)\n ((prime? n) #t)\n (else (helper 2))))\n (and (< a 100) (multiply-primes a)))\n"], ["#lang racket\n;; Your task is to write a function that returns true if a number x is a simple\n;; power of n and false in other cases.\n;; x is a simple power of n if n**int=x\n;; For example:\n;; >>> (is_simple_power 1 4)\n;; #t\n;; >>> (is_simple_power 2 2)\n;; #t\n;; >>> (is_simple_power 8 2)\n;; #t\n;; >>> (is_simple_power 3 2)\n;; #f\n;; >>> (is_simple_power 3 1)\n;; #f\n;; >>> (is_simple_power 5 3)\n;; #f\n(define (is_simple_power x n)\n (let loop ((i 0))\n (cond\n ((= (expt n i) x) #t)\n ((> (expt n i) x) #f)\n (else (loop (+ i 1))))))\n"], ["#lang racket\n;; Write a function that takes an integer a and returns #t \n;; if this ingeger is a cube of some integer number.\n;; Note: you may assume the input is always valid.\n;; Examples:\n;; >>> (iscube 1)\n;; #t\n;; >>> (iscube 2)\n;; #f\n;; >>> (iscube -1)\n;; #t\n;; >>> (iscube 64)\n;; #t\n;; >>> (iscube 0)\n;; #t\n;; >>> (iscube 180)\n;; #f\n(define (iscube a)\n (let ((cube-root (expt a (/ 1 3))))\n (= a (* cube-root cube-root cube-root))))\n"], ["#lang racket\n;; You have been tasked to write a function that receives \n;; a hexadecimal number as a string and counts the number of hexadecimal \n;; digits that are primes (prime number, or a prime, is a natural number \n;; greater than 1 that is not a product of two smaller natural numbers).\n;; Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n;; Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n;; So you have to determine a number of the following digits: 2, 3, 5, 7, \n;; B (=decimal 11), D (=decimal 13).\n;; Note: you may assume the input is always correct or empty string, \n;; and symbols A,B,C,D,E,F are always uppercase.\n;; Examples:\n;; >>> (hex_key \"AB\")\n;; 1\n;; >>> (hex_key \"1077E\")\n;; 2\n;; >>> (hex_key \"ABED1A33\")\n;; 4\n;; >>> (hex_key \"123456789ABCDEF0\")\n;; 6\n;; >>> (hex_key \"2020\")\n;; 2\n(define (hex_key num)\n (let ((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))\n (count (lambda (x) (member x primes)) (map string->number (map string (string->list num))))))\n"], ["#lang racket\n;; You will be given a number in decimal form and your task is to convert it to\n;; binary format. The function should return a string, with each character representing a binary\n;; number. Each character in the string will be '0' or '1'.\n;; There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n;; The extra characters are there to help with the format.\n;; Examples:\n;; >>> (decimal_to_binary 15)\n;; \"db1111db\"\n;; >>> (decimal_to_binary 32)\n;; \"db100000db\"\n(define (decimal_to_binary decimal)\n (string-append \"db\" (number->string decimal 2) \"db\"))\n"], ["#lang racket\n;; Filter an input list of strings only for ones that contain given substring\n;; >>> (filter_by_substring (list ) \"a\")\n;; (list )\n;; >>> (filter_by_substring (list \"abc\" \"bacd\" \"cde\" \"array\") \"a\")\n;; (list \"abc\" \"bacd\" \"array\")\n(define (filter_by_substring strings substring)\n (filter (lambda (s) (string-contains? s substring)) strings))\n"], ["#lang racket\n;; You are given a string s.\n;; Your task is to check if the string is haprkt or not.\n;; A string is haprkt if its length is at least 3 and every 3 consecutive letters are distinct\n;; For example:\n;; >>> (is_happy \"a\")\n;; #f\n;; >>> (is_happy \"aa\")\n;; #f\n;; >>> (is_happy \"abcd\")\n;; #t\n;; >>> (is_happy \"aabb\")\n;; #f\n;; >>> (is_happy \"adb\")\n;; #t\n;; >>> (is_happy \"xyy\")\n;; #f\n(define (is_happy s)\n (and (>= (string-length s) 3)\n (for/and ([i (in-range (- (string-length s) 2))])\n (not (equal? (string-ref s i) (string-ref s (+ i 1)) (string-ref s (+ i 2)))))))\n"], ["#lang racket\n;; It is the last week of the semester and the teacher has to give the grades\n;; to students. The teacher has been making her own algorithm for grading.\n;; The only problem is, she has lost the code she used for grading.\n;; She has given you a list of GPAs for some students and you have to write \n;; a function that can output a list of letter grades using the following table:\n;; GPA | Letter grade\n;; 4.0 A+\n;; > 3.7 A \n;; > 3.3 A- \n;; > 3.0 B+\n;; > 2.7 B \n;; > 2.3 B-\n;; > 2.0 C+\n;; > 1.7 C\n;; > 1.3 C-\n;; > 1.0 D+ \n;; > 0.7 D \n;; > 0.0 D-\n;; 0.0 E\n;; Example:\n;; >>> (grade_equation (list 4.0 3 1.7 2 3.5))\n;; (list \"A+\" \"B\" \"C-\" \"C\" \"A-\")\n(define (numerical_letter_grade grades)\n (map (lambda (gpa)\n (cond\n [(>= gpa 4.0) \"A+\"]\n [(>= gpa 3.7) \"A\"]\n [(>= gpa 3.3) \"A-\"]\n [(>= gpa 3.0) \"B+\"]\n [(>= gpa 2.7) \"B\"]\n [(>= gpa 2.3) \"B-\"]\n [(>= gpa 2.0) \"C+\"]\n [(>= gpa 1.7) \"C\"]\n [(>= gpa 1.3) \"C-\"]\n [(>= gpa 1.0) \"D+\"]\n [(>= gpa 0.7) \"D\"]\n [(>= gpa 0.0) \"D-\"]\n [else \"E\"]))\n grades))\n"], ["#lang racket\n;; Write a function that takes a string and returns #t if the string\n;; length is a prime number or #f otherwise\n;; Examples\n;; >>> (prime_length \"Hello\")\n;; #t\n;; >>> (prime_length \"abcdcba\")\n;; #t\n;; >>> (prime_length \"kittens\")\n;; #t\n;; >>> (prime_length \"orange\")\n;; #f\n(define (prime_length string)\n (define (prime? n)\n (define (helper i)\n (cond\n [(> (* i i) n) #t]\n [(zero? (modulo n i)) #f]\n [else (helper (+ i 1))]))\n (if (< n 2)\n #f\n (helper 2)))\n (prime? (string-length string)))\n"], ["#lang racket\n;; Given a positive integer n, return the count of the numbers of n-digit\n;; positive integers that start or end with 1.\n(define (starts_one_ends n)\n (if (= n 1)\n 2\n (+ (expt 2 (- n 2)) 2)))\n"], ["#lang racket\n;; Given a positive integer N, return the total sum of its digits in binary.\n;; Example\n;; >>> (solve 1000)\n;; \"1\"\n;; >>> (solve 150)\n;; \"110\"\n;; >>> (solve 147)\n;; \"1100\"\n;; Variables:\n;; @N integer\n;; Constraints: 0 \u2264 N \u2264 10000.\n;; Output:\n;; a string of binary number\n(define (solve N)\n (number->string (string->number (number->string (sum-digits N) 2))))\n"], ["#lang racket\n;; Given a non-empty list of integers lst. add the even elements that are at odd indices..\n;; Examples:\n;; >>> (add (list 4 2 6 7))\n;; 2\n(define (add lst)\n (let loop ((lst lst) (index 0) (sum 0))\n (cond\n [(null? lst) sum]\n [(odd? index) (loop (cdr lst) (+ index 1) (+ sum (car lst)))]\n [else (loop (cdr lst) (+ index 1) sum)])))\n"], ["#lang racket\n;; Write a function that takes a string and returns an ordered version of it.\n;; Ordered version of string, is a string where all words (separated by space)\n;; are replaced by a new word where all the characters arranged in\n;; ascending order based on ascii value.\n;; Note: You should keep the order of words and blank spaces in the sentence.\n;; For example:\n;; >>> (anti_shuffle \"Hi\")\n;; \"Hi\"\n;; >>> (anti_shuffle \"hello\")\n;; \"ehllo\"\n;; >>> (anti_shuffle \"Hello World!!!\")\n;; \"Hello !!!Wdlor\"\n(define (anti_shuffle s)\n (string-join\n (map (lambda (word)\n (list->string (sort (string->list word) char>> (get_row (list (list 1 2 3 4 5 6) (list 1 2 3 4 1 6) (list 1 2 3 4 5 1)) 1)\n;; (list (list 0 0) (list 1 4) (list 1 0) (list 2 5) (list 2 0))\n;; >>> (get_row (list ) 1)\n;; (list )\n;; >>> (get_row (list (list ) (list 1) (list 1 2 3)) 3)\n;; (list (list 2 2))\n(define (get_row lst x)\n (let loop ((lst lst) (row 0) (result '()))\n (if (null? lst)\n (sort result (lambda (a b)\n (or (< (car a) (car b))\n (and (= (car a) (car b))\n (> (cadr a) (cadr b))))))\n (let ((col (member x (car lst))))\n (if col\n (loop (cdr lst) (+ row 1) (cons (list row (- (length (car lst)) (length col))) result))\n (loop (cdr lst) (+ row 1) result))))))\n"], ["#lang racket\n;; Given a list of non-negative integers, return a corkt of the given list after sorting,\n;; you will sort the given list in ascending order if the sum( first index value, last index value) is odd,\n;; or sort it in descending order if the sum( first index value, last index value) is even.\n;; Note:\n;; * don't change the given list.\n;; Examples:\n;; >>> (sort_array (list ))\n;; (list )\n;; >>> (sort_array (list 5))\n;; (list 5)\n;; >>> (sort_array (list 2 4 3 0 1 5))\n;; (list 0 1 2 3 4 5)\n;; >>> (sort_array (list 2 4 3 0 1 5 6))\n;; (list 6 5 4 3 2 1 0)\n(define (sort_array array)\n (let ((sum (+ (car array) (last array))))\n (if (odd? sum)\n (sort array <)\n (sort array >))))\n"], ["#lang racket\n;; Create a function encrypt that takes a string as an argument and\n;; returns a string encrypted with the alphabet being rotated. \n;; The alphabet should be rotated in a manner such that the letters \n;; shift down by two multiplied to two places.\n;; For example:\n;; >>> (encrypt \"hi\")\n;; \"lm\"\n;; >>> (encrypt \"asdfghjkl\")\n;; \"ewhjklnop\"\n;; >>> (encrypt \"gf\")\n;; \"kj\"\n;; >>> (encrypt \"et\")\n;; \"ix\"\n(define (encrypt s)\n (define alphabet \"abcdefghijklmnopqrstuvwxyz\")\n (define rotated-alphabet (substring alphabet 2 (string-length alphabet)))\n (define (rotate-char c)\n (let ((index (string-index alphabet c)))\n (if index\n (string-ref rotated-alphabet index)\n c)))\n (string-map rotate-char s))\n"], ["#lang racket\n;; For a given list of integers, return a list consisting of a sum and a product of all the integers in a list.\n;; Empty sum should be equal to 0 and empty product should be equal to 1.\n;; >>> (sum_product (list ))\n;; (list 0 1)\n;; >>> (sum_product (list 1 2 3 4))\n;; (list 10 24)\n(define (sum_product numbers)\n (if (empty? numbers)\n (list 0 1)\n (list (apply + numbers) (apply * numbers))))\n"], ["#lang racket\n;; You are given a list of integers.\n;; Write a function next_smallest() that returns the 2nd smallest element of the list.\n;; Return #f if there is no such element.\n;; >>> (next_smallest (list 1 2 3 4 5))\n;; 2\n;; >>> (next_smallest (list 5 1 4 3 2))\n;; 2\n;; >>> (next_smallest (list ))\n;; #f\n;; >>> (next_smallest (list 1 1))\n;; #f\n(define (next_smallest lst)\n (define (helper lst smallest second_smallest)\n (cond\n ((null? lst) (if (= smallest second_smallest) #f second_smallest))\n ((< (car lst) smallest) (helper (cdr lst) (car lst) smallest))\n ((< (car lst) second_smallest) (helper (cdr lst) smallest (car lst)))\n (else (helper (cdr lst) smallest second_smallest))))\n (helper lst (car lst) (car lst)))\n"], ["#lang racket\n;; You'll be given a string of words, and your task is to count the number\n;; of boredoms. A boredom is a sentence that starts with the word \"I\".\n;; Sentences are delimited by '.', '?' or '!'.\n;; For example:\n;; >>> (is_bored \"Hello world\")\n;; 0\n;; >>> (is_bored \"The sky is blue. The sun is shining. I love this weather\")\n;; 1\n(define (is_bored S)\n (let ((sentences (regexp-split #rx\"[.?!]\" S)))\n (count (lambda (s) (regexp-match #rx\"^I\" s)) sentences)))\n"], ["#lang racket\n;; Create a function that takes 3 numbers.\n;; Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n;; Returns false in any other cases.\n;; Examples\n;; >>> (any_int 5 2 7)\n;; #t\n;; >>> (any_int 3 2 2)\n;; #f\n;; >>> (any_int 3 -2 1)\n;; #t\n;; >>> (any_int 3.6 -2.2 2)\n;; #f\n(define (any_int x y z)\n (and (integer? x) (integer? y) (integer? z)\n (or (= x (+ y z)) (= y (+ x z)) (= z (+ x y)))))\n"], ["#lang racket\n;; Write a function that takes a message, and encodes in such a \n;; way that it swaps case of all letters, replaces all vowels in \n;; the message with the letter that appears 2 places ahead of that \n;; vowel in the english alphabet. \n;; Assume only letters. \n;; Examples:\n;; >>> (encode \"test\")\n;; \"TGST\"\n;; >>> (encode \"This is a message\")\n;; \"tHKS KS C MGSSCGG\"\n(define (encode message)\n (define vowels \"aeiouAEIOU\")\n (define (swap-case c)\n (if (char-lower-case? c)\n (char-upcase c)\n (char-downcase c)))\n (define (vowel-shift c)\n (define index (string-index vowels c))\n (if index\n (string-ref vowels (modulo (+ index 2) 10))\n c))\n (list->string\n (map (lambda (c)\n (if (char-alphabetic? c)\n (vowel-shift (swap-case c))\n c))\n (string->list message))))\n"], ["#lang racket\n;; You are given a list of integers.\n;; You need to find the largest prime value and return the sum of its digits.\n;; Examples:\n;; >>> (skjkasdkd (list 0 3 2 1 3 5 7 4 5 5 5 2 181 32 4 32 3 2 32 324 4 3))\n;; 10\n;; >>> (skjkasdkd (list 1 0 1 8 2 4597 2 1 3 40 1 2 1 2 4 2 5 1))\n;; 25\n;; >>> (skjkasdkd (list 1 3 1 32 5107 34 83278 109 163 23 2323 32 30 1 9 3))\n;; 13\n;; >>> (skjkasdkd (list 0 724 32 71 99 32 6 0 5 91 83 0 5 6))\n;; 11\n;; >>> (skjkasdkd (list 0 81 12 3 1 21))\n;; 3\n;; >>> (skjkasdkd (list 0 8 1 2 1 7))\n;; 7\n(define (skjkasdkd lst)\n (define (prime? n)\n (define (helper i)\n (cond ((> (* i i) n) #t)\n ((zero? (modulo n i)) #f)\n (else (helper (+ i 1)))))\n (if (< n 2)\n #f\n (helper 2)))\n (define (sum-digits n)\n (if (< n 10)\n n\n (+ (modulo n 10) (sum-digits (quotient n 10)))))\n (define (largest-prime lst)\n (cond ((null? lst) 0)\n ((prime? (car lst)) (max (car lst) (largest-prime (cdr lst))))\n (else (largest-prime (cdr lst)))))\n (sum-digits (largest-prime lst)))\n"], ["#lang racket\n;; Given a hash, return #t if all keys are strings in lower \n;; case or all keys are strings in upper case, else return #f.\n;; The function should return #f is the given hash is empty.\n;; Examples:\n;; >>> (check_dict_case #hash((\"a\" . \"apple\") (\"b\" . \"banana\")))\n;; #t\n;; >>> (check_dict_case #hash((\"a\" . \"apple\") (\"A\" . \"banana\") (\"B\" . \"banana\")))\n;; #f\n;; >>> (check_dict_case #hash((\"a\" . \"apple\") (8 . \"banana\") (\"a\" . \"apple\")))\n;; #f\n;; >>> (check_dict_case #hash((\"Name\" . \"John\") (\"Age\" . \"36\") (\"City\" . \"Houston\")))\n;; #f\n;; >>> (check_dict_case #hash((\"STATE\" . \"NC\") (\"ZIP\" . \"12345\")))\n;; #t\n(define (check_dict_case dict)\n (cond\n [(empty? dict) #f]\n [(andmap string? (hash-keys dict))\n (let ([keys (hash-keys dict)])\n (or (andmap string-lower-case? keys)\n (andmap string-upper-case? keys)))]\n [else #f]))\n"], ["#lang racket\n;; Implement a function that takes an non-negative integer and returns a list of the first n\n;; integers that are prime numbers and less than n.\n;; for example:\n;; >>> (count_up_to 5)\n;; (list 2 3)\n;; >>> (count_up_to 11)\n;; (list 2 3 5 7)\n;; >>> (count_up_to 0)\n;; (list )\n;; >>> (count_up_to 20)\n;; (list 2 3 5 7 11 13 17 19)\n;; >>> (count_up_to 1)\n;; (list )\n;; >>> (count_up_to 18)\n;; (list 2 3 5 7 11 13 17)\n(define (count_up_to n)\n (define (prime? x)\n (define (helper y)\n (cond\n ((> (* y y) x) #t)\n ((zero? (modulo x y)) #f)\n (else (helper (+ y 1)))))\n (if (< x 2)\n #f\n (helper 2)))\n (define (helper i lst)\n (cond\n ((= i n) lst)\n ((prime? i) (helper (+ i 1) (append lst (list i))))\n (else (helper (+ i 1) lst))))\n (helper 2 '()))\n"], ["#lang racket\n;; Complete the function that takes two integers and returns \n;; the product of their unit digits.\n;; Assume the input is always valid.\n;; Examples:\n;; >>> (multiply 148 412)\n;; 16\n;; >>> (multiply 19 28)\n;; 72\n;; >>> (multiply 2020 1851)\n;; 0\n;; >>> (multiply 14 -15)\n;; 20\n(define (multiply a b)\n (* (modulo a 10) (modulo b 10)))\n"], ["#lang racket\n;; Given a string s, count the number of uppercase vowels in even indices.\n;; For example:\n;; >>> (count_upper \"aBCdEf\")\n;; 1\n;; >>> (count_upper \"abcdefg\")\n;; 0\n;; >>> (count_upper \"dBBE\")\n;; 0\n(define (count_upper s)\n (let loop ((i 0) (count 0))\n (if (>= i (string-length s))\n count\n (loop (+ i 2) (if (and (even? i) (char-upper-case? (string-ref s i)))\n (+ count 1)\n count)))))\n"], ["#lang racket\n;; Create a function that takes a value (string) representing a number\n;; and returns the closest integer to it. If the number is equidistant\n;; from two integers, round it away from zero.\n;; Examples\n;; >>> (closest_integer \"10\")\n;; 10\n;; >>> (closest_integer \"15.3\")\n;; 15\n;; Note:\n;; Rounding away from zero means that if the given number is equidistant\n;; from two integers, the one you should return is the one that is the\n;; farthest from zero. For example closest_integer(\"14.5\") should\n;; return 15 and closest_integer(\"-14.5\") should return -15.\n(define (closest_integer value)\n (let ((num (string->number value)))\n (if (< (abs (- num (floor num))) (abs (- num (ceiling num))))\n (floor num)\n (ceiling num))))\n"], ["#lang racket\n;; From a given list of integers, generate a list of rolling maximum element found until given moment\n;; in the sequence.\n;; >>> (rolling_max (list 1 2 3 2 3 4 2))\n;; (list 1 2 3 3 3 4 4)\n(define (rolling_max numbers)\n (let loop ((nums numbers) (max (car numbers)) (result (list max)))\n (if (null? (cdr nums))\n (reverse result)\n (loop (cdr nums) (max (car nums) max) (cons (max (car nums) max) result)))))\n"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rs_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rs_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..645a0eb41404cb071e6535f617784a22f400170b --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-rs_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["/// Check if in given vector of numbers, are any two numbers closer to each other than\n/// given threshold.\n/// >>> has_close_elements(vec![1.0, 2.0, 3.0], 0.5)\n/// false\n/// >>> has_close_elements(vec![1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n/// true\nfn has_close_elements(numbers: Vec, threshold: f64) -> bool {\n for i in 0..numbers.len() {\n for j in i+1..numbers.len() {\n if (numbers[i] - numbers[j]).abs() < threshold {\n return true;\n }\n }\n }\n false"], ["/// Given a positive integer n, you have to make a pile of n levels of stones.\n/// The first level has n stones.\n/// The number of stones in the next level is:\n/// - the next odd number if n is odd.\n/// - the next even number if n is even.\n/// Return the number of stones in each level in a vector, where element at index\n/// i represents the number of stones in the level (i+1).\n/// Examples:\n/// >>> make_a_pile(3)\n/// vec![3, 5, 7]\nfn make_a_pile(n: isize) -> Vec {\n let mut stones = Vec::new();\n let mut level = n;\n while level > 0 {\n stones.push(level);\n level = if n % 2 == 0 { level - 2 } else { level - 2 };\n }\n stones"], ["/// You will be given a string of words separated by commas or spaces. Your task is\n/// to split the string into words and return a vector of the words.\n/// For example:\n/// >>> words_string(String::from(\"Hi, my name is John\"))\n/// vec![String::from(\"Hi\"), String::from(\"my\"), String::from(\"name\"), String::from(\"is\"), String::from(\"John\")]\n/// >>> words_string(String::from(\"One, two, three, four, five, six\"))\n/// vec![String::from(\"One\"), String::from(\"two\"), String::from(\"three\"), String::from(\"four\"), String::from(\"five\"), String::from(\"six\")]\nfn words_string(s: String) -> Vec {\n s.split_whitespace().map(|x| x.to_string()).collect()"], ["/// This function takes two positive numbers x and y and returns the\n/// biggest even integer number that is in the range [x, y] inclusive. If \n/// there's no such number, then the function should return -1.\n/// For example:\n/// >>> choose_num(12, 15)\n/// 14\n/// >>> choose_num(13, 12)\n/// -1\nfn choose_num(x: isize, y: isize) -> isize {\n if x % 2 != 0 {\n x += 1;\n }\n if x > y {\n return -1;\n }\n x"], ["/// Given a vector of positive integers x. return a sorted vector of all \n/// elements that hasn't any even digit.\n/// Note: Returned vector should be sorted in increasing order.\n/// For example:\n/// >>> unique_digits(vec![15, 33, 1422, 1])\n/// vec![1, 15, 33]\n/// >>> unique_digits(vec![152, 323, 1422, 10])\n/// Vec::::new()\nfn unique_digits(x: Vec) -> Vec {\n let mut result = Vec::new();\n for num in x {\n let mut has_even_digit = false;\n let mut n = num;\n while n > 0 {\n let digit = n % 10;\n if digit % 2 == 0 {\n has_even_digit = true;\n break;\n }\n n /= 10;\n }\n if !has_even_digit {\n result.push(num);\n }\n }\n result.sort();\n result"], ["/// Given a vector of integers, sort the integers that are between 1 and 9 inclusive,\n/// reverse the resulting vector, and then replace each digit by its corresponding name from\n/// \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n/// For example:\n/// >>> by_length(vec![2, 1, 1, 4, 5, 8, 2, 3])\n/// vec![String::from(\"Eight\"), String::from(\"Five\"), String::from(\"Four\"), String::from(\"Three\"), String::from(\"Two\"), String::from(\"Two\"), String::from(\"One\"), String::from(\"One\")]\n/// If the vector is empty, return an empty vector:\n/// >>> by_length(vec![])\n/// Vec::::new()\n/// If the vector has any strange number ignore it:\n/// >>> by_length(vec![1, -1, 55])\n/// vec![String::from(\"One\")]\nfn by_length(arr: Vec) -> Vec {\n let mut result = Vec::new();\n for i in arr {\n if i >= 1 && i <= 9 {\n result.push(i.to_string());\n }\n }\n result.sort_by(|a, b| b.cmp(a));\n result.iter_mut().for_each(|s| {\n *s = match s.as_str() {\n \"1\" => \"One\",\n \"2\" => \"Two\",\n \"3\" => \"Three\",\n \"4\" => \"Four\",\n \"5\" => \"Five\",\n \"6\" => \"Six\",\n \"7\" => \"Seven\",\n \"8\" => \"Eight\",\n \"9\" => \"Nine\",\n _ => \"\",\n }.to_string();\n });\n result"], ["/// Implement the function f that takes n as a parameter,\n/// and returns a vector of size n, such that the value of the element at index i is the factorial of i if i is even\n/// or the sum of numbers from 1 to i otherwise.\n/// i starts from 1.\n/// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n/// Example:\n/// >>> f(5)\n/// vec![1, 2, 6, 24, 15]\nfn f(n: isize) -> Vec {\n let mut result = Vec::new();\n for i in 1..=n {\n if i % 2 == 0 {\n let mut factorial = 1;\n for j in 1..=i {\n factorial *= j;\n }\n result.push(factorial);\n } else {\n let sum = (1..=i).sum();\n result.push(sum);\n }\n }\n result"], ["/// Given a positive integer n, return a tuple that has the number of even and odd\n/// integer palindromes that fall within the range(1, n), inclusive.\n/// Example 1:\n/// >>> even_odd_palindrome(3)\n/// (1, 2)\n/// Explanation:\n/// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n/// Example 2:\n/// >>> even_odd_palindrome(12)\n/// (4, 6)\n/// Explanation:\n/// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n/// Note:\n/// 1. 1 <= n <= 10^3\n/// 2. returned tuple has the number of even and odd integer palindromes respectively.\nfn even_odd_palindrome(n: isize) -> (isize, isize) {\n let mut even = 0;\n let mut odd = 0;\n for i in 1..=n {\n let s = i.to_string();\n if s == s.chars().rev().collect::() {\n if i % 2 == 0 {\n even += 1;\n } else {\n odd += 1;\n }\n }\n }\n (even, odd)"], ["/// Write a function count_nums which takes a vector of integers and returns\n/// the number of elements which has a sum of digits > 0.\n/// If a number is negative, then its first signed digit will be negative:\n/// e.g. -123 has signed digits -1, 2, and 3.\n/// >>> count_nums(vec![])\n/// 0\n/// >>> count_nums(vec![-1, 11, -11])\n/// 1\n/// >>> count_nums(vec![1, 1, 2])\n/// 3\nfn count_nums(arr: Vec) -> isize {\n let mut count = 0;\n for num in arr {\n let mut sum = 0;\n let mut n = num;\n if n < 0 {\n sum += n % 10;\n n /= 10;\n }\n while n != 0 {\n sum += n % 10;\n n /= 10;\n }\n if sum > 0 {\n count += 1;\n }\n }\n count"], ["/// We have a vector 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n/// numbers in the vector will be randomly ordered. Your task is to determine if\n/// it is possible to get a vector sorted in non-decreasing order by performing \n/// the following operation on the given vector:\n/// You are allowed to perform right shift operation any number of times.\n/// One right shift operation means shifting all elements of the vector by one\n/// position in the right direction. The last element of the vector will be moved to\n/// the starting position in the vector i.e. 0th index. \n/// If it is possible to obtain the sorted vector by performing the above operation\n/// then return true else return false.\n/// If the given vector is empty then return true.\n/// Note: The given vector is guaranteed to have unique elements.\n/// For Example:\n/// >>> move_one_ball(vec![3, 4, 5, 1, 2])\n/// true\n/// Explanation: By performin 2 right shift operations, non-decreasing order can\n/// be achieved for the given vector.\n/// >>> move_one_ball(vec![3, 5, 4, 1, 2])\n/// false\n/// Explanation:It is not possible to get non-decreasing order for the given\n/// vector by performing any number of right shift operations.\nfn move_one_ball(arr: Vec) -> bool {\n if arr.is_empty() {\n return true;\n }\n let mut sorted = arr.clone();\n sorted.sort();\n let mut count = 0;\n for i in 0..arr.len() {\n if arr[i] != sorted[i] {\n count += 1;\n }\n }\n count <= 2"], ["/// Find the shortest palindrome that begins with a supplied string.\n/// Algorithm idea is simple:\n/// - Find the longest postfix of supplied string that is a palindrome.\n/// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n/// >>> make_palindrome(String::from(\"\"))\n/// String::from(\"\")\n/// >>> make_palindrome(String::from(\"cat\"))\n/// String::from(\"catac\")\n/// >>> make_palindrome(String::from(\"cata\"))\n/// String::from(\"catac\")\nfn make_palindrome(string: String) -> String {\n let mut longest_palindrome = String::new();\n let mut longest_palindrome_length = 0;\n\n for i in 0..string.len() {\n let suffix = &string[i..];\n if is_palindrome(suffix) {\n let prefix = &string[0..i];\n let reversed_prefix: String = prefix.chars().rev().collect();\n let palindrome = format!(\"{}{}\", string, reversed_prefix);\n if palindrome.len() > longest_palindrome_length {\n longest_palindrome = palindrome;\n longest_palindrome_length = palindrome.len();\n }\n }\n }\n\n longest_palindrome"], ["/// In this problem, you will implement a function that takes two vectors of numbers,\n/// and determines whether it is possible to perform an exchange of elements\n/// between them to make lst1 a vector of only even numbers.\n/// There is no limit on the number of exchanged elements between lst1 and lst2.\n/// If it is possible to exchange elements between the lst1 and lst2 to make\n/// all the elements of lst1 to be even, return \"YES\".\n/// Otherwise, return \"NO\".\n/// For example:\n/// >>> exchange(vec![1, 2, 3, 4], vec![1, 2, 3, 4])\n/// String::from(\"YES\")\n/// >>> exchange(vec![1, 2, 3, 4], vec![1, 5, 3, 4])\n/// String::from(\"NO\")\n/// It is assumed that the input vectors will be non-empty.\nfn exchange(lst1: Vec, lst2: Vec) -> String {\n let mut even_count = 0;\n let mut odd_count = 0;\n\n for num in lst1 {\n if num % 2 == 0 {\n even_count += 1;\n } else {\n odd_count += 1;\n }\n }\n\n for num in lst2 {\n if num % 2 == 0 {\n even_count += 1;\n } else {\n odd_count += 1;\n }\n }\n\n if even_count == lst1.len() {\n return String::from(\"YES\");\n } else if odd_count == lst1.len() {\n return String::from(\"NO\");\n } else {\n return String::from(\"YES\");\n }"], ["use std::collections::HashMap;\n\n/// Given a string representing a space separated lowercase letters, return a HashMap\n/// of the letter with the most repetition and containing the corresponding count.\n/// If several letters have the same occurrence, return all of them.\n/// Example:\n/// >>> histogram(String::from(\"a b c\"))\n/// HashMap::from([(String::from(\"a\"), 1), (String::from(\"b\"), 1), (String::from(\"c\"), 1)])\n/// >>> histogram(String::from(\"a b b a\"))\n/// HashMap::from([(String::from(\"a\"), 2), (String::from(\"b\"), 2)])\n/// >>> histogram(String::from(\"a b c a b\"))\n/// HashMap::from([(String::from(\"a\"), 2), (String::from(\"b\"), 2)])\n/// >>> histogram(String::from(\"b b b b a\"))\n/// HashMap::from([(String::from(\"b\"), 4)])\n/// >>> histogram(String::from(\"\"))\n/// HashMap::from([])\nfn histogram(test: String) -> HashMap {\n let mut map = HashMap::new();\n let mut max_count = 0;\n for word in test.split_whitespace() {\n let count = map.entry(word.to_string()).or_insert(0);\n *count += 1;\n if *count > max_count {\n max_count = *count;\n }\n }\n let mut result = HashMap::new();\n for (key, value) in map {\n if value == max_count {\n result.insert(key, value);\n }\n }\n result"], ["/// Task\n/// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n/// then check if the result string is palindrome.\n/// A string is called palindrome if it reads the same backward as forward.\n/// You should return a tuple containing the result string and true/false for the check.\n/// Example\n/// >>> reverse_delete(String::from(\"abcde\"), String::from(\"ae\"))\n/// (String::from(\"bcd\"), false)\n/// >>> reverse_delete(String::from(\"abcdef\"), String::from(\"b\"))\n/// (String::from(\"acdef\"), false)\n/// >>> reverse_delete(String::from(\"abcdedcba\"), String::from(\"ab\"))\n/// (String::from(\"cdedc\"), true)\nfn reverse_delete(s: String, c: String) -> (String, bool) {\n let mut result = String::new();\n for ch in s.chars() {\n if !c.contains(ch) {\n result.push(ch);\n }\n }\n let is_palindrome = result == result.chars().rev().collect::();\n (result, is_palindrome)"], ["/// Given a vector of strings, where each string consists of only digits, return a vector.\n/// Each element i of the output should be \"the number of odd elements in the\n/// string i of the input.\" where all the i's should be replaced by the number\n/// of odd digits in the i'th string of the input.\n/// >>> odd_count(vec![String::from(\"1234567\")])\n/// vec![String::from(\"the number of odd elements 4n the str4ng 4 of the 4nput.\")]\n/// >>> odd_count(vec![String::from(\"3\"), String::from(\"11111111\")])\n/// vec![String::from(\"the number of odd elements 1n the str1ng 1 of the 1nput.\"), String::from(\"the number of odd elements 8n the str8ng 8 of the 8nput.\")]\nfn odd_count(lst: Vec) -> Vec {\n lst.iter()\n .map(|s| format!(\"the number of odd elements {}n the str{}ng {} of the {}nput.\", s.chars().filter(|&c| c.is_digit(10) && c.to_digit(10).unwrap() & 1 == 1).count(), s.len(), s.len(), s.len()))\n .collect()"], ["/// Given a vector of integers nums, find the minimum sum of any non-empty sub-vector\n/// of nums.\n/// Example\n/// >>> minSubArraySum(vec![2, 3, 4, 1, 2, 4])\n/// 1\n/// >>> minSubArraySum(vec![-1, -2, -3])\n/// -6\nfn minSubArraySum(nums: Vec) -> isize {\n let mut min_sum = nums[0];\n let mut cur_sum = nums[0];\n\n for i in 1..nums.len() {\n cur_sum = nums[i].min(cur_sum + nums[i]);\n min_sum = min_sum.min(cur_sum);\n }\n\n min_sum"], ["/// You are given a rectangular grid of wells. Each row represents a single well,\n/// and each 1 in a row represents a single unit of water.\n/// Each well has a corresponding bucket that can be used to extract water from it, \n/// and all buckets have the same capacity.\n/// Your task is to use the buckets to empty the wells.\n/// Output the number of times you need to lower the buckets.\n/// Example 1:\n/// >>> max_fill(vec![vec![0, 0, 1, 0], vec![0, 1, 0, 0], vec![1, 1, 1, 1]], 1)\n/// 6\n/// Example 2:\n/// >>> max_fill(vec![vec![0, 0, 1, 1], vec![0, 0, 0, 0], vec![1, 1, 1, 1], vec![0, 1, 1, 1]], 2)\n/// 5\n/// Example 3:\n/// >>> max_fill(vec![vec![0, 0, 0], vec![0, 0, 0]], 5)\n/// 0\n/// Constraints:\n/// * all wells have the same length\n/// * 1 <= grid.length <= 10^2\n/// * 1 <= grid[:,1].length <= 10^2\n/// * grid[i][j] -> 0 | 1\n/// * 1 <= capacity <= 10\nfn max_fill(grid: Vec>, capacity: isize) -> isize {\n let mut count = 0;\n let mut bucket_level = capacity;\n for row in grid {\n for well in row {\n if well == 1 {\n if bucket_level == 0 {\n bucket_level = capacity;\n count += 1;\n }\n bucket_level -= 1;\n }\n }\n }\n count"], ["/// In this Kata, you have to sort a vector of non-negative integers according to\n/// number of ones in their binary representation in ascending order.\n/// For similar number of ones, sort based on decimal value.\n/// It must be implemented like this:\n/// >>> sort_array(vec![1, 5, 2, 3, 4])\n/// vec![1, 2, 3, 4, 5]\n/// >>> sort_array(vec![-2, -3, -4, -5, -6])\n/// vec![-6, -5, -4, -3, -2]\n/// >>> sort_array(vec![1, 0, 2, 3, 4])\n/// vec![0, 1, 2, 3, 4]\nfn sort_array(arr: Vec) -> Vec {\n let mut arr = arr;\n arr.sort_by(|a, b| a.count_ones().cmp(&b.count_ones()).then(a.cmp(b)));\n arr"], ["/// Given a string s and a natural number n, you have been tasked to implement \n/// a function that returns a vector of all words from string s that contain exactly \n/// n consonants, in order these words appear in the string s.\n/// If the string s is empty then the function should return an empty vector.\n/// Note: you may assume the input string contains only letters and spaces.\n/// Examples:\n/// >>> select_words(String::from(\"Mary had a little lamb\"), 4)\n/// vec![String::from(\"little\")]\n/// >>> select_words(String::from(\"Mary had a little lamb\"), 3)\n/// vec![String::from(\"Mary\"), String::from(\"lamb\")]\n/// >>> select_words(String::from(\"simple white space\"), 2)\n/// Vec::::new()\n/// >>> select_words(String::from(\"Hello world\"), 4)\n/// vec![String::from(\"world\")]\n/// >>> select_words(String::from(\"Uncle sam\"), 3)\n/// vec![String::from(\"Uncle\")]\nfn select_words(s: String, n: isize) -> Vec {\n let mut result = Vec::new();\n let mut word = String::new();\n let mut consonant_count = 0;\n\n for c in s.chars() {\n if c.is_alphabetic() {\n word.push(c);\n if ![b'a', b'e', b'i', b'o', b'u'].contains(&c.to_ascii_lowercase().unwrap()) {\n consonant_count += 1;\n }\n } else {\n if consonant_count == n {\n result.push(word);\n }\n word = String::new();\n consonant_count = 0;\n }\n }\n\n if consonant_count == n {\n result.push(word);\n }\n\n result"], ["/// You are given a word. Your task is to find the closest vowel that stands between \n/// two consonants from the right side of the word (case sensitive).\n/// Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n/// find any vowel met the above condition. \n/// You may assume that the given string contains English letter only.\n/// Example:\n/// >>> get_closest_vowel(String::from(\"yogurt\"))\n/// String::from(\"u\")\n/// >>> get_closest_vowel(String::from(\"FULL\"))\n/// String::from(\"U\")\n/// >>> get_closest_vowel(String::from(\"quick\"))\n/// String::from(\"\")\n/// >>> get_closest_vowel(String::from(\"ab\"))\n/// String::from(\"\")\nfn get_closest_vowel(word: String) -> String {\n let vowels = vec![b'a', b'e', b'i', b'o', b'u'];\n let mut closest_vowel = b' ';\n let mut distance = word.len();\n\n for i in (1..word.len() - 1).rev() {\n if !vowels.contains(&word.as_bytes()[i]) && vowels.contains(&word.as_bytes()[i + 1]) {\n let current_distance = i + 1 - (word.len() - 1 - i);\n if current_distance < distance {\n distance = current_distance;\n closest_vowel = word.as_bytes()[i + 1];\n }\n }\n }\n\n if closest_vowel != b' ' {\n String::from_utf8(vec![closest_vowel]).unwrap()\n } else {\n String::new()\n }"], ["/// You are given a vector of two strings, both strings consist of open\n/// parentheses '(' or close parentheses ')' only.\n/// Your job is to check if it is possible to concatenate the two strings in\n/// some order, that the resulting string will be good.\n/// A string S is considered to be good if and only if all parentheses in S\n/// are balanced. For example: the string '(())()' is good, while the string\n/// '())' is not.\n/// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n/// Examples:\n/// >>> match_parens(vec![String::from(\"()(\"), String::from(\")\")])\n/// String::from(\"Yes\")\n/// >>> match_parens(vec![String::from(\")\"), String::from(\")\")])\n/// String::from(\"No\")\nfn match_parens(lst: Vec) -> String {\n let mut count = 0;\n for s in lst {\n for c in s.chars() {\n if c == '(' {\n count += 1;\n } else {\n count -= 1;\n }\n }\n }\n if count == 0 {\n String::from(\"Yes\")\n } else {\n String::from(\"No\")\n }"], ["/// Input are two strings a and b consisting only of 1s and 0s.\n/// Perform binary XOR on these inputs and return result also as a string.\n/// >>> string_xor(String::from(\"010\"), String::from(\"110\"))\n/// String::from(\"100\")\nfn string_xor(a: String, b: String) -> String {\n let mut result = String::new();\n for (c1, c2) in a.chars().zip(b.chars()) {\n let xor = if c1 == '1' ^ c2 == '1' { '1' } else { '0' };\n result.push(xor);\n }\n result"], ["/// Given a vector arr of integers and a positive integer k, return a sorted vector \n/// of length k with the maximum k numbers in arr.\n/// Example 1:\n/// >>> maximum(vec![-3, -4, 5], 3)\n/// vec![-4, -3, 5]\n/// Example 2:\n/// >>> maximum(vec![4, -4, 4], 2)\n/// vec![4, 4]\n/// Example 3:\n/// >>> maximum(vec![-3, 2, 1, 2, -1, -2, 1], 1)\n/// vec![2]\n/// Note:\n/// 1. The length of the vector will be in the range of [1, 1000].\n/// 2. The elements in the vector will be in the range of [-1000, 1000].\n/// 3. 0 <= k <= len(arr)\nfn maximum(arr: Vec, k: isize) -> Vec {\n let mut arr = arr;\n arr.sort_by(|a, b| b.cmp(a));\n arr[0..k as usize].to_vec()"], ["/// Given a non-empty vector of integers, return the sum of all of the odd elements that are in even positions.\n/// Examples\n/// >>> solution(vec![5, 8, 7, 1])\n/// 12\n/// >>> solution(vec![3, 3, 3, 3, 3])\n/// 9\n/// >>> solution(vec![30, 13, 24, 321])\n/// 0\nfn solution(lst: Vec) -> isize {\n lst.iter().enumerate()\n .filter(|&(i, _)| i % 2 == 0)\n .filter(|&(_, x)| x % 2 != 0)\n .map(|(_, x)| x)\n .sum()"], ["/// Given a non-empty vector of integers arr and an integer k, return\n/// the sum of the elements with at most two digits from the first k elements of arr.\n/// Example:\n/// >>> add_elements(vec![111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)\n/// 24\n/// Constraints:\n/// 1. 1 <= len(arr) <= 100\n/// 2. 1 <= k <= len(arr)\nfn add_elements(arr: Vec, k: isize) -> isize {\n let mut sum = 0;\n for i in 0..k {\n if arr[i] < 100 {\n sum += arr[i];\n }\n }\n sum"], ["/// Given a positive integer n, return a sorted vector that has the odd numbers in collatz sequence.\n/// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n/// as follows: start with any positive integer n. Then each term is obtained from the \n/// previous term as follows: if the previous term is even, the next term is one half of \n/// the previous term. If the previous term is odd, the next term is 3 times the previous\n/// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n/// Note: \n/// 1. Collatz(1) is [1].\n/// 2. returned vector sorted in increasing order.\n/// For example:\n/// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n/// >>> get_odd_collatz(5)\n/// vec![1, 5]\nfn get_odd_collatz(n: isize) -> Vec {\n let mut collatz_seq = vec![n];\n let mut current = n;\n while current != 1 {\n if current % 2 == 0 {\n current = current / 2;\n } else {\n current = 3 * current + 1;\n }\n collatz_seq.push(current);\n }\n collatz_seq.into_iter().filter(|&x| x % 2 != 0).collect::>()"], ["/// You have to write a function which validates a given date string and\n/// returns true if the date is valid otherwise false.\n/// The date is valid if all of the following rules are satisfied:\n/// 1. The date string is not empty.\n/// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n/// 3. The months should not be less than 1 or higher than 12.\n/// 4. The date should be in the format: mm-dd-yyyy\n/// >>> valid_date(String::from(\"03-11-2000\"))\n/// true\n/// >>> valid_date(String::from(\"15-01-2012\"))\n/// false\n/// >>> valid_date(String::from(\"04-0-2040\"))\n/// false\n/// >>> valid_date(String::from(\"06-04-2020\"))\n/// true\n/// >>> valid_date(String::from(\"06/04/2020\"))\n/// false\nfn valid_date(date: String) -> bool {\n let parts: Vec<&str> = date.split('-').collect();\n if parts.len() != 3 {\n return false;\n }\n let month = parts[0].parse::().unwrap_or(0);\n let day = parts[1].parse::().unwrap_or(0);\n let year = parts[2].parse::().unwrap_or(0);\n if month < 1 || month > 12 {\n return false;\n }\n if day < 1 || day > 31 {\n return false;\n }\n if month == 2 {\n if day > 29 {\n return false;\n }\n if day == 29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {\n return false;\n }\n } else if month == 4 || month == 6 || month == 9 || month == 11 {\n if day > 30 {\n return false;\n }\n }\n true"], ["/// Given a vector of numbers, return whether or not they are sorted\n/// in ascending order. If vector has more than 1 duplicate of the same\n/// number, return false. Assume no negative numbers and only integers.\n/// Examples\n/// >>> is_sorted(vec![5])\n/// true\n/// >>> is_sorted(vec![1, 2, 3, 4, 5])\n/// true\n/// >>> is_sorted(vec![1, 3, 2, 4, 5])\n/// false\n/// >>> is_sorted(vec![1, 2, 3, 4, 5, 6])\n/// true\n/// >>> is_sorted(vec![1, 2, 3, 4, 5, 6, 7])\n/// true\n/// >>> is_sorted(vec![1, 3, 2, 4, 5, 6, 7])\n/// false\n/// >>> is_sorted(vec![1, 2, 2, 3, 3, 4])\n/// true\n/// >>> is_sorted(vec![1, 2, 2, 2, 3, 4])\n/// false\nfn is_sorted(lst: Vec) -> bool {\n let mut prev = None;\n for &x in lst.iter() {\n if let Some(y) = prev {\n if x <= y {\n return false;\n }\n }\n prev = Some(x);\n }\n true"], ["/// You are given two intervals,\n/// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n/// The given intervals are closed which means that the interval (start, end)\n/// includes both start and end.\n/// For each given interval, it is assumed that its start is less or equal its end.\n/// Your task is to determine whether the length of intersection of these two \n/// intervals is a prime number.\n/// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n/// which its length is 1, which not a prime number.\n/// If the length of the intersection is a prime number, return \"YES\",\n/// otherwise, return \"NO\".\n/// If the two intervals don't intersect, return \"NO\".\n/// [input/output] samples:\n/// >>> intersection((1, 2), (2, 3))\n/// String::from(\"NO\")\n/// >>> intersection((-1, 1), (0, 4))\n/// String::from(\"NO\")\n/// >>> intersection((-3, -1), (-5, 5))\n/// String::from(\"YES\")\nfn intersection(interval1: (isize, isize), interval2: (isize, isize)) -> String {\n let (start1, end1) = interval1;\n let (start2, end2) = interval2;\n let start = start1.max(start2);\n let end = end1.min(end2);\n let length = end - start + 1;\n if length <= 1 {\n return String::from(\"NO\");\n }\n for i in 2..length {\n if length % i == 0 {\n return String::from(\"NO\");\n }\n }\n String::from(\"YES\")"], ["/// You are given a vector arr of integers and you need to return\n/// sum of magnitudes of integers multiplied by product of all signs\n/// of each number in the vector, represented by 1, -1 or 0.\n/// Note: return None for empty arr.\n/// Example:\n/// >>> prod_signs(vec![1, 2, 2, -4])\n/// Some(9)\n/// >>> prod_signs(vec![0, 1])\n/// Some(0)\n/// >>> prod_signs(vec![])\n/// None\nfn prod_signs(arr: Vec) -> Option {\n if arr.is_empty() {\n return None;\n }\n\n let mut sum = 0;\n let mut product = 1;\n\n for num in arr {\n sum += num.abs();\n product *= num.signum();\n }\n\n Some(sum * product)"], ["/// Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n/// each cell of the grid contains a value. Every integer in the range [1, N * N]\n/// inclusive appears exactly once on the cells of the grid.\n/// You have to find the minimum path of length k in the grid. You can start\n/// from any cell, and in each step you can move to any of the neighbor cells,\n/// in other words, you can go to cells which share an edge with you current\n/// cell.\n/// Please note that a path of length k means visiting exactly k cells (not\n/// necessarily distinct).\n/// You CANNOT go off the grid.\n/// A path A (of length k) is considered less than a path B (of length k) if\n/// after making the ordered vectors of the values on the cells that A and B go\n/// through (let's call them lst_A and lst_B), lst_A is lexicographically less\n/// than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n/// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n/// lst_A[j] = lst_B[j].\n/// It is guaranteed that the answer is unique.\n/// Return an ordered vector of the values on the cells that the minimum path go through.\n/// Examples: \n/// >>> minPath(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]], 3)\n/// vec![1, 2, 1]\n/// >>> minPath(vec![vec![5, 9, 3], vec![4, 1, 6], vec![7, 8, 2]], 1)\n/// vec![1]\nfn minPath(grid: Vec>, k: isize) -> Vec {\n let n = grid.len();\n let mut dp = vec![vec![vec![isize::MAX; k as usize + 1]; n]; n];\n dp[0][0][0] = grid[0][0];\n for i in 0..n {\n for j in 0..n {\n for l in 0..k as usize + 1 {\n if i > 0 {\n dp[i][j][l] = dp[i][j][l].min(dp[i - 1][j][l]);\n }\n if j > 0 {\n dp[i][j][l] = dp[i][j][l].min(dp[i][j - 1][l]);\n }\n if l > 0 {\n dp[i][j][l] = dp[i][j][l].min(dp[i][j][l - 1]);\n }\n if dp[i][j][l] != isize::MAX {\n dp[i][j][l] += grid[i][j];\n }\n }\n }\n }\n let mut path = vec![];\n let mut i = n - 1;\n let mut j = n - 1;\n let mut l = k as usize;\n while i > 0 || j > 0 {\n if i > 0 && dp[i - 1][j][l] < dp[i][j][l] {\n i -= 1;\n } else if j > 0 && dp[i][j - 1][l] < dp[i][j][l] {\n j -= 1;\n } else {\n l -= 1;\n }\n path.push(grid[i][j]);\n }\n path.push(grid[0][0]);\n path.reverse();\n path"], ["/// Out of vector of strings, return the longest one. Return the first one in case of multiple\n/// strings of the same length. Return None in case the input vector is empty.\n/// >>> longest(vec![])\n/// None\n/// >>> longest(vec![String::from(\"a\"), String::from(\"b\"), String::from(\"c\")])\n/// Some(String::from(\"a\"))\n/// >>> longest(vec![String::from(\"a\"), String::from(\"bb\"), String::from(\"ccc\")])\n/// Some(String::from(\"ccc\"))\nfn longest(strings: Vec) -> Option {\n strings.into_iter().max_by_key(|s| s.len()).cloned()"], ["/// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n/// the last couple centuries. However, what people don't know is Tribonacci sequence.\n/// Tribonacci sequence is defined by the recurrence:\n/// tri(1) = 3\n/// tri(n) = 1 + n / 2, if n is even.\n/// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n/// For example:\n/// tri(2) = 1 + (2 / 2) = 2\n/// tri(4) = 3\n/// tri(3) = tri(2) + tri(1) + tri(4)\n/// = 2 + 3 + 3 = 8 \n/// You are given a non-negative integer number n, you have to a return a vector of the \n/// first n + 1 numbers of the Tribonacci sequence.\n/// Examples:\n/// >>> tri(3)\n/// vec![1, 3, 2, 8]\nfn tri(n: isize) -> Vec {\n let mut result = vec![0; (n + 1) as usize];\n result[0] = 3;\n for i in 1..=n {\n if i % 2 == 0 {\n result[i as usize] = 1 + i / 2;\n } else {\n result[i as usize] = result[(i - 1) as usize] + result[(i - 2) as usize] + result[(i + 1) as usize];\n }\n }\n result"], ["/// Given a positive integer n, return the product of the odd digits.\n/// Return 0 if all digits are even.\n/// For example:\n/// >>> digits(1)\n/// 1\n/// >>> digits(4)\n/// 0\n/// >>> digits(235)\n/// 15\nfn digits(n: isize) -> isize {\n let mut product = 1;\n let mut has_odd = false;\n let mut num = n;\n\n while num > 0 {\n let digit = num % 10;\n if digit % 2 != 0 {\n product *= digit;\n has_odd = true;\n }\n num /= 10;\n }\n\n if has_odd { product } else { 0 }"], ["/// Create a function that takes a string as input which contains only square brackets.\n/// The function should return true if and only if there is a valid subsequence of brackets \n/// where at least one bracket in the subsequence is nested.\n/// >>> is_nested(String::from(\"[[]]\"))\n/// true\n/// >>> is_nested(String::from(\"[]]]]]]][[[[[]\"))\n/// false\n/// >>> is_nested(String::from(\"[][]\"))\n/// false\n/// >>> is_nested(String::from(\"[]\"))\n/// false\n/// >>> is_nested(String::from(\"[[][]]\"))\n/// true\n/// >>> is_nested(String::from(\"[[]][[\"))\n/// true\nfn is_nested(string: String) -> bool {\n let mut stack = Vec::new();\n for c in string.chars() {\n match c {\n '[' => stack.push(c),\n ']' => {\n if stack.is_empty() {\n return false;\n }\n stack.pop();\n }\n _ => return false,\n }\n }\n !stack.is_empty()"], ["/// You are given a vector of numbers.\n/// You need to return the sum of squared numbers in the given vector,\n/// round each element in the vector to the upper int(Ceiling) first.\n/// Examples:\n/// >>> lst(vec![1.0, 2.0, 3.0])\n/// 14\n/// >>> lst(vec![1.0, 4.0, 9.0])\n/// 98\n/// >>> lst(vec![1.0, 3.0, 5.0, 7.0])\n/// 84\n/// >>> lst(vec![1.4, 4.2, 0.0])\n/// 29\n/// >>> lst(vec![-2.4, 1.0, 1.0])\n/// 6\nfn sum_squares(lst: Vec) -> isize {\n lst.iter()\n .map(|&x| (x.ceil().powi(2) as isize))\n .sum()"], ["/// Create a function that returns true if the last character\n/// of a given string is an alphabetical character and is not\n/// a part of a word, and false otherwise.\n/// Note: \"word\" is a group of characters separated by space.\n/// Examples:\n/// >>> check_if_last_char_is_a_letter(String::from(\"apple pie\"))\n/// false\n/// >>> check_if_last_char_is_a_letter(String::from(\"apple pi e\"))\n/// true\n/// >>> check_if_last_char_is_a_letter(String::from(\"apple pi e \"))\n/// false\n/// >>> check_if_last_char_is_a_letter(String::from(\"\"))\n/// false\nfn check_if_last_char_is_a_letter(txt: String) -> bool {\n let mut last_char = ' ';\n let mut is_word = false;\n for c in txt.chars() {\n if c.is_alphabetic() {\n last_char = c;\n is_word = true;\n } else if c.is_whitespace() {\n is_word = false;\n }\n }\n last_char.is_alphabetic() && !is_word"], ["/// Create a function which returns the largest index of an element which\n/// is not greater than or equal to the element immediately preceding it. If\n/// no such element exists then return -1. The given vector will not contain\n/// duplicate values.\n/// Examples:\n/// >>> can_arrange(vec![1, 2, 4, 3, 5])\n/// 3\n/// >>> can_arrange(vec![1, 2, 3])\n/// -1\nfn can_arrange(arr: Vec) -> isize {\n let mut max_index = -1;\n for i in 1..arr.len() {\n if arr[i] <= arr[i-1] {\n max_index = i as isize;\n }\n }\n max_index"], ["/// Create a function that returns a tuple (a, b), where 'a' is\n/// the largest of negative integers, and 'b' is the smallest\n/// of positive integers in a vector.\n/// If there is no negative or positive integers, return them as None.\n/// Examples:\n/// >>> largest_smallest_integers(vec![2, 4, 1, 3, 5, 7])\n/// (None, Some(1))\n/// >>> largest_smallest_integers(vec![])\n/// (None, None)\n/// >>> largest_smallest_integers(vec![0])\n/// (None, None)\nfn largest_smallest_integers(lst: Vec) -> (Option, Option) {\n let mut largest_negative = None;\n let mut smallest_positive = None;\n\n for num in lst {\n if num < 0 {\n if largest_negative.is_none() || num > largest_negative.unwrap() {\n largest_negative = Some(num);\n }\n } else if num > 0 {\n if smallest_positive.is_none() || num < smallest_positive.unwrap() {\n smallest_positive = Some(num);\n }\n }\n }\n\n (largest_negative, smallest_positive)"], ["/// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n/// Example\n/// >>> is_equal_to_sum_even(4)\n/// false\n/// >>> is_equal_to_sum_even(6)\n/// false\n/// >>> is_equal_to_sum_even(8)\n/// true\nfn is_equal_to_sum_even(n: isize) -> bool {\n if n % 2 != 0 {\n return false;\n }\n let n = n / 2;\n for i in 1..=n {\n for j in i..=n {\n for k in j..=n {\n for l in k..=n {\n if i + j + k + l == n {\n return true;\n }\n }\n }\n }\n }\n false"], ["/// The Brazilian factorial is defined as:\n/// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n/// where n > 0\n/// For example:\n/// >>> special_factorial(4)\n/// 288\n/// The function will receive an integer as input and should return the special\n/// factorial of this integer.\nfn special_factorial(n: isize) -> isize {\n let mut result = 1;\n for i in 1..=n {\n result *= (1..=i).product();\n }\n result"], ["/// Return a greatest common divisor of two integers a and b\n/// >>> greatest_common_divisor(3, 5)\n/// 1\n/// >>> greatest_common_divisor(25, 15)\n/// 5\nfn greatest_common_divisor(a: isize, b: isize) -> isize {\n let mut a = a;\n let mut b = b;\n while b != 0 {\n let temp = b;\n b = a % b;\n a = temp;\n }\n a.abs()"], ["/// Given a string text, replace all spaces in it with underscores, \n/// and if a string has more than 2 consecutive spaces, \n/// then replace all consecutive spaces with - \n/// >>> fix_spaces(String::from(\" Example\"))\n/// String::from(\"Example\")\n/// >>> fix_spaces(String::from(\" Example 1\"))\n/// String::from(\"Example_1\")\n/// >>> fix_spaces(String::from(\" Example 2\"))\n/// String::from(\"_Example_2\")\n/// >>> fix_spaces(String::from(\" Example 3\"))\n/// String::from(\"_Example-3\")\nfn fix_spaces(text: String) -> String {\n let mut result = String::new();\n let mut prev_char = ' ';\n let mut consecutive_spaces = 0;\n\n for c in text.chars() {\n if c == ' ' {\n consecutive_spaces += 1;\n if consecutive_spaces > 2 {\n result.push('-');\n consecutive_spaces = 0;\n }\n } else {\n if prev_char == ' ' {\n result.push('_');\n }\n result.push(c);\n consecutive_spaces = 0;\n }\n prev_char = c;\n }\n\n result"], ["/// Create a function which takes a string representing a file's name, and returns\n/// 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n/// A file's name is considered to be valid if and only if all the following conditions \n/// are met:\n/// - There should not be more than three digits ('0'-'9') in the file's name.\n/// - The file's name contains exactly one dot '.'\n/// - The substring before the dot should not be empty, and it starts with a letter from \n/// the latin alphapet ('a'-'z' and 'A'-'Z').\n/// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n/// Examples:\n/// >>> file_name_check(String::from(\"example.txt\"))\n/// String::from(\"Yes\")\n/// >>> file_name_check(String::from(\"1example.dll\"))\n/// String::from(\"No\")\nfn file_name_check(file_name: String) -> String {\n let mut digit_count = 0;\n let mut dot_count = 0;\n let mut before_dot = String::new();\n let mut after_dot = String::new();\n\n for c in file_name.chars() {\n if c.is_digit() {\n digit_count += 1;\n } else if c == '.' {\n dot_count += 1;\n } else if before_dot.is_empty() {\n before_dot.push(c);\n } else {\n after_dot.push(c);\n }\n }\n\n if digit_count > 3 || dot_count != 1 || before_dot.is_empty() || !before_dot.chars().next().unwrap().is_alphabetic() || ![\"txt\", \"exe\", \"dll\"].contains(&after_dot) {\n return String::from(\"No\");\n }\n\n String::from(\"Yes\")"], ["/// \"\n/// This function will take a vector of integers. For all entries in the vector, the function shall square the integer entry if its index is a \n/// multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n/// change the entries in the vector whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n/// Examples:\n/// >>> lst\n/// vec![1, 2, 3]\n/// >>> lst\n/// vec![]\n/// >>> lst\n/// vec![-1, -5, 2, -1, -5]\nfn sum_squares(lst: Vec) -> isize {\n let mut sum = 0;\n for (i, &num) in lst.iter().enumerate() {\n if i % 3 == 0 {\n sum += num * num;\n } else if i % 4 == 0 {\n sum += num * num * num;\n } else {\n sum += num;\n }\n }\n sum"], ["/// You are given a string representing a sentence,\n/// the sentence contains some words separated by a space,\n/// and you have to return a string that contains the words from the original sentence,\n/// whose lengths are prime numbers,\n/// the order of the words in the new string should be the same as the original one.\n/// Example 1:\n/// >>> words_in_sentence(String::from(\"This is a test\"))\n/// String::from(\"is\")\n/// Example 2:\n/// >>> words_in_sentence(String::from(\"lets go for swimming\"))\n/// String::from(\"go for\")\n/// Constraints:\n/// * 1 <= len(sentence) <= 100\n/// * sentence contains only letters\nfn words_in_sentence(sentence: String) -> String {\n let mut result = String::new();\n for word in sentence.split_whitespace() {\n if is_prime(word.len()) {\n result.push_str(&format!(\"{} \", word));\n }\n }\n result.trim().to_string()"], ["/// Your task is to implement a function that will simplify the expression\n/// x * n. The function returns true if x * n evaluates to a whole number and false\n/// otherwise. Both x and n, are string representation of a fraction, and have the following format,\n/// / where both numerator and denominator are positive whole numbers.\n/// You can assume that x, and n are valid fractions, and do not have zero as denominator.\n/// >>> simplify(String::from(\"1/5\"), String::from(\"5/1\"))\n/// true\n/// >>> simplify(String::from(\"1/6\"), String::from(\"2/1\"))\n/// false\n/// >>> simplify(String::from(\"7/10\"), String::from(\"10/2\"))\n/// false\nfn simplify(x: String, n: String) -> bool {\n let mut x_parts = x.split('/').map(|s| s.parse::().unwrap());\n let mut n_parts = n.split('/').map(|s| s.parse::().unwrap());\n\n let mut x_num = x_parts.next().unwrap();\n let mut x_den = x_parts.next().unwrap();\n let mut n_num = n_parts.next().unwrap();\n let mut n_den = n_parts.next().unwrap();\n\n // Multiply the numerators and denominators\n let mut num = x_num * n_num;\n let mut den = x_den * n_den;\n\n // Simplify the fraction\n let gcd = gcd(num, den);\n num /= gcd;\n den /= gcd;\n\n // Check if the result is a whole number\n num % den == 0"], ["/// Write a function which sorts the given vector of integers\n/// in ascending order according to the sum of their digits.\n/// Note: if there are several items with similar sum of their digits,\n/// order them based on their index in original vector.\n/// For example:\n/// >>> order_by_points(vec![1, 11, -1, -11, -12])\n/// vec![-1, -11, 1, -12, 11]\n/// >>> order_by_points(vec![])\n/// Vec::::new()\nfn order_by_points(nums: Vec) -> Vec {\n let mut nums = nums;\n nums.sort_by_key(|&n| (n.abs().to_string().chars().map(|c| c.to_digit(10).unwrap()).sum::(), n.abs()));\n nums"], ["/// Write a function that takes a vector of numbers as input and returns \n/// the number of elements in the vector that are greater than 10 and both \n/// first and last digits of a number are odd (1, 3, 5, 7, 9).\n/// For example:\n/// >>> specialFilter(vec![15, -73, 14, -15])\n/// 1\n/// >>> specialFilter(vec![33, -2, -3, 45, 21, 109])\n/// 2\nfn specialFilter(nums: Vec) -> isize {\n let mut count = 0;\n for num in nums {\n if num > 10 && (num.abs() % 10) % 2 == 1 && (num.abs() / 100000000) % 2 == 1 {\n count += 1;\n }\n }\n count"], ["/// You are given a positive integer n. You have to create an integer vector a of length n.\n/// For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n/// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n/// and a[i] + a[j] + a[k] is a multiple of 3.\n/// Example :\n/// >>> get_max_triples(5)\n/// 1\n/// Explanation: \n/// a = [1, 3, 7, 13, 21]\n/// The only valid triple is (1, 7, 13).\nfn get_max_triples(n: isize) -> isize {\n let mut count = 0;\n for i in 1..=n {\n for j in (i+1)..=n {\n for k in (j+1)..=n {\n let sum = i*i - i + 1 + j*j - j + 1 + k*k - k + 1;\n if sum % 3 == 0 {\n count += 1;\n }\n }\n }\n }\n count"], ["/// Write a function that accepts a vector of strings as a parameter,\n/// deletes the strings that have odd lengths from it,\n/// and returns the resulted vector with a sorted order,\n/// The vector is always a vector of strings and never a vector of numbers,\n/// and it may contain duplicates.\n/// The order of the vector should be ascending by length of each word, and you\n/// should return the vector sorted by that rule.\n/// If two words have the same length, sort the vector alphabetically.\n/// The function should return a vector of strings in sorted order.\n/// You may assume that all words will have the same length.\n/// For example:\n/// >>> list_sort(vec![String::from(\"aa\"), String::from(\"a\"), String::from(\"aaa\")])\n/// vec![String::from(\"aa\")]\n/// >>> list_sort(vec![String::from(\"ab\"), String::from(\"a\"), String::from(\"aaa\"), String::from(\"cd\")])\n/// vec![String::from(\"ab\"), String::from(\"cd\")]\nfn sorted_list_sum(lst: Vec) -> Vec {\n let mut result = lst.into_iter()\n .filter(|s| s.len() % 2 == 0)\n .collect::>();\n result.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)));\n result"], ["/// Return vector of all prefixes from shortest to longest of the input string\n/// >>> all_prefixes(String::from(\"abc\"))\n/// vec![String::from(\"a\"), String::from(\"ab\"), String::from(\"abc\")]\nfn all_prefixes(string: String) -> Vec {\n (1..=string.len()).map(|i| string[0..i].to_string()).collect()"], ["/// A simple program which should return the value of x if n is \n/// a prime number and should return the value of y otherwise.\n/// Examples:\n/// >>> x_or_y(7, 34, 12)\n/// 34\n/// >>> x_or_y(15, 8, 5)\n/// 5\nfn x_or_y(n: isize, x: isize, y: isize) -> isize {\n if is_prime(n) {\n return x;\n } else {\n return y;\n }"], ["/// Given a vector of numbers, return the sum of squares of the numbers\n/// in the vector that are odd. Ignore numbers that are negative or not integers.\n/// >>> double_the_difference(vec![1, 3, 2, 0])\n/// 10\n/// >>> double_the_difference(vec![-1, -2, 0])\n/// 0\n/// >>> double_the_difference(vec![9, -2])\n/// 81\n/// >>> double_the_difference(vec![0])\n/// 0\n/// If the input vector is empty, return 0.\nfn double_the_difference(lst: Vec) -> isize {\n lst.iter()\n .filter(|&x| x.is_sign_positive() && x.fract() == 0.0)\n .map(|&x| (x as isize).pow(2))\n .sum()"], ["/// I think we all remember that feeling when the result of some long-awaited\n/// event is finally known. The feelings and thoughts you have at that moment are\n/// definitely worth noting down and comparing.\n/// Your task is to determine if a person correctly guessed the results of a number of matches.\n/// You are given two vectors of scores and guesses of equal length, where each index shows a match. \n/// Return a vector of the same length denoting how far off each guess was. If they have guessed correctly,\n/// the value is 0, and if not, the value is the absolute difference between the guess and the score.\n/// example:\n/// >>> compare(vec![1, 2, 3, 4, 5, 1], vec![1, 2, 3, 4, 2, -2])\n/// vec![0, 0, 0, 0, 3, 3]\n/// >>> compare(vec![0, 5, 0, 0, 0, 4], vec![4, 1, 1, 0, 0, -2])\n/// vec![4, 4, 1, 0, 0, 6]\nfn compare(game: Vec, guess: Vec) -> Vec {\n game.iter().zip(guess.iter()).map(|(s, g)| (s - g).abs()).collect()"], ["/// You will be given the name of a class (a string) and a vector of extensions.\n/// The extensions are to be used to load additional classes to the class. The\n/// strength of the extension is as follows: Let CAP be the number of the uppercase\n/// letters in the extension's name, and let SM be the number of lowercase letters \n/// in the extension's name, the strength is given by the fraction CAP - SM. \n/// You should find the strongest extension and return a string in this \n/// format: ClassName.StrongestExtensionName.\n/// If there are two or more extensions with the same strength, you should\n/// choose the one that comes first in the vector.\n/// For example, if you are given \"Slices\" as the class and a vector of the\n/// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n/// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n/// (its strength is -1).\n/// Example:\n/// >>> Strongest_Extension(String::from(\"my_class\"), vec![String::from(\"AA\"), String::from(\"Be\"), String::from(\"CC\")])\n/// String::from(\"my_class.AA\")\nfn Strongest_Extension(class_name: String, extensions: Vec) -> String {\n let mut strongest_extension = extensions[0].clone();\n let mut strongest_strength = get_strength(&strongest_extension);\n\n for extension in extensions.iter().skip(1) {\n let strength = get_strength(extension);\n if strength > strongest_strength {\n strongest_extension = extension.clone();\n strongest_strength = strength;\n }\n }\n\n format!(\"{}.{}\", class_name, strongest_extension)"], ["/// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n/// >>> cycpattern_check(String::from(\"abcd\"), String::from(\"abd\"))\n/// false\n/// >>> cycpattern_check(String::from(\"hello\"), String::from(\"ell\"))\n/// true\n/// >>> cycpattern_check(String::from(\"whassup\"), String::from(\"psus\"))\n/// false\n/// >>> cycpattern_check(String::from(\"abab\"), String::from(\"baa\"))\n/// true\n/// >>> cycpattern_check(String::from(\"efef\"), String::from(\"eeff\"))\n/// false\n/// >>> cycpattern_check(String::from(\"himenss\"), String::from(\"simen\"))\n/// true\nfn cycpattern_check(a: String, b: String) -> bool {\n let mut rotations = vec![b.clone()];\n for i in 1..b.len() {\n let mut rotation = b[i..].to_string();\n rotation.push_str(&b[..i]);\n rotations.push(rotation);\n }\n rotations.iter().any(|r| a.contains(r))"], ["/// Given an integer. return a tuple that has the number of even and odd digits respectively.\n/// Example:\n/// >>> even_odd_count(-12)\n/// (1, 1)\n/// >>> even_odd_count(123)\n/// (1, 2)\nfn even_odd_count(num: isize) -> (isize, isize) {\n let mut even_count = 0;\n let mut odd_count = 0;\n\n let mut num = num.abs();\n\n while num > 0 {\n let digit = num % 10;\n if digit % 2 == 0 {\n even_count += 1;\n } else {\n odd_count += 1;\n }\n num /= 10;\n }\n\n (even_count, odd_count)"], ["/// Given a positive integer, obtain its roman numeral equivalent as a string,\n/// and return it in lowercase.\n/// Restrictions: 1 <= num <= 1000\n/// Examples:\n/// >>> int_to_mini_roman(19)\n/// String::from(\"xix\")\n/// >>> int_to_mini_roman(152)\n/// String::from(\"clii\")\n/// >>> int_to_mini_roman(426)\n/// String::from(\"cdxxvi\")\nfn int_to_mini_roman(number: isize) -> String {\n let mut result = String::new();\n let mut num = number;\n\n while num > 0 {\n if num >= 100 {\n result.push_str(\"c\");\n num -= 100;\n } else if num >= 90 {\n result.push_str(\"xc\");\n num -= 90;\n } else if num >= 50 {\n result.push_str(\"l\");\n num -= 50;\n } else if num >= 40 {\n result.push_str(\"xl\");\n num -= 40;\n } else if num >= 10 {\n result.push_str(\"x\");\n num -= 10;\n } else if num >= 9 {\n result.push_str(\"ix\");\n num -= 9;\n } else if num >= 5 {\n result.push_str(\"v\");\n num -= 5;\n } else if num >= 4 {\n result.push_str(\"iv\");\n num -= 4;\n } else {\n result.push_str(\"i\");\n num -= 1;\n }\n }\n\n result.to_lowercase()"], ["/// Given the lengths of the three sides of a triangle. Return true if the three\n/// sides form a right-angled triangle, false otherwise.\n/// A right-angled triangle is a triangle in which one angle is right angle or \n/// 90 degree.\n/// Example:\n/// >>> right_angle_triangle(3, 4, 5)\n/// true\n/// >>> right_angle_triangle(1, 2, 3)\n/// false\nfn right_angle_triangle(a: isize, b: isize, c: isize) -> bool {\n let mut sides = vec![a, b, c];\n sides.sort();\n sides[0] * sides[0] + sides[1] * sides[1] == sides[2] * sides[2]"], ["/// Write a function that accepts a vector of strings.\n/// The vector contains different words. Return the word with maximum number\n/// of unique characters. If multiple strings have maximum number of unique\n/// characters, return the one which comes first in lexicographical order.\n/// >>> find_max(vec![String::from(\"name\"), String::from(\"of\"), String::from(\"string\")])\n/// String::from(\"string\")\n/// >>> find_max(vec![String::from(\"name\"), String::from(\"enam\"), String::from(\"game\")])\n/// String::from(\"enam\")\n/// >>> find_max(vec![String::from(\"aaaaaaa\"), String::from(\"bb\"), String::from(\"cc\")])\n/// String::from(\"aaaaaaa\")\nfn find_max(words: Vec) -> String {\n let mut max_word = String::new();\n let mut max_unique_chars = 0;\n\n for word in words {\n let unique_chars = word.chars().collect::>().len();\n\n if unique_chars > max_unique_chars || (unique_chars == max_unique_chars && word < max_word) {\n max_word = word.clone();\n max_unique_chars = unique_chars;\n }\n }\n\n max_word"], ["/// You're a hungry rabbit, and you already have eaten a certain number of carrots,\n/// but now you need to eat more carrots to complete the day's meals.\n/// you should return a vector of [ total number of eaten carrots after your meals,\n/// the number of carrots left after your meals ]\n/// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n/// Example:\n/// >>> eat(5, 6, 10)\n/// vec![11, 4]\n/// >>> eat(4, 8, 9)\n/// vec![12, 1]\n/// >>> eat(1, 10, 10)\n/// vec![11, 0]\n/// >>> eat(2, 11, 5)\n/// vec![7, 0]\n/// Variables:\n/// @number : integer\n/// the number of carrots that you have eaten.\n/// @need : integer\n/// the number of carrots that you need to eat.\n/// @remaining : integer\n/// the number of remaining carrots thet exist in stock\n/// Constrain:\n/// * 0 <= number <= 1000\n/// * 0 <= need <= 1000\n/// * 0 <= remaining <= 1000\n/// Have fun :)\nfn eat(number: isize, need: isize, remaining: isize) -> Vec {\n let eaten = number + need;\n let left = if remaining < need { remaining } else { remaining - need };\n vec![eaten, left]"], ["/// Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n/// >>> string_sequence(0)\n/// String::from(\"0\")\n/// >>> string_sequence(5)\n/// String::from(\"0 1 2 3 4 5\")\nfn string_sequence(n: isize) -> String {\n (0..=n).map(|x| x.to_string()).collect::>().join(\" \")"], ["/// Given two vectors operator, and operand. The first vector has basic algebra operations, and \n/// the second vector is a vector of integers. Use the two given vectors to build the algebric \n/// expression and return the evaluation of this expression.\n/// The basic algebra operations:\n/// Addition ( + ) \n/// Subtraction ( - ) \n/// Multiplication ( * ) \n/// Floor division ( // ) \n/// Exponentiation ( ** ) \n/// Example:\n/// operator['+', '*', '-']\n/// vector = [2, 3, 4, 5]\n/// result = 2 + 3 * 4 - 5\n/// => result = 9\n/// Note:\n/// The length of operator vector is equal to the length of operand vector minus one.\n/// Operand is a vector of of non-negative integers.\n/// Operator vector has at least one operator, and operand vector has at least two operands.\nfn do_algebra(operator: Vec, operand: Vec) -> isize {\n let mut result = operand[0];\n for i in 1..operand.len() {\n match operator[i - 1].as_str() {\n \"+\" => result += operand[i],\n \"-\" => result -= operand[i],\n \"*\" => result *= operand[i],\n \"//\" => result /= operand[i],\n \"**\" => result = result.pow(operand[i] as u32),\n _ => panic!(\"Invalid operator\"),\n }\n }\n result"], ["/// You are given a string s.\n/// if s[i] is a letter, reverse its case from lower to upper or vise versa, \n/// otherwise keep it as it is.\n/// If the string contains no letters, reverse the string.\n/// The function should return the resulted string.\n/// Examples\n/// >>> solve(String::from(\"1234\"))\n/// String::from(\"4321\")\n/// >>> solve(String::from(\"ab\"))\n/// String::from(\"AB\")\n/// >>> solve(String::from(\"#a@C\"))\n/// String::from(\"#A@c\")\nfn solve(s: String) -> String {\n let mut result = String::new();\n let mut has_letter = false;\n for c in s.chars() {\n if c.is_alphabetic() {\n has_letter = true;\n if c.is_lowercase() {\n result.push(c.to_uppercase().next().unwrap());\n } else {\n result.push(c.to_lowercase().next().unwrap());\n }\n } else {\n result.push(c);\n }\n }\n if !has_letter {\n result = s.chars().rev().collect();\n }\n result"], ["/// Given a string 'text', return its md5 hash equivalent string.\n/// If 'text' is an empty string, return None.\n/// >>> string_to_md5(String::from(\"Hello world\"))\n/// Some(String::from(\"3e25960a79dbc69b674cd4ec67a72c62\"))\nfn string_to_md5(text: String) -> Option {\n if text.is_empty() {\n None\n } else {\n let digest = md5::compute(text.as_bytes());\n let mut result = String::new();\n for &byte in digest.as_ref() {\n result.push_str(&format!(\"{:02x}\", byte));\n }\n Some(result)\n }"], ["/// Given two positive integers a and b, return the even digits between a\n/// and b, in ascending order.\n/// For example:\n/// >>> generate_integers(2, 8)\n/// vec![2, 4, 6, 8]\n/// >>> generate_integers(8, 2)\n/// vec![2, 4, 6, 8]\n/// >>> generate_integers(10, 14)\n/// Vec::::new()\nfn generate_integers(a: isize, b: isize) -> Vec {\n let mut result = Vec::new();\n let mut current = a;\n if a > b {\n current = b;\n }\n while current <= a.max(b) {\n if current % 2 == 0 {\n result.push(current);\n }\n current += 1;\n }\n result"], ["/// Given a string, find out how many distinct characters (regardless of case) does it consist of\n/// >>> count_distinct_characters(String::from(\"xyzXYZ\"))\n/// 3\n/// >>> count_distinct_characters(String::from(\"Jerry\"))\n/// 4\nfn count_distinct_characters(string: String) -> isize {\n let mut set = std::collections::HashSet::new();\n for c in string.chars() {\n set.insert(c.to_ascii_lowercase());\n }\n set.len() as isize"], ["/// Input to this function is a string representing musical notes in a special ASCII format.\n/// Your task is to parse this string and return vector of integers corresponding to how many beats does each\n/// not last.\n/// Here is a legend:\n/// 'o' - whole note, lasts four beats\n/// 'o|' - half note, lasts two beats\n/// '.|' - quater note, lasts one beat\n/// >>> parse_music(String::from(\"o o| .| o| o| .| .| .| .| o o\"))\n/// vec![4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\nfn parse_music(music_string: String) -> Vec {\n let mut beats = Vec::new();\n let mut current_beat = 0;\n\n for note in music_string.chars() {\n match note {\n 'o' => {\n current_beat += 4;\n beats.push(current_beat);\n current_beat = 0;\n }\n '|' => {\n current_beat += 2;\n beats.push(current_beat);\n current_beat = 0;\n }\n '.' => {\n current_beat += 1;\n beats.push(current_beat);\n current_beat = 0;\n }\n _ => {}\n }\n }\n\n beats"], ["/// Find how many times a given substring can be found in the original string. Count overlaping cases.\n/// >>> how_many_times(String::from(\"\"), String::from(\"a\"))\n/// 0\n/// >>> how_many_times(String::from(\"aaa\"), String::from(\"a\"))\n/// 3\n/// >>> how_many_times(String::from(\"aaaa\"), String::from(\"aa\"))\n/// 3\nfn how_many_times(string: String, substring: String) -> isize {\n let mut count = 0;\n let mut index = 0;\n while let Some(i) = string[index..].find(&substring) {\n count += 1;\n index += i + 1;\n }\n count"], ["/// Input is a space-delimited string of numberals from 'zero' to 'nine'.\n/// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n/// Return the string with numbers sorted from smallest to largest\n/// >>> sort_numbers(String::from(\"three one five\"))\n/// String::from(\"one three five\")\nfn sort_numbers(numbers: String) -> String {\n let mut nums: Vec<&str> = numbers.split_whitespace().collect();\n nums.sort_by(|a, b| a.cmp(b));\n nums.join(\" \")"], ["/// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n/// separate those group into separate strings and return the vector of those.\n/// Separate groups are balanced (each open brace is properly closed) and not nested within each other\n/// Ignore any spaces in the input string.\n/// >>> separate_paren_groups(String::from(\"( ) (( )) (( )( ))\"))\n/// vec![String::from(\"()\"), String::from(\"(())\"), String::from(\"(()())\")]\nfn separate_paren_groups(paren_string: String) -> Vec {\n let mut groups = Vec::new();\n let mut current_group = String::new();\n let mut open_count = 0;\n\n for c in paren_string.chars() {\n if c == '(' {\n open_count += 1;\n } else if c == ')' {\n open_count -= 1;\n }\n\n if open_count == 0 && !current_group.is_empty() {\n groups.push(current_group);\n current_group = String::new();\n } else if c != ' ' {\n current_group.push(c);\n }\n }\n\n groups"], ["/// From a supplied vector of numbers (of length at least two) select and return two that are the closest to each\n/// other and return them in order (smaller number, larger number).\n/// >>> find_closest_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n/// (2.0, 2.2)\n/// >>> find_closest_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n/// (2.0, 2.0)\nfn find_closest_elements(numbers: Vec) -> (f64, f64) {\n let mut closest_pair = (numbers[0], numbers[1]);\n let mut min_diff = (closest_pair.0 - closest_pair.1).abs();\n\n for i in 0..numbers.len() {\n for j in i + 1..numbers.len() {\n let diff = (numbers[i] - numbers[j]).abs();\n if diff < min_diff {\n min_diff = diff;\n closest_pair = (numbers[i], numbers[j]);\n }\n }\n }\n\n if closest_pair.0 < closest_pair.1 {\n closest_pair\n } else {\n (closest_pair.1, closest_pair.0)\n }"], ["/// Given vector of numbers (of at least two elements), apply a linear transform to that vector,\n/// such that the smallest number will become 0 and the largest will become 1\n/// >>> rescale_to_unit(vec![1.0, 2.0, 3.0, 4.0, 5.0])\n/// vec![0.0, 0.25, 0.5, 0.75, 1.0]\nfn rescale_to_unit(numbers: Vec) -> Vec {\n let min = numbers.iter().copied().min().unwrap();\n let max = numbers.iter().copied().max().unwrap();\n let range = max - min;\n\n numbers\n .iter()\n .map(|&x| (x - min) / range)\n .collect()"], ["/// Return length of given string\n/// >>> strlen(String::from(\"\"))\n/// 0\n/// >>> strlen(String::from(\"abc\"))\n/// 3\nfn strlen(string: String) -> isize {\n string.len() as isize"], ["/// For a given number n, find the largest number that divides n evenly, smaller than n\n/// >>> largest_divisor(15)\n/// 5\nfn largest_divisor(n: isize) -> isize {\n let mut divisor = n - 1;\n while divisor > 1 {\n if n % divisor == 0 {\n return divisor;\n }\n divisor -= 1;\n }\n 1"], ["/// Return vector of prime factors of given integer in the order from smallest to largest.\n/// Each of the factors should be vectored number of times corresponding to how many times it appeares in factorization.\n/// Input number should be equal to the product of all factors\n/// >>> factorize(8)\n/// vec![2, 2, 2]\n/// >>> factorize(25)\n/// vec![5, 5]\n/// >>> factorize(70)\n/// vec![2, 5, 7]\nfn factorize(n: isize) -> Vec {\n let mut factors = Vec::new();\n let mut num = n;\n let mut divisor = 2;\n\n while num > 1 {\n if num % divisor == 0 {\n factors.push(divisor);\n num /= divisor;\n } else {\n divisor += 1;\n }\n }\n\n factors"], ["/// From a vector of integers, remove all elements that occur more than once.\n/// Keep order of elements left the same as in the input.\n/// >>> remove_duplicates(vec![1, 2, 3, 2, 4])\n/// vec![1, 3, 4]\nfn remove_duplicates(numbers: Vec) -> Vec {\n let mut result = Vec::new();\n for number in numbers {\n if !result.contains(&number) {\n result.push(number);\n }\n }\n result"], ["/// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n/// >>> flip_case(String::from(\"Hello\"))\n/// String::from(\"hELLO\")\nfn flip_case(string: String) -> String {\n string.chars().map(|c| {\n if c.is_uppercase() {\n c.to_lowercase()\n } else if c.is_lowercase() {\n c.to_uppercase()\n } else {\n c\n }\n }).collect()"], ["/// Concatenate vector of strings into a single string\n/// >>> concatenate(vec![])\n/// String::from(\"\")\n/// >>> concatenate(vec![String::from(\"a\"), String::from(\"b\"), String::from(\"c\")])\n/// String::from(\"abc\")\nfn concatenate(strings: Vec) -> String {\n strings.join(\"\")"], ["/// Filter an input vector of strings only for ones that start with a given prefix.\n/// >>> filter_by_prefix(vec![], String::from(\"a\"))\n/// Vec::::new()\n/// >>> filter_by_prefix(vec![String::from(\"abc\"), String::from(\"bcd\"), String::from(\"cde\"), String::from(\"array\")], String::from(\"a\"))\n/// vec![String::from(\"abc\"), String::from(\"array\")]\nfn filter_by_prefix(strings: Vec, prefix: String) -> Vec {\n strings.into_iter().filter(|s| s.starts_with(&prefix)).collect()"], ["/// Given a positive floating point number, it can be decomposed into\n/// and integer part (largest integer smaller than given number) and decimals\n/// (leftover part always smaller than 1).\n/// Return the decimal part of the number.\n/// >>> truncate_number(3.5)\n/// 0.5\nfn truncate_number(number: f64) -> f64 {\n number - number.floor()"], ["/// Return only positive numbers in the vector.\n/// >>> get_positive(vec![-1, 2, -4, 5, 6])\n/// vec![2, 5, 6]\n/// >>> get_positive(vec![5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n/// vec![5, 3, 2, 3, 9, 123, 1]\nfn get_positive(l: Vec) -> Vec {\n l.into_iter().filter(|&x| x > 0).collect()"], ["/// Return true if a given number is prime, and false otherwise.\n/// >>> is_prime(6)\n/// false\n/// >>> is_prime(101)\n/// true\n/// >>> is_prime(11)\n/// true\n/// >>> is_prime(13441)\n/// true\n/// >>> is_prime(61)\n/// true\n/// >>> is_prime(4)\n/// false\n/// >>> is_prime(1)\n/// false\nfn is_prime(n: isize) -> bool {\n if n <= 1 {\n return false;\n }\n for i in 2..((n as f64).sqrt().ceil() as isize + 1) {\n if n % i == 0 {\n return false;\n }\n }\n true"], ["/// This function takes a vector l and returns a vector l' such that\n/// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n/// to the values of the corresponding indicies of l, but sorted.\n/// >>> sort_third(vec![1, 2, 3])\n/// vec![1, 2, 3]\n/// >>> sort_third(vec![5, 6, 3, 4, 8, 9, 2])\n/// vec![2, 6, 3, 4, 8, 9, 5]\nfn sort_third(l: Vec) -> Vec {\n let mut l_prime = l.clone();\n let mut divisible_by_three = Vec::new();\n for i in 0..l.len() {\n if i % 3 == 0 {\n divisible_by_three.push(l[i]);\n }\n }\n divisible_by_three.sort();\n let mut j = 0;\n for i in 0..l.len() {\n if i % 3 == 0 {\n l_prime[i] = divisible_by_three[j];\n j += 1;\n }\n }\n l_prime"], ["/// Return sorted unique elements in a vector\n/// >>> unique(vec![5, 3, 5, 2, 3, 3, 9, 0, 123])\n/// vec![0, 2, 3, 5, 9, 123]\nfn unique(l: Vec) -> Vec {\n let mut v = l.clone();\n v.sort();\n v.dedup();\n v"], ["/// Return maximum element in the vector.\n/// >>> max_element(vec![1, 2, 3])\n/// 3\n/// >>> max_element(vec![5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n/// 123\nfn max_element(l: Vec) -> isize {\n *l.iter().max().unwrap()"], ["/// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n/// >>> fizz_buzz(50)\n/// 0\n/// >>> fizz_buzz(78)\n/// 2\n/// >>> fizz_buzz(79)\n/// 3\nfn fizz_buzz(n: isize) -> isize {\n let mut count = 0;\n for i in 1..n {\n if i % 11 == 0 || i % 13 == 0 {\n let mut num = i;\n while num > 0 {\n if num % 10 == 7 {\n count += 1;\n }\n num /= 10;\n }\n }\n }\n count"], ["/// This function takes a vector l and returns a vector l' such that\n/// l' is identical to l in the odd indicies, while its values at the even indicies are equal\n/// to the values of the even indicies of l, but sorted.\n/// >>> sort_even(vec![1, 2, 3])\n/// vec![1, 2, 3]\n/// >>> sort_even(vec![5, 6, 3, 4])\n/// vec![3, 6, 5, 4]\nfn sort_even(l: Vec) -> Vec {\n let mut l_sorted = l.clone();\n l_sorted.sort_unstable();\n let mut l_sorted_even = Vec::new();\n for i in (0..l.len()).step_by(2) {\n l_sorted_even.push(l_sorted[i]);\n }\n let mut l_sorted_odd = Vec::new();\n for i in (1..l.len()).step_by(2) {\n l_sorted_odd.push(l[i]);\n }\n l_sorted_even.append(&mut l_sorted_odd);\n l_sorted_even"], ["/// prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n/// >>> prime_fib(1)\n/// 2\n/// >>> prime_fib(2)\n/// 3\n/// >>> prime_fib(3)\n/// 5\n/// >>> prime_fib(4)\n/// 13\n/// >>> prime_fib(5)\n/// 89\nfn prime_fib(n: isize) -> isize {\n let mut fib_nums = vec![0, 1];\n let mut prime_fibs = vec![];\n\n for i in 2.. {\n let fib_num = fib_nums[i - 1] + fib_nums[i - 2];\n fib_nums.push(fib_num);\n\n if is_prime(fib_num) {\n prime_fibs.push(fib_num);\n }\n\n if prime_fibs.len() == n as usize {\n return prime_fibs[n as usize - 1];\n }\n }\n\n -1"], ["/// You're given a vector of deposit and withdrawal operations on a bank account that starts with\n/// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n/// at that point function should return true. Otherwise it should return false.\n/// >>> below_zero(vec![1, 2, 3])\n/// false\n/// >>> below_zero(vec![1, 2, -4, 5])\n/// true\nfn below_zero(operations: Vec) -> bool {\n let mut balance = 0;\n for operation in operations {\n balance += operation;\n if balance < 0 {\n return true;\n }\n }\n false"], ["/// triples_sum_to_zero takes a vector of integers as an input.\n/// it returns true if there are three distinct elements in the vector that\n/// sum to zero, and false otherwise.\n/// >>> triples_sum_to_zero(vec![1, 3, 5, 0])\n/// false\n/// >>> triples_sum_to_zero(vec![1, 3, -2, 1])\n/// true\n/// >>> triples_sum_to_zero(vec![1, 2, 3, 7])\n/// false\n/// >>> triples_sum_to_zero(vec![2, 4, -5, 3, 9, 7])\n/// true\n/// >>> triples_sum_to_zero(vec![1])\n/// false\nfn triples_sum_to_zero(l: Vec) -> bool {\n for i in 0..l.len() {\n for j in i+1..l.len() {\n for k in j+1..l.len() {\n if l[i] + l[j] + l[k] == 0 {\n return true;\n }\n }\n }\n }\n false"], ["/// Imagine a road that's a perfectly straight infinitely long line.\n/// n cars are driving left to right; simultaneously, a different set of n cars\n/// are driving right to left. The two sets of cars start out being very far from\n/// each other. All cars move in the same speed. Two cars are said to collide\n/// when a car that's moving left to right hits a car that's moving right to left.\n/// However, the cars are infinitely sturdy and strong; as a result, they continue moving\n/// in their trajectory as if they did not collide.\n/// This function outputs the number of such collisions.\nfn car_race_collision(n: isize) -> isize {\n n * (n - 1) / 2"], ["/// Return vector with elements incremented by 1.\n/// >>> incr_list(vec![1, 2, 3])\n/// vec![2, 3, 4]\n/// >>> incr_list(vec![5, 3, 5, 2, 3, 3, 9, 0, 123])\n/// vec![6, 4, 6, 3, 4, 4, 10, 1, 124]\nfn incr_list(l: Vec) -> Vec {\n l.iter().map(|x| x + 1).collect()"], ["/// pairs_sum_to_zero takes a vector of integers as an input.\n/// it returns true if there are two distinct elements in the vector that\n/// sum to zero, and false otherwise.\n/// >>> pairs_sum_to_zero(vec![1, 3, 5, 0])\n/// false\n/// >>> pairs_sum_to_zero(vec![1, 3, -2, 1])\n/// false\n/// >>> pairs_sum_to_zero(vec![1, 2, 3, 7])\n/// false\n/// >>> pairs_sum_to_zero(vec![2, 4, -5, 3, 5, 7])\n/// true\n/// >>> pairs_sum_to_zero(vec![1])\n/// false\nfn pairs_sum_to_zero(l: Vec) -> bool {\n for i in 0..l.len() {\n for j in i+1..l.len() {\n if l[i] + l[j] == 0 {\n return true;\n }\n }\n }\n false"], ["/// Change numerical base of input number x to base.\n/// return string representation after the conversion.\n/// base numbers are less than 10.\n/// >>> change_base(8, 3)\n/// String::from(\"22\")\n/// >>> change_base(8, 2)\n/// String::from(\"1000\")\n/// >>> change_base(7, 2)\n/// String::from(\"111\")\nfn change_base(x: isize, base: isize) -> String {\n let mut result = String::new();\n let mut num = x;\n\n while num > 0 {\n let digit = num % base;\n result.insert(0, char::from_digit(digit as u32, 10).unwrap());\n num /= base;\n }\n\n result"], ["/// Given length of a side and high return area for a triangle.\n/// >>> triangle_area(5, 3)\n/// 7.5\nfn triangle_area(a: isize, h: isize) -> f64 {\n (a * h) as f64 / 2.0"], ["/// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n/// fib4(0) -> 0\n/// fib4(1) -> 0\n/// fib4(2) -> 2\n/// fib4(3) -> 0\n/// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n/// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n/// >>> fib4(5)\n/// 4\n/// >>> fib4(6)\n/// 8\n/// >>> fib4(7)\n/// 14\nfn fib4(n: isize) -> isize {\n let mut fibs = vec![0, 0, 2, 0];\n for i in 4..=n {\n let new_fib = fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4];\n fibs.push(new_fib);\n }\n fibs[n as usize]"], ["/// Return median of elements in the vector l.\n/// >>> median(vec![3, 1, 2, 4, 5])\n/// 3.0\n/// >>> median(vec![-10, 4, 6, 1000, 10, 20])\n/// 15.0\nfn median(l: Vec) -> f64 {\n let mut sorted = l.clone();\n sorted.sort();\n let len = sorted.len();\n if len % 2 == 0 {\n (sorted[len / 2 - 1] + sorted[len / 2]) as f64 / 2.0\n } else {\n sorted[len / 2] as f64\n }"], ["/// Checks if given string is a palindrome\n/// >>> is_palindrome(String::from(\"\"))\n/// true\n/// >>> is_palindrome(String::from(\"aba\"))\n/// true\n/// >>> is_palindrome(String::from(\"aaaaa\"))\n/// true\n/// >>> is_palindrome(String::from(\"zbcd\"))\n/// false\nfn is_palindrome(text: String) -> bool {\n let chars: Vec = text.chars().collect();\n let len = chars.len();\n for i in 0..len/2 {\n if chars[i] != chars[len-i-1] {\n return false;\n }\n }\n true"], ["/// Return 2^n modulo p (be aware of numerics).\n/// >>> modp(3, 5)\n/// 3\n/// >>> modp(1101, 101)\n/// 2\n/// >>> modp(0, 101)\n/// 1\n/// >>> modp(3, 11)\n/// 8\n/// >>> modp(100, 101)\n/// 1\nfn modp(n: isize, p: isize) -> isize {\n (2isize.pow(n as u32) % p) as isize"], ["/// For a given vector of input numbers, calculate Mean Absolute Deviation\n/// around the mean of this dataset.\n/// Mean Absolute Deviation is the average absolute difference between each\n/// element and a centerpoint (mean in this case):\n/// MAD = average | x - x_mean |\n/// >>> mean_absolute_deviation(vec![1.0, 2.0, 3.0, 4.0])\n/// 1.0\nfn mean_absolute_deviation(numbers: Vec) -> f64 {\n let mean = numbers.iter().sum::() / numbers.len() as f64;\n let mut sum_abs_diff = 0.0;\n for &number in &numbers {\n sum_abs_diff += (number - mean).abs();\n }\n sum_abs_diff / numbers.len() as f64"], ["/// remove_vowels is a function that takes string and returns string without vowels.\n/// >>> remove_vowels(String::from(\"\"))\n/// String::from(\"\")\n/// >>> remove_vowels(String::from(\"abcdef\"))\n/// String::from(\"bcdf\")\n/// >>> remove_vowels(String::from(\"aaaaa\"))\n/// String::from(\"\")\n/// >>> remove_vowels(String::from(\"aaBAA\"))\n/// String::from(\"B\")\n/// >>> remove_vowels(String::from(\"zbcd\"))\n/// String::from(\"zbcd\")\nfn remove_vowels(text: String) -> String {\n text.chars()\n .filter(|c| !['a', 'e', 'i', 'o', 'u'].contains(&c.to_lowercase().next().unwrap()))\n .collect()"], ["/// Return true if all numbers in the vector l are below threshold t.\n/// >>> below_threshold(vec![1, 2, 4, 10], 100)\n/// true\n/// >>> below_threshold(vec![1, 20, 4, 10], 5)\n/// false\nfn below_threshold(l: Vec, t: isize) -> bool {\n for &n in &l {\n if n >= t {\n return false;\n }\n }\n true"], ["/// Add two numbers x and y\n/// >>> add(2, 3)\n/// 5\n/// >>> add(5, 7)\n/// 12\nfn add(x: isize, y: isize) -> isize {\n x + y"], ["/// Check if two words have the same characters.\n/// >>> same_chars(String::from(\"eabcdzzzz\"), String::from(\"dddzzzzzzzddeddabc\"))\n/// true\n/// >>> same_chars(String::from(\"abcd\"), String::from(\"dddddddabc\"))\n/// true\n/// >>> same_chars(String::from(\"dddddddabc\"), String::from(\"abcd\"))\n/// true\n/// >>> same_chars(String::from(\"eabcd\"), String::from(\"dddddddabc\"))\n/// false\n/// >>> same_chars(String::from(\"abcd\"), String::from(\"dddddddabce\"))\n/// false\n/// >>> same_chars(String::from(\"eabcdzzzz\"), String::from(\"dddzzzzzzzddddabc\"))\n/// false\nfn same_chars(s0: String, s1: String) -> bool {\n let mut s0_chars = s0.chars().collect::>();\n let mut s1_chars = s1.chars().collect::>();\n s0_chars.sort();\n s1_chars.sort();\n s0_chars == s1_chars"], ["/// Return n-th Fibonacci number.\n/// >>> fib(10)\n/// 55\n/// >>> fib(1)\n/// 1\n/// >>> fib(8)\n/// 21\nfn fib(n: isize) -> isize {\n if n == 0 {\n 0\n } else if n == 1 {\n 1\n } else {\n fib(n - 1) + fib(n - 2)\n }"], ["/// brackets is a string of \"<\" and \">\".\n/// return true if every opening bracket has a corresponding closing bracket.\n/// >>> correct_bracketing(String::from(\"<\"))\n/// false\n/// >>> correct_bracketing(String::from(\"<>\"))\n/// true\n/// >>> correct_bracketing(String::from(\"<<><>>\"))\n/// true\n/// >>> correct_bracketing(String::from(\"><<>\"))\n/// false\nfn correct_bracketing(brackets: String) -> bool {\n let mut stack = Vec::new();\n for c in brackets.chars() {\n match c {\n '<' => stack.push('<'),\n '>' => {\n if stack.is_empty() {\n return false;\n }\n stack.pop();\n }\n _ => (),\n }\n }\n stack.is_empty()"], ["/// Return true is vector elements are monotonically increasing or decreasing.\n/// >>> monotonic(vec![1, 2, 4, 20])\n/// true\n/// >>> monotonic(vec![1, 20, 4, 10])\n/// false\n/// >>> monotonic(vec![4, 1, 0, -10])\n/// true\nfn monotonic(l: Vec) -> bool {\n let mut increasing = true;\n let mut decreasing = true;\n\n for i in 1..l.len() {\n if l[i] < l[i - 1] {\n increasing = false;\n }\n if l[i] > l[i - 1] {\n decreasing = false;\n }\n }\n\n increasing || decreasing"], ["/// Return sorted unique common elements for two vectors.\n/// >>> common(vec![1, 4, 3, 34, 653, 2, 5], vec![5, 7, 1, 5, 9, 653, 121])\n/// vec![1, 5, 653]\n/// >>> common(vec![5, 3, 2, 8], vec![3, 2])\n/// vec![2, 3]\nfn common(l1: Vec, l2: Vec) -> Vec {\n let mut result = Vec::new();\n for i in &l1 {\n if l2.contains(i) && !result.contains(i) {\n result.push(*i);\n }\n }\n result.sort();\n result"], ["/// Return the largest prime factor of n. Assume n > 1 and is not a prime.\n/// >>> largest_prime_factor(13195)\n/// 29\n/// >>> largest_prime_factor(2048)\n/// 2\nfn largest_prime_factor(n: isize) -> isize {\n let mut factor = 2;\n let mut largest_factor = 1;\n\n while factor * factor <= n {\n if n % factor == 0 {\n largest_factor = factor;\n n /= factor;\n } else {\n factor += 1;\n }\n }\n\n if n > largest_factor {\n n\n } else {\n largest_factor\n }"], ["/// Insert a number 'delimeter' between every two consecutive elements of input vector `numbers'\n/// >>> intersperse(vec![], 4)\n/// Vec::::new()\n/// >>> intersperse(vec![1, 2, 3], 4)\n/// vec![1, 4, 2, 4, 3]\nfn intersperse(numbers: Vec, delimeter: isize) -> Vec {\n let mut result = Vec::new();\n for i in 0..numbers.len() {\n result.push(numbers[i]);\n if i != numbers.len() - 1 {\n result.push(delimeter);\n }\n }\n result"], ["/// sum_to_n is a function that sums numbers from 1 to n.\n/// >>> sum_to_n(30)\n/// 465\n/// >>> sum_to_n(100)\n/// 5050\n/// >>> sum_to_n(5)\n/// 15\n/// >>> sum_to_n(10)\n/// 55\n/// >>> sum_to_n(1)\n/// 1\nfn sum_to_n(n: isize) -> isize {\n (n * (n + 1)) / 2"], ["/// brackets is a string of \"(\" and \")\".\n/// return true if every opening bracket has a corresponding closing bracket.\n/// >>> correct_bracketing(String::from(\"(\"))\n/// false\n/// >>> correct_bracketing(String::from(\"()\"))\n/// true\n/// >>> correct_bracketing(String::from(\"(()())\"))\n/// true\n/// >>> correct_bracketing(String::from(\")(()\"))\n/// false\nfn correct_bracketing(brackets: String) -> bool {\n let mut stack = Vec::new();\n for c in brackets.chars() {\n match c {\n '(' => stack.push('('),\n ')' => {\n if stack.is_empty() {\n return false;\n }\n stack.pop();\n }\n _ => (),\n }\n }\n stack.is_empty()"], ["/// xs represent coefficients of a polynomial.\n/// xs[0] + xs[1] * x + xs[2] * x^2 + ....\n/// Return derivative of this polynomial in the same form.\n/// >>> derivative(vec![3, 1, 2, 4, 5])\n/// vec![1, 4, 12, 20]\n/// >>> derivative(vec![1, 2, 3])\n/// vec![2, 6]\nfn derivative(xs: Vec) -> Vec {\n let mut result = Vec::new();\n for i in 1..xs.len() {\n result.push(xs[i] * i as isize);\n }\n result"], ["/// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n/// fibfib(0) == 0\n/// fibfib(1) == 0\n/// fibfib(2) == 1\n/// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n/// Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n/// >>> fibfib(1)\n/// 0\n/// >>> fibfib(5)\n/// 4\n/// >>> fibfib(8)\n/// 24\nfn fibfib(n: isize) -> isize {\n let mut fibfib_seq = vec![0, 0, 1];\n for i in 3..=n {\n fibfib_seq.push(fibfib_seq[i as usize - 1] + fibfib_seq[i as usize - 2] + fibfib_seq[i as usize - 3]);\n }\n fibfib_seq[n as usize]"], ["/// Write a function vowels_count which takes a string representing\n/// a word as input and returns the number of vowels in the string.\n/// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n/// vowel, but only when it is at the end of the given word.\n/// Example:\n/// >>> vowels_count(String::from(\"abcde\"))\n/// 2\n/// >>> vowels_count(String::from(\"ACEDY\"))\n/// 3\nfn vowels_count(s: String) -> isize {\n let mut count = 0;\n for c in s.chars() {\n match c {\n 'a' | 'e' | 'i' | 'o' | 'u' | 'y' => count += 1,\n _ => (),\n }\n }\n count"], ["/// Circular shift the digits of the integer x, shift the digits right by shift\n/// and return the result as a string.\n/// If shift > number of digits, return digits reversed.\n/// >>> circular_shift(12, 1)\n/// String::from(\"21\")\n/// >>> circular_shift(12, 2)\n/// String::from(\"12\")\nfn circular_shift(x: isize, shift: isize) -> String {\n let mut digits: Vec = x.to_string().chars().collect();\n let len = digits.len() as isize;\n if shift > len {\n digits.reverse();\n } else {\n let shift = shift % len;\n let mut shifted = vec![0; len as usize];\n for i in 0..len {\n let j = (i + len - shift) % len;\n shifted[j as usize] = digits[i as usize];\n }\n digits = shifted;\n }\n digits.iter().collect()"], ["/// Task\n/// Write a function that takes a string as input and returns the sum of the upper characters only'\n/// ASCII codes.\n/// Examples:\n/// >>> digitSum(String::from(\"\"))\n/// 0\n/// >>> digitSum(String::from(\"abAB\"))\n/// 131\n/// >>> digitSum(String::from(\"abcCd\"))\n/// 67\n/// >>> digitSum(String::from(\"helloE\"))\n/// 69\n/// >>> digitSum(String::from(\"woArBld\"))\n/// 131\n/// >>> digitSum(String::from(\"aAaaaXa\"))\n/// 153\nfn digitSum(s: String) -> isize {\n s.chars().fold(0, |acc, c| if c.is_uppercase() { acc + c as isize } else { acc })"], ["/// In this task, you will be given a string that represents a number of apples and oranges \n/// that are distributed in a basket of fruit this basket contains \n/// apples, oranges, and mango fruits. Given the string that represents the total number of \n/// the oranges and apples and an integer that represent the total number of the fruits \n/// in the basket return the number of the mango fruits in the basket.\n/// for examble:\n/// >>> fruit_distribution(String::from(\"5 apples and 6 oranges\"), 19)\n/// 8\n/// >>> fruit_distribution(String::from(\"0 apples and 1 oranges\"), 3)\n/// 2\n/// >>> fruit_distribution(String::from(\"2 apples and 3 oranges\"), 100)\n/// 95\n/// >>> fruit_distribution(String::from(\"100 apples and 1 oranges\"), 120)\n/// 19\nfn fruit_distribution(s: String, n: isize) -> isize {\n let mut count = 0;\n let mut total = 0;\n let mut num_str = String::new();\n let mut num = 0;\n let mut fruit = String::new();\n let mut fruits = vec![];\n\n for c in s.chars() {\n if c.is_digit(10) {\n num_str.push(c);\n } else if c == ' ' {\n num = num_str.parse::().unwrap();\n num_str = String::new();\n } else {\n fruit.push(c);\n if fruit.len() > 0 {\n fruits.push(fruit.clone());\n fruit = String::new();\n }\n }\n }\n\n for i in 0..fruits.len() {\n if fruits[i] == \"apples\" {\n count += num;\n } else if fruits[i] == \"oranges\" {\n count += num;\n }\n }\n\n total = n - count;\n\n total"], ["/// \"Given a vector representing a branch of a tree that has non-negative integer nodes\n/// your task is to pluck one of the nodes and return it.\n/// The plucked node should be the node with the smallest even value.\n/// If multiple nodes with the same smallest even value are found return the node that has smallest index.\n/// The plucked node should be returned in a vector, [ smalest_value, its index ],\n/// If there are no even values or the given vector is empty, return [].\n/// Example 1:\n/// >>> pluck(vec![4, 2, 3])\n/// vec![2, 1]\n/// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n/// Example 2:\n/// >>> pluck(vec![1, 2, 3])\n/// vec![2, 1]\n/// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n/// Example 3:\n/// >>> pluck(vec![])\n/// Vec::::new()\n/// Example 4:\n/// >>> pluck(vec![5, 0, 3, 0, 4, 2])\n/// vec![0, 1]\n/// Explanation: 0 is the smallest value, but there are two zeros,\n/// so we will choose the first zero, which has the smallest index.\n/// Constraints:\n/// * 1 <= nodes.length <= 10000\n/// * 0 <= node.value\nfn pluck(arr: Vec) -> Vec {\n let mut min_even = isize::MAX;\n let mut min_index = -1;\n for (i, &val) in arr.iter().enumerate() {\n if val % 2 == 0 && val < min_even {\n min_even = val;\n min_index = i as isize;\n }\n }\n if min_index == -1 {\n vec![min_even, min_index]\n } else {\n vec![min_even, min_index]\n }"], ["/// You are given a non-empty vector of positive integers. Return the greatest integer that is greater than \n/// zero, and has a frequency greater than or equal to the value of the integer itself. \n/// The frequency of an integer is the number of times it appears in the vector.\n/// If no such a value exist, return -1.\n/// Examples:\n/// >>> search(vec![4, 1, 2, 2, 3, 1])\n/// 2\n/// >>> search(vec![1, 2, 2, 3, 3, 3, 4, 4, 4])\n/// 3\n/// >>> search(vec![5, 5, 4, 4, 4])\n/// -1\nfn search(lst: Vec) -> isize {\n let mut freq = std::collections::HashMap::new();\n for &num in lst.iter() {\n *freq.entry(num).or_insert(0) += 1;\n }\n for num in (1..).rev() {\n if *freq.get(&num).unwrap_or(&0) >= num {\n return num;\n }\n }\n -1"], ["/// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n/// For each of the group, output the deepest level of nesting of parentheses.\n/// E.g. (()()) has maximum two levels of nesting while ((())) has three.\n/// >>> parse_nested_parens(String::from(\"(()()) ((())) () ((())()())\"))\n/// vec![2, 3, 1, 3]\nfn parse_nested_parens(paren_string: String) -> Vec {\n let mut max_depths = Vec::new();\n let mut current_depth = 0;\n for c in paren_string.chars() {\n match c {\n '(' => {\n current_depth += 1;\n if current_depth > max_depths.len() as isize {\n max_depths.push(current_depth);\n }\n }\n ')' => {\n current_depth -= 1;\n }\n _ => {}\n }\n }\n max_depths"], ["/// Given vector of integers, return vector in strange order.\n/// Strange sorting, is when you start with the minimum value,\n/// then maximum of the remaining integers, then minimum and so on.\n/// Examples:\n/// >>> strange_sort_list(vec![1, 2, 3, 4])\n/// vec![1, 4, 2, 3]\n/// >>> strange_sort_list(vec![5, 5, 5, 5])\n/// vec![5, 5, 5, 5]\n/// >>> strange_sort_list(vec![])\n/// Vec::::new()\nfn strange_sort_list(lst: Vec) -> Vec {\n let mut sorted = lst.clone();\n sorted.sort();\n let mut result = Vec::new();\n let mut i = 0;\n let mut j = sorted.len() - 1;\n while i <= j {\n result.push(sorted[i]);\n if i != j {\n result.push(sorted[j]);\n }\n i += 1;\n j -= 1;\n }\n result"], ["/// Given the lengths of the three sides of a triangle. Return the area of\n/// the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n/// Otherwise return -1\n/// Three sides make a valid triangle when the sum of any two sides is greater \n/// than the third side.\n/// Example:\n/// >>> triangle_area(3, 4, 5)\n/// 6.0\n/// >>> triangle_area(1, 2, 10)\n/// -1.0\nfn triangle_area(a: isize, b: isize, c: isize) -> f64 {\n if a + b > c && a + c > b && b + c > a {\n let s = (a + b + c) as f64 / 2.0;\n let area = (s * (s - a as f64) * (s - b as f64) * (s - c as f64)).sqrt();\n (area * 100.0).round() / 100.0\n } else {\n -1.0\n }"], ["/// Write a function that returns true if the object q will fly, and false otherwise.\n/// The object q will fly if it's balanced (it is a palindromic vector) and the sum of its elements is less than or equal the maximum possible weight w.\n/// Example:\n/// >>> will_it_fly(vec![1, 2], 5)\n/// false\n/// # 1+2 is less than the maximum possible weight, but it's unbalanced.\n/// >>> will_it_fly(vec![3, 2, 3], 1)\n/// false\n/// # it's balanced, but 3+2+3 is more than the maximum possible weight.\n/// >>> will_it_fly(vec![3, 2, 3], 9)\n/// true\n/// # 3+2+3 is less than the maximum possible weight, and it's balanced.\n/// >>> will_it_fly(vec![3], 5)\n/// true\n/// # 3 is less than the maximum possible weight, and it's balanced.\nfn will_it_fly(q: Vec, w: isize) -> bool {\n let mut sum = 0;\n for i in 0..q.len() {\n sum += q[i];\n }\n if sum > w {\n return false;\n }\n for i in 0..q.len()/2 {\n if q[i] != q[q.len()-1-i] {\n return false;\n }\n }\n true"], ["/// Given a vector arr of integers, find the minimum number of elements that\n/// need to be changed to make the vector palindromic. A palindromic vector is a vector that\n/// is read the same backwards and forwards. In one change, you can change one element to any other element.\n/// For example:\n/// >>> smallest_change(vec![1, 2, 3, 5, 4, 7, 9, 6])\n/// 4\n/// >>> smallest_change(vec![1, 2, 3, 4, 3, 2, 2])\n/// 1\n/// >>> smallest_change(vec![1, 2, 3, 2, 1])\n/// 0\nfn smallest_change(arr: Vec) -> isize {\n let mut count = 0;\n let mut i = 0;\n let mut j = arr.len() - 1;\n\n while i < j {\n if arr[i] != arr[j] {\n count += 1;\n }\n i += 1;\n j -= 1;\n }\n\n count"], ["/// Write a function that accepts two vectors of strings and returns the vector that has \n/// total number of chars in the all strings of the vector less than the other vector.\n/// if the two vectors have the same number of chars, return the first vector.\n/// Examples\n/// >>> total_match(vec![], vec![])\n/// Vec::::new()\n/// >>> total_match(vec![String::from(\"hi\"), String::from(\"admin\")], vec![String::from(\"hI\"), String::from(\"Hi\")])\n/// vec![String::from(\"hI\"), String::from(\"Hi\")]\n/// >>> total_match(vec![String::from(\"hi\"), String::from(\"admin\")], vec![String::from(\"hi\"), String::from(\"hi\"), String::from(\"admin\"), String::from(\"project\")])\n/// vec![String::from(\"hi\"), String::from(\"admin\")]\n/// >>> total_match(vec![String::from(\"hi\"), String::from(\"admin\")], vec![String::from(\"hI\"), String::from(\"hi\"), String::from(\"hi\")])\n/// vec![String::from(\"hI\"), String::from(\"hi\"), String::from(\"hi\")]\n/// >>> total_match(vec![String::from(\"4\")], vec![String::from(\"1\"), String::from(\"2\"), String::from(\"3\"), String::from(\"4\"), String::from(\"5\")])\n/// vec![String::from(\"4\")]\nfn total_match(lst1: Vec, lst2: Vec) -> Vec {\n let lst1_len = lst1.iter().map(|s| s.len()).sum::();\n let lst2_len = lst2.iter().map(|s| s.len()).sum::();\n if lst1_len < lst2_len {\n lst1\n } else {\n lst2\n }"], ["/// Write a function that returns true if the given number is the multiplication of 3 prime numbers\n/// and false otherwise.\n/// Knowing that (a) is less then 100. \n/// Example:\n/// >>> is_multiply_prime(30)\n/// true\n/// 30 = 2 * 3 * 5\nfn is_multiply_prime(a: isize) -> bool {\n let mut num = a;\n let mut count = 0;\n let mut primes = vec![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];\n\n for prime in primes.iter() {\n while num % prime == 0 {\n num /= prime;\n count += 1;\n }\n }\n\n count == 3 && num == 1"], ["/// Your task is to write a function that returns true if a number x is a simple\n/// power of n and false in other cases.\n/// x is a simple power of n if n**int=x\n/// For example:\n/// >>> is_simple_power(1, 4)\n/// true\n/// >>> is_simple_power(2, 2)\n/// true\n/// >>> is_simple_power(8, 2)\n/// true\n/// >>> is_simple_power(3, 2)\n/// false\n/// >>> is_simple_power(3, 1)\n/// false\n/// >>> is_simple_power(5, 3)\n/// false\nfn is_simple_power(x: isize, n: isize) -> bool {\n if x == 1 {\n return true;\n }\n let mut power = n;\n while power < x {\n power *= n;\n }\n power == x"], ["/// Write a function that takes an integer a and returns true \n/// if this ingeger is a cube of some integer number.\n/// Note: you may assume the input is always valid.\n/// Examples:\n/// >>> iscube(1)\n/// true\n/// >>> iscube(2)\n/// false\n/// >>> iscube(-1)\n/// true\n/// >>> iscube(64)\n/// true\n/// >>> iscube(0)\n/// true\n/// >>> iscube(180)\n/// false\nfn iscube(a: isize) -> bool {\n let cube_root = (a as f64).cbrt().round() as isize;\n cube_root * cube_root * cube_root == a"], ["/// You have been tasked to write a function that receives \n/// a hexadecimal number as a string and counts the number of hexadecimal \n/// digits that are primes (prime number, or a prime, is a natural number \n/// greater than 1 that is not a product of two smaller natural numbers).\n/// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n/// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n/// So you have to determine a number of the following digits: 2, 3, 5, 7, \n/// B (=decimal 11), D (=decimal 13).\n/// Note: you may assume the input is always correct or empty string, \n/// and symbols A,B,C,D,E,F are always uppercase.\n/// Examples:\n/// >>> hex_key(String::from(\"AB\"))\n/// 1\n/// >>> hex_key(String::from(\"1077E\"))\n/// 2\n/// >>> hex_key(String::from(\"ABED1A33\"))\n/// 4\n/// >>> hex_key(String::from(\"123456789ABCDEF0\"))\n/// 6\n/// >>> hex_key(String::from(\"2020\"))\n/// 2\nfn hex_key(num: String) -> isize {\n let mut count = 0;\n for c in num.chars() {\n match c {\n '2' | '3' | '5' | '7' | 'B' | 'D' => count += 1,\n _ => (),\n }\n }\n count"], ["/// You will be given a number in decimal form and your task is to convert it to\n/// binary format. The function should return a string, with each character representing a binary\n/// number. Each character in the string will be '0' or '1'.\n/// There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n/// The extra characters are there to help with the format.\n/// Examples:\n/// >>> decimal_to_binary(15)\n/// String::from(\"db1111db\")\n/// >>> decimal_to_binary(32)\n/// String::from(\"db100000db\")\nfn decimal_to_binary(decimal: isize) -> String {\n let binary = format!(\"{:b}\", decimal);\n format!(\"db{}db\", binary)"], ["/// Filter an input vector of strings only for ones that contain given substring\n/// >>> filter_by_substring(vec![], String::from(\"a\"))\n/// Vec::::new()\n/// >>> filter_by_substring(vec![String::from(\"abc\"), String::from(\"bacd\"), String::from(\"cde\"), String::from(\"array\")], String::from(\"a\"))\n/// vec![String::from(\"abc\"), String::from(\"bacd\"), String::from(\"array\")]\nfn filter_by_substring(strings: Vec, substring: String) -> Vec {\n strings.into_iter().filter(|s| s.contains(&substring)).collect()"], ["/// You are given a string s.\n/// Your task is to check if the string is haprs or not.\n/// A string is haprs if its length is at least 3 and every 3 consecutive letters are distinct\n/// For example:\n/// >>> is_happy(String::from(\"a\"))\n/// false\n/// >>> is_happy(String::from(\"aa\"))\n/// false\n/// >>> is_happy(String::from(\"abcd\"))\n/// true\n/// >>> is_happy(String::from(\"aabb\"))\n/// false\n/// >>> is_happy(String::from(\"adb\"))\n/// true\n/// >>> is_happy(String::from(\"xyy\"))\n/// false\nfn is_happy(s: String) -> bool {\n if s.len() < 3 {\n return false;\n }\n let mut prev = s.chars().nth(0).unwrap();\n let mut curr = s.chars().nth(1).unwrap();\n for c in s.chars().skip(2) {\n if prev != curr && curr != c && prev != c {\n return true;\n }\n prev = curr;\n curr = c;\n }\n false"], ["/// It is the last week of the semester and the teacher has to give the grades\n/// to students. The teacher has been making her own algorithm for grading.\n/// The only problem is, she has lost the code she used for grading.\n/// She has given you a vector of GPAs for some students and you have to write \n/// a function that can output a vector of letter grades using the following table:\n/// GPA | Letter grade\n/// 4.0 A+\n/// > 3.7 A \n/// > 3.3 A- \n/// > 3.0 B+\n/// > 2.7 B \n/// > 2.3 B-\n/// > 2.0 C+\n/// > 1.7 C\n/// > 1.3 C-\n/// > 1.0 D+ \n/// > 0.7 D \n/// > 0.0 D-\n/// 0.0 E\n/// Example:\n/// >>> grade_equation(vec![4.0, 3, 1.7, 2, 3.5])\n/// vec![String::from(\"A+\"), String::from(\"B\"), String::from(\"C-\"), String::from(\"C\"), String::from(\"A-\")]\nfn numerical_letter_grade(grades: Vec) -> Vec {\n grades.iter().map(|&g| match g {\n g if g >= 4.0 => \"A+\".to_string(),\n g if g > 3.7 => \"A\".to_string(),\n g if g > 3.3 => \"A-\".to_string(),\n g if g > 3.0 => \"B+\".to_string(),\n g if g > 2.7 => \"B\".to_string(),\n g if g > 2.3 => \"B-\".to_string(),\n g if g > 2.0 => \"C+\".to_string(),\n g if g > 1.7 => \"C\".to_string(),\n g if g > 1.3 => \"C-\".to_string(),\n g if g > 1.0 => \"D+\".to_string(),\n g if g > 0.7 => \"D\".to_string(),\n g if g > 0.0 => \"D-\".to_string(),\n _ => \"E\".to_string(),\n }).collect()"], ["/// Write a function that takes a string and returns true if the string\n/// length is a prime number or false otherwise\n/// Examples\n/// >>> prime_length(String::from(\"Hello\"))\n/// true\n/// >>> prime_length(String::from(\"abcdcba\"))\n/// true\n/// >>> prime_length(String::from(\"kittens\"))\n/// true\n/// >>> prime_length(String::from(\"orange\"))\n/// false\nfn prime_length(string: String) -> bool {\n let length = string.len();\n if length < 2 {\n return false;\n }\n for i in 2..length {\n if length % i == 0 {\n return false;\n }\n }\n true"], ["/// Given a positive integer n, return the count of the numbers of n-digit\n/// positive integers that start or end with 1.\nfn starts_one_ends(n: isize) -> isize {\n if n == 1 {\n return 1;\n }\n let mut count = 0;\n for i in 0..n {\n count += (10_isize.pow(i) - 1) * (10_isize.pow(n - i - 1) - 1) + 1;\n }\n count"], ["/// Given a positive integer N, return the total sum of its digits in binary.\n/// Example\n/// >>> solve(1000)\n/// String::from(\"1\")\n/// >>> solve(150)\n/// String::from(\"110\")\n/// >>> solve(147)\n/// String::from(\"1100\")\n/// Variables:\n/// @N integer\n/// Constraints: 0 \u2264 N \u2264 10000.\n/// Output:\n/// a string of binary number\nfn solve(N: isize) -> String {\n let mut sum = 0;\n let mut n = N;\n while n > 0 {\n sum += n % 2;\n n /= 2;\n }\n format!(\"{:b}\", sum)"], ["/// Given a non-empty vector of integers lst. add the even elements that are at odd indices..\n/// Examples:\n/// >>> add(vec![4, 2, 6, 7])\n/// 2\nfn add(lst: Vec) -> isize {\n lst.iter().enumerate()\n .filter(|&(i, _)| i % 2 != 0)\n .filter(|&(_, x)| x % 2 == 0)\n .map(|(_, x)| x)\n .sum()"], ["/// Write a function that takes a string and returns an ordered version of it.\n/// Ordered version of string, is a string where all words (separated by space)\n/// are replaced by a new word where all the characters arranged in\n/// ascending order based on ascii value.\n/// Note: You should keep the order of words and blank spaces in the sentence.\n/// For example:\n/// >>> anti_shuffle(String::from(\"Hi\"))\n/// String::from(\"Hi\")\n/// >>> anti_shuffle(String::from(\"hello\"))\n/// String::from(\"ehllo\")\n/// >>> anti_shuffle(String::from(\"Hello World!!!\"))\n/// String::from(\"Hello !!!Wdlor\")\nfn anti_shuffle(s: String) -> String {\n s.split_whitespace()\n .map(|word| {\n let mut chars: Vec = word.chars().collect();\n chars.sort_by(|a, b| a.cmp(b));\n chars.into_iter().collect()\n })\n .collect::>()\n .join(\" \")"], ["/// You are given a 2 dimensional data, as a nested vectors,\n/// which is similar to matrix, however, unlike matrices,\n/// each row may contain a different number of columns.\n/// Given lst, and integer x, find integers x in the vector,\n/// and return vector of tuples, [(x1, y1), (x2, y2) ...] such that\n/// each tuple is a coordinate - (row, columns), starting with 0.\n/// Sort coordinates initially by rows in ascending order.\n/// Also, sort coordinates of the row by columns in descending order.\n/// Examples:\n/// >>> get_row(vec![vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 1, 6], vec![1, 2, 3, 4, 5, 1]], 1)\n/// vec![(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n/// >>> get_row(vec![], 1)\n/// Vec::<(isize, isize)>::new()\n/// >>> get_row(vec![vec![], vec![1], vec![1, 2, 3]], 3)\n/// vec![(2, 2)]\nfn get_row(lst: Vec>, x: isize) -> Vec<(isize, isize)> {\n let mut result = Vec::new();\n for (i, row) in lst.iter().enumerate() {\n for (j, &val) in row.iter().enumerate() {\n if val == x {\n result.push((i as isize, j as isize));\n }\n }\n }\n result.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));\n result"], ["/// Given a vector of non-negative integers, return a cors of the given vector after sorting,\n/// you will sort the given vector in ascending order if the sum( first index value, last index value) is odd,\n/// or sort it in descending order if the sum( first index value, last index value) is even.\n/// Note:\n/// * don't change the given vector.\n/// Examples:\n/// >>> sort_array(vec![])\n/// Vec::::new()\n/// >>> sort_array(vec![5])\n/// vec![5]\n/// >>> sort_array(vec![2, 4, 3, 0, 1, 5])\n/// vec![0, 1, 2, 3, 4, 5]\n/// >>> sort_array(vec![2, 4, 3, 0, 1, 5, 6])\n/// vec![6, 5, 4, 3, 2, 1, 0]\nfn sort_array(array: Vec) -> Vec {\n let mut sorted = array.clone();\n sorted.sort();\n if (sorted[0] + sorted[sorted.len() - 1]) % 2 == 0 {\n sorted.reverse();\n }\n sorted"], ["/// Create a function encrypt that takes a string as an argument and\n/// returns a string encrypted with the alphabet being rotated. \n/// The alphabet should be rotated in a manner such that the letters \n/// shift down by two multiplied to two places.\n/// For example:\n/// >>> encrypt(String::from(\"hi\"))\n/// String::from(\"lm\")\n/// >>> encrypt(String::from(\"asdfghjkl\"))\n/// String::from(\"ewhjklnop\")\n/// >>> encrypt(String::from(\"gf\"))\n/// String::from(\"kj\")\n/// >>> encrypt(String::from(\"et\"))\n/// String::from(\"ix\")\nfn encrypt(s: String) -> String {\n let mut encrypted = String::new();\n for c in s.chars() {\n let mut new_c = c as u8 + 2 * 2;\n if new_c > 'z' as u8 {\n new_c -= 26;\n }\n encrypted.push(new_c as char);\n }\n encrypted"], ["/// For a given vector of integers, return a tuple consisting of a sum and a product of all the integers in a vector.\n/// Empty sum should be equal to 0 and empty product should be equal to 1.\n/// >>> sum_product(vec![])\n/// (0, 1)\n/// >>> sum_product(vec![1, 2, 3, 4])\n/// (10, 24)\nfn sum_product(numbers: Vec) -> (isize, isize) {\n let mut sum = 0;\n let mut product = 1;\n\n for number in numbers {\n sum += number;\n product *= number;\n }\n\n (sum, product)"], ["/// You are given a vector of integers.\n/// Write a function next_smallest() that returns the 2nd smallest element of the vector.\n/// Return None if there is no such element.\n/// >>> next_smallest(vec![1, 2, 3, 4, 5])\n/// Some(2)\n/// >>> next_smallest(vec![5, 1, 4, 3, 2])\n/// Some(2)\n/// >>> next_smallest(vec![])\n/// None\n/// >>> next_smallest(vec![1, 1])\n/// None\nfn next_smallest(lst: Vec) -> Option {\n if lst.len() < 2 {\n return None;\n }\n let mut smallest = lst[0];\n let mut second_smallest = lst[1];\n if second_smallest < smallest {\n std::mem::swap(&mut smallest, &mut second_smallest);\n }\n for &num in &lst[2..] {\n if num < smallest {\n second_smallest = smallest;\n smallest = num;\n } else if num < second_smallest && num != smallest {\n second_smallest = num;\n }\n }\n if smallest == second_smallest {\n None\n } else {\n Some(second_smallest)\n }"], ["/// You'll be given a string of words, and your task is to count the number\n/// of boredoms. A boredom is a sentence that starts with the word \"I\".\n/// Sentences are delimited by '.', '?' or '!'.\n/// For example:\n/// >>> is_bored(String::from(\"Hello world\"))\n/// 0\n/// >>> is_bored(String::from(\"The sky is blue. The sun is shining. I love this weather\"))\n/// 1\nfn is_bored(S: String) -> isize {\n let mut count = 0;\n let mut sentence = String::new();\n\n for c in S.chars() {\n sentence.push(c);\n\n if c == '.' || c == '?' || c == '!' {\n if sentence.starts_with(\"I \") {\n count += 1;\n }\n\n sentence = String::new();\n }\n }\n\n count"], ["/// Create a function that takes 3 numbers.\n/// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n/// Returns false in any other cases.\n/// Examples\n/// >>> any_int(5, 2, 7)\n/// true\n/// >>> any_int(3, 2, 2)\n/// false\n/// >>> any_int(3, -2, 1)\n/// true\n/// >>> any_int(3.6, -2.2, 2)\n/// false\nfn any_int(x: f64, y: f64, z: f64) -> bool {\n if x.is_integer() && y.is_integer() && z.is_integer() {\n return x == y + z || y == x + z || z == x + y;\n }\n false"], ["/// Write a function that takes a message, and encodes in such a \n/// way that it swaps case of all letters, replaces all vowels in \n/// the message with the letter that appears 2 places ahead of that \n/// vowel in the english alphabet. \n/// Assume only letters. \n/// Examples:\n/// >>> encode(String::from(\"test\"))\n/// String::from(\"TGST\")\n/// >>> encode(String::from(\"This is a message\"))\n/// String::from(\"tHKS KS C MGSSCGG\")\nfn encode(message: String) -> String {\n let mut encoded = String::new();\n for c in message.chars() {\n let mut new_c = c;\n if c.is_alphabetic() {\n new_c = match c.to_ascii_lowercase() {\n 'a' => 'c',\n 'e' => 'g',\n 'i' => 'k',\n 'o' => 'q',\n 'u' => 's',\n 'y' => 'a',\n _ => c,\n };\n if c.is_uppercase() {\n new_c = new_c.to_uppercase();\n }\n }\n encoded.push(new_c);\n }\n encoded"], ["/// You are given a vector of integers.\n/// You need to find the largest prime value and return the sum of its digits.\n/// Examples:\n/// >>> skjkasdkd(vec![0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3])\n/// 10\n/// >>> skjkasdkd(vec![1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1])\n/// 25\n/// >>> skjkasdkd(vec![1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3])\n/// 13\n/// >>> skjkasdkd(vec![0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6])\n/// 11\n/// >>> skjkasdkd(vec![0, 81, 12, 3, 1, 21])\n/// 3\n/// >>> skjkasdkd(vec![0, 8, 1, 2, 1, 7])\n/// 7\nfn skjkasdkd(lst: Vec) -> isize {\n let mut largest_prime = 0;\n for num in lst {\n if is_prime(num) && num > largest_prime {\n largest_prime = num;\n }\n }\n sum_of_digits(largest_prime)"], ["use std::collections::HashMap;\n\n/// Given a HashMap, return true if all keys are strings in lower \n/// case or all keys are strings in upper case, else return false.\n/// The function should return false is the given HashMap is empty.\n/// Examples:\n/// >>> check_dict_case(HashMap::from([(String::from(\"a\"), String::from(\"apple\")), (String::from(\"b\"), String::from(\"banana\"))]))\n/// true\n/// >>> check_dict_case(HashMap::from([(String::from(\"a\"), String::from(\"apple\")), (String::from(\"A\"), String::from(\"banana\")), (String::from(\"B\"), String::from(\"banana\"))]))\n/// false\n/// >>> check_dict_case(HashMap::from([(String::from(\"a\"), String::from(\"apple\")), (8, String::from(\"banana\")), (String::from(\"a\"), String::from(\"apple\"))]))\n/// false\n/// >>> check_dict_case(HashMap::from([(String::from(\"Name\"), String::from(\"John\")), (String::from(\"Age\"), String::from(\"36\")), (String::from(\"City\"), String::from(\"Houston\"))]))\n/// false\n/// >>> check_dict_case(HashMap::from([(String::from(\"STATE\"), String::from(\"NC\")), (String::from(\"ZIP\"), String::from(\"12345\"))]))\n/// true\nfn check_dict_case(dict: HashMap) -> bool {\n if dict.is_empty() {\n return false;\n }\n\n let mut all_lower = true;\n let mut all_upper = true;\n\n for key in dict.keys() {\n if !key.is_ascii() {\n return false;\n }\n\n if key.to_lowercase() != key {\n all_lower = false;\n }\n\n if key.to_uppercase() != key {\n all_upper = false;\n }\n }\n\n all_lower || all_upper"], ["/// Implement a function that takes an non-negative integer and returns a vector of the first n\n/// integers that are prime numbers and less than n.\n/// for example:\n/// >>> count_up_to(5)\n/// vec![2, 3]\n/// >>> count_up_to(11)\n/// vec![2, 3, 5, 7]\n/// >>> count_up_to(0)\n/// Vec::::new()\n/// >>> count_up_to(20)\n/// vec![2, 3, 5, 7, 11, 13, 17, 19]\n/// >>> count_up_to(1)\n/// Vec::::new()\n/// >>> count_up_to(18)\n/// vec![2, 3, 5, 7, 11, 13, 17]\nfn count_up_to(n: isize) -> Vec {\n let mut primes = Vec::new();\n for i in 2..n {\n let mut is_prime = true;\n for j in 2..i {\n if i % j == 0 {\n is_prime = false;\n break;\n }\n }\n if is_prime {\n primes.push(i);\n }\n }\n primes"], ["/// Complete the function that takes two integers and returns \n/// the product of their unit digits.\n/// Assume the input is always valid.\n/// Examples:\n/// >>> multiply(148, 412)\n/// 16\n/// >>> multiply(19, 28)\n/// 72\n/// >>> multiply(2020, 1851)\n/// 0\n/// >>> multiply(14, -15)\n/// 20\nfn multiply(a: isize, b: isize) -> isize {\n (a % 10) * (b % 10)"], ["/// Given a string s, count the number of uppercase vowels in even indices.\n/// For example:\n/// >>> count_upper(String::from(\"aBCdEf\"))\n/// 1\n/// >>> count_upper(String::from(\"abcdefg\"))\n/// 0\n/// >>> count_upper(String::from(\"dBBE\"))\n/// 0\nfn count_upper(s: String) -> isize {\n let mut count = 0;\n for (i, c) in s.chars().enumerate() {\n if i % 2 == 0 && c.is_uppercase() && \"AEIOU\".contains(c) {\n count += 1;\n }\n }\n count"], ["/// Create a function that takes a value (string) representing a number\n/// and returns the closest integer to it. If the number is equidistant\n/// from two integers, round it away from zero.\n/// Examples\n/// >>> closest_integer(String::from(\"10\"))\n/// 10\n/// >>> closest_integer(String::from(\"15.3\"))\n/// 15\n/// Note:\n/// Rounding away from zero means that if the given number is equidistant\n/// from two integers, the one you should return is the one that is the\n/// farthest from zero. For example closest_integer(\"14.5\") should\n/// return 15 and closest_integer(\"-14.5\") should return -15.\nfn closest_integer(value: String) -> isize {\n let num: f64 = value.parse().unwrap();\n num.round() as isize"], ["/// From a given vector of integers, generate a vector of rolling maximum element found until given moment\n/// in the sequence.\n/// >>> rolling_max(vec![1, 2, 3, 2, 3, 4, 2])\n/// vec![1, 2, 3, 3, 3, 4, 4]\nfn rolling_max(numbers: Vec) -> Vec {\n let mut max_numbers = Vec::new();\n let mut current_max = isize::MIN;\n\n for number in numbers {\n if number > current_max {\n current_max = number;\n }\n max_numbers.push(current_max);\n }\n\n max_numbers"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-swift_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-swift_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..7fb4879c754a8b567cf390667b3ec5433e04f154 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/generations_CodeFuse-DeepSeek-33b/generations_multiple-swift_CodeFuse-DeepSeek-33b.json @@ -0,0 +1 @@ +[["/// Check if in given array of numbers, are any two numbers closer to each other than\n/// given threshold.\n/// >>> has_close_elements(numbers: [1.0, 2.0, 3.0], threshold: 0.5)\n/// false\n/// >>> has_close_elements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3)\n/// true\nfunc has_close_elements(numbers: [Double], threshold: Double) -> Bool {\n for i in 0..>> make_a_pile(n: 3)\n/// [3, 5, 7]\nfunc make_a_pile(n: Int) -> [Int] {\n var result = [Int]()\n var current = n\n for i in 1...n {\n result.append(current)\n if i % 2 == 1 {\n current += 2\n } else {\n current += 1\n }\n }\n return result"], ["/// You will be given a string of words separated by commas or spaces. Your task is\n/// to split the string into words and return an array of the words.\n/// For example:\n/// >>> words_string(s: \"Hi, my name is John\")\n/// [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n/// >>> words_string(s: \"One, two, three, four, five, six\")\n/// [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\nfunc words_string(s: String) -> [String] {\n return s.components(separatedBy: .whitespacesAndNewlines)"], ["/// This function takes two positive numbers x and y and returns the\n/// biggest even integer number that is in the range [x, y] inclusive. If \n/// there's no such number, then the function should return -1.\n/// For example:\n/// >>> choose_num(x: 12, y: 15)\n/// 14\n/// >>> choose_num(x: 13, y: 12)\n/// -1\nfunc choose_num(x: Int, y: Int) -> Int {\n var result = -1\n for i in x...y {\n if i % 2 == 0 && i > result {\n result = i\n }\n }\n return result"], ["extension Int: Error {}\n \n/// You are given two positive integers n and m, and your task is to compute the\n/// average of the integers from n through m (including n and m). \n/// Round the answer to the nearest integer and convert that to binary.\n/// If n is greater than m, return -1.\n/// Example:\n/// >>> rounded_avg(n: 1, m: 5)\n/// .success(\"0b11\")\n/// >>> rounded_avg(n: 7, m: 5)\n/// .failure(-1)\n/// >>> rounded_avg(n: 10, m: 20)\n/// .success(\"0b1111\")\n/// >>> rounded_avg(n: 20, m: 33)\n/// .success(\"0b11010\")\nfunc rounded_avg(n: Int, m: Int) -> Result {\n guard n <= m else { return .failure(-1) }\n let avg = Double(n + m) / 2.0\n let roundedAvg = Int(round(avg))\n let binary = String(roundedAvg, radix: 2)\n return .success(binary)"], ["/// Given an array of positive integers x. return a sorted array of all \n/// elements that hasn't any even digit.\n/// Note: Returned array should be sorted in increasing order.\n/// For example:\n/// >>> unique_digits(x: [15, 33, 1422, 1])\n/// [1, 15, 33]\n/// >>> unique_digits(x: [152, 323, 1422, 10])\n/// [] as [Int]\nfunc unique_digits(x: [Int]) -> [Int] {\n var result: [Int] = []\n for num in x {\n var hasEvenDigit = false\n var temp = num\n while temp > 0 {\n let digit = temp % 10\n if digit % 2 == 0 {\n hasEvenDigit = true\n break\n }\n temp /= 10\n }\n if !hasEvenDigit {\n result.append(num)\n }\n }\n return result.sorted()"], ["/// Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n/// reverse the resulting array, and then replace each digit by its corresponding name from\n/// \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n/// For example:\n/// >>> by_length(arr: [2, 1, 1, 4, 5, 8, 2, 3])\n/// [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n/// If the array is empty, return an empty array:\n/// >>> by_length(arr: [] as [Int])\n/// [] as [String]\n/// If the array has any strange number ignore it:\n/// >>> by_length(arr: [1, -1, 55])\n/// [\"One\"]\nfunc by_length(arr: [Int]) -> [String] {\n let sortedArr = arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed()\n let names = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"]\n return sortedArr.map { names[$0 - 1] }"], ["/// Implement the function f that takes n as a parameter,\n/// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even\n/// or the sum of numbers from 1 to i otherwise.\n/// i starts from 1.\n/// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n/// Example:\n/// >>> f(n: 5)\n/// [1, 2, 6, 24, 15]\nfunc f(n: Int) -> [Int] {\n var result = [Int]()\n for i in 1...n {\n if i % 2 == 0 {\n var factorial = 1\n for j in 1...i {\n factorial *= j\n }\n result.append(factorial)\n } else {\n var sum = 0\n for j in 1...i {\n sum += j\n }\n result.append(sum)\n }\n }\n return result"], ["/// Given a positive integer n, return a tuple that has the number of even and odd\n/// integer palindromes that fall within the range(1, n), inclusive.\n/// Example 1:\n/// >>> even_odd_palindrome(n: 3)\n/// (1, 2)\n/// Explanation:\n/// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n/// Example 2:\n/// >>> even_odd_palindrome(n: 12)\n/// (4, 6)\n/// Explanation:\n/// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n/// Note:\n/// 1. 1 <= n <= 10^3\n/// 2. returned tuple has the number of even and odd integer palindromes respectively.\nfunc even_odd_palindrome(n: Int) -> (Int, Int) {\n var evenCount = 0\n var oddCount = 0\n for i in 1...n {\n let str = String(i)\n if str == String(reversed(str)) {\n if i % 2 == 0 {\n evenCount += 1\n } else {\n oddCount += 1\n }\n }\n }\n return (evenCount, oddCount)"], ["/// Write a function count_nums which takes an array of integers and returns\n/// the number of elements which has a sum of digits > 0.\n/// If a number is negative, then its first signed digit will be negative:\n/// e.g. -123 has signed digits -1, 2, and 3.\n/// >>> count_nums(arr: [] as [Int])\n/// 0\n/// >>> count_nums(arr: [-1, 11, -11])\n/// 1\n/// >>> count_nums(arr: [1, 1, 2])\n/// 3\nfunc count_nums(arr: [Int]) -> Int {\n var count = 0\n for num in arr {\n var sum = 0\n var n = abs(num)\n while n > 0 {\n sum += n % 10\n n /= 10\n }\n if sum > 0 {\n count += 1\n }\n }\n return count"], ["/// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n/// numbers in the array will be randomly ordered. Your task is to determine if\n/// it is possible to get an array sorted in non-decreasing order by performing \n/// the following operation on the given array:\n/// You are allowed to perform right shift operation any number of times.\n/// One right shift operation means shifting all elements of the array by one\n/// position in the right direction. The last element of the array will be moved to\n/// the starting position in the array i.e. 0th index. \n/// If it is possible to obtain the sorted array by performing the above operation\n/// then return true else return false.\n/// If the given array is empty then return true.\n/// Note: The given array is guaranteed to have unique elements.\n/// For Example:\n/// >>> move_one_ball(arr: [3, 4, 5, 1, 2])\n/// true\n/// Explanation: By performin 2 right shift operations, non-decreasing order can\n/// be achieved for the given array.\n/// >>> move_one_ball(arr: [3, 5, 4, 1, 2])\n/// false\n/// Explanation:It is not possible to get non-decreasing order for the given\n/// array by performing any number of right shift operations.\nfunc move_one_ball(arr: [Int]) -> Bool {\n if arr.isEmpty {\n return true\n }\n let sortedArr = arr.sorted()\n let lastIndex = arr.count - 1\n for i in 0..>> make_palindrome(string: \"\")\n/// \"\"\n/// >>> make_palindrome(string: \"cat\")\n/// \"catac\"\n/// >>> make_palindrome(string: \"cata\")\n/// \"catac\"\nfunc make_palindrome(string: String) -> String {\n var reversed = String(string.reversed())\n for i in 0..>> exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4])\n/// \"YES\"\n/// >>> exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4])\n/// \"NO\"\n/// It is assumed that the input arrays will be non-empty.\nfunc exchange(lst1: [Int], lst2: [Int]) -> String {\n var evenCount = 0\n var oddCount = 0\n for num in lst1 {\n if num % 2 == 0 {\n evenCount += 1\n } else {\n oddCount += 1\n }\n }\n for num in lst2 {\n if num % 2 == 0 {\n evenCount += 1\n } else {\n oddCount += 1\n }\n }\n if evenCount == lst1.count {\n return \"YES\"\n } else {\n return \"NO\"\n }"], ["/// Given a string representing a space separated lowercase letters, return a dictionary\n/// of the letter with the most repetition and containing the corresponding count.\n/// If several letters have the same occurrence, return all of them.\n/// Example:\n/// >>> histogram(test: \"a b c\")\n/// [\"a\" : 1, \"b\" : 1, \"c\" : 1]\n/// >>> histogram(test: \"a b b a\")\n/// [\"a\" : 2, \"b\" : 2]\n/// >>> histogram(test: \"a b c a b\")\n/// [\"a\" : 2, \"b\" : 2]\n/// >>> histogram(test: \"b b b b a\")\n/// [\"b\" : 4]\n/// >>> histogram(test: \"\")\n/// [:] as [String : Int]\nfunc histogram(test: String) -> [String : Int] {\n var dict = [String : Int]()\n let words = test.split(separator: \" \")\n for word in words {\n dict[word, default: 0] += 1\n }\n let maxCount = dict.values.max() ?? 0\n return dict.filter { $0.value == maxCount }"], ["/// Task\n/// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n/// then check if the result string is palindrome.\n/// A string is called palindrome if it reads the same backward as forward.\n/// You should return a tuple containing the result string and true/false for the check.\n/// Example\n/// >>> reverse_delete(s: \"abcde\", c: \"ae\")\n/// (\"bcd\", false)\n/// >>> reverse_delete(s: \"abcdef\", c: \"b\")\n/// (\"acdef\", false)\n/// >>> reverse_delete(s: \"abcdedcba\", c: \"ab\")\n/// (\"cdedc\", true)\nfunc reverse_delete(s: String, c: String) -> (String, Bool) {\n let filteredString = s.filter { !c.contains($0) }\n let reversedString = String(filteredString.reversed())\n let isPalindrome = filteredString == reversedString\n return (filteredString, isPalindrome)"], ["/// Given an array of strings, where each string consists of only digits, return an array.\n/// Each element i of the output should be \"the number of odd elements in the\n/// string i of the input.\" where all the i's should be replaced by the number\n/// of odd digits in the i'th string of the input.\n/// >>> odd_count(lst: [\"1234567\"])\n/// [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n/// >>> odd_count(lst: [\"3\", \"11111111\"])\n/// [\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\nfunc odd_count(lst: [String]) -> [String] {\n var result: [String] = []\n for str in lst {\n var count = 0\n for char in str {\n if let digit = Int(String(char)) {\n if digit % 2 != 0 {\n count += 1\n }\n }\n }\n result.append(\"the number of odd elements \\(count)n the str\\(count)ng \\(count) of the \\(count)nput.\")\n }\n return result"], ["/// Given an array of integers nums, find the minimum sum of any non-empty sub-array\n/// of nums.\n/// Example\n/// >>> minSubArraySum(nums: [2, 3, 4, 1, 2, 4])\n/// 1\n/// >>> minSubArraySum(nums: [-1, -2, -3])\n/// -6\nfunc minSubArraySum(nums: [Int]) -> Int {\n var minSum = nums[0]\n var currSum = nums[0]\n for i in 1..>> max_fill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1)\n/// 6\n/// Example 2:\n/// >>> max_fill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2)\n/// 5\n/// Example 3:\n/// >>> max_fill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5)\n/// 0\n/// Constraints:\n/// * all wells have the same length\n/// * 1 <= grid.length <= 10^2\n/// * 1 <= grid[:,1].length <= 10^2\n/// * grid[i][j] -> 0 | 1\n/// * 1 <= capacity <= 10\nfunc max_fill(grid: [[Int]], capacity: Int) -> Int {\n var count = 0\n var currentCapacity = 0\n for row in grid {\n for well in row {\n if well == 1 {\n currentCapacity += 1\n if currentCapacity == capacity {\n count += 1\n currentCapacity = 0\n }\n }\n }\n }\n return count"], ["/// In this Kata, you have to sort an array of non-negative integers according to\n/// number of ones in their binary representation in ascending order.\n/// For similar number of ones, sort based on decimal value.\n/// It must be implemented like this:\n/// >>> sort_array(arr: [1, 5, 2, 3, 4])\n/// [1, 2, 3, 4, 5]\n/// >>> sort_array(arr: [-2, -3, -4, -5, -6])\n/// [-6, -5, -4, -3, -2]\n/// >>> sort_array(arr: [1, 0, 2, 3, 4])\n/// [0, 1, 2, 3, 4]\nfunc sort_array(arr: [Int]) -> [Int] {\n return arr.sorted { a, b in\n let aCount = String(a, radix: 2).filter { $0 == \"1\" }.count\n let bCount = String(b, radix: 2).filter { $0 == \"1\" }.count\n if aCount == bCount {\n return a < b\n } else {\n return aCount < bCount\n }\n }"], ["/// Given a string s and a natural number n, you have been tasked to implement \n/// a function that returns an array of all words from string s that contain exactly \n/// n consonants, in order these words appear in the string s.\n/// If the string s is empty then the function should return an empty array.\n/// Note: you may assume the input string contains only letters and spaces.\n/// Examples:\n/// >>> select_words(s: \"Mary had a little lamb\", n: 4)\n/// [\"little\"]\n/// >>> select_words(s: \"Mary had a little lamb\", n: 3)\n/// [\"Mary\", \"lamb\"]\n/// >>> select_words(s: \"simple white space\", n: 2)\n/// [] as [String]\n/// >>> select_words(s: \"Hello world\", n: 4)\n/// [\"world\"]\n/// >>> select_words(s: \"Uncle sam\", n: 3)\n/// [\"Uncle\"]\nfunc select_words(s: String, n: Int) -> [String] {\n let vowels = Set(\"aeiouAEIOU\")\n var result = [String]()\n for word in s.split(separator: \" \") {\n let consonants = word.filter { !vowels.contains($0) }\n if consonants.count == n {\n result.append(word)\n }\n }\n return result"], ["/// You are given a word. Your task is to find the closest vowel that stands between \n/// two consonants from the right side of the word (case sensitive).\n/// Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n/// find any vowel met the above condition. \n/// You may assume that the given string contains English letter only.\n/// Example:\n/// >>> get_closest_vowel(word: \"yogurt\")\n/// \"u\"\n/// >>> get_closest_vowel(word: \"FULL\")\n/// \"U\"\n/// >>> get_closest_vowel(word: \"quick\")\n/// \"\"\n/// >>> get_closest_vowel(word: \"ab\")\n/// \"\"\nfunc get_closest_vowel(word: String) -> String {\n let vowels = Set(\"aeiouAEIOU\")\n let consonants = Set(\"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ\")\n var closestVowel = \"\"\n var distance = Int.max\n for i in stride(from: word.count-1, through: 1, by: -1) {\n let char = word[word.index(word.startIndex, offsetBy: i)]\n if vowels.contains(char) {\n closestVowel = String(char)\n distance = 0\n } else if consonants.contains(char) {\n distance += 1\n }\n if distance == 2 {\n return closestVowel\n }\n }\n return \"\""], ["/// You are given an array of two strings, both strings consist of open\n/// parentheses '(' or close parentheses ')' only.\n/// Your job is to check if it is possible to concatenate the two strings in\n/// some order, that the resulting string will be good.\n/// A string S is considered to be good if and only if all parentheses in S\n/// are balanced. For example: the string '(())()' is good, while the string\n/// '())' is not.\n/// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n/// Examples:\n/// >>> match_parens(lst: [\"()(\", \")\"])\n/// \"Yes\"\n/// >>> match_parens(lst: [\")\", \")\"])\n/// \"No\"\nfunc match_parens(lst: [String]) -> String {\n var stack = [Character]()\n for c in lst.joined() {\n if c == \"(\" {\n stack.append(c)\n } else if c == \")\" {\n if stack.count > 0 && stack.last == \"(\" {\n stack.removeLast()\n } else {\n return \"No\"\n }\n }\n }\n return stack.count == 0 ? \"Yes\" : \"No\""], ["/// Input are two strings a and b consisting only of 1s and 0s.\n/// Perform binary XOR on these inputs and return result also as a string.\n/// >>> string_xor(a: \"010\", b: \"110\")\n/// \"100\"\nfunc string_xor(a: String, b: String) -> String {\n let aBits = Array(a.map { Int(String($0)) ?? 0 })\n let bBits = Array(b.map { Int(String($0)) ?? 0 })\n var result = [Int]()\n for i in 0..>> maximum(arr: [-3, -4, 5], k: 3)\n/// [-4, -3, 5]\n/// Example 2:\n/// >>> maximum(arr: [4, -4, 4], k: 2)\n/// [4, 4]\n/// Example 3:\n/// >>> maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1)\n/// [2]\n/// Note:\n/// 1. The length of the array will be in the range of [1, 1000].\n/// 2. The elements in the array will be in the range of [-1000, 1000].\n/// 3. 0 <= k <= len(arr)\nfunc maximum(arr: [Int], k: Int) -> [Int] {\n return arr.sorted().reversed().prefix(k)"], ["/// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.\n/// Examples\n/// >>> solution(lst: [5, 8, 7, 1])\n/// 12\n/// >>> solution(lst: [3, 3, 3, 3, 3])\n/// 9\n/// >>> solution(lst: [30, 13, 24, 321])\n/// 0\nfunc solution(lst: [Int]) -> Int {\n var sum = 0\n for (index, value) in lst.enumerated() {\n if index % 2 == 0 && value % 2 != 0 {\n sum += value\n }\n }\n return sum"], ["/// Given a non-empty array of integers arr and an integer k, return\n/// the sum of the elements with at most two digits from the first k elements of arr.\n/// Example:\n/// >>> add_elements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4)\n/// 24\n/// Constraints:\n/// 1. 1 <= len(arr) <= 100\n/// 2. 1 <= k <= len(arr)\nfunc add_elements(arr: [Int], k: Int) -> Int {\n var sum = 0\n for i in 0..>> get_odd_collatz(n: 5)\n/// [1, 5]\nfunc get_odd_collatz(n: Int) -> [Int] {\n var collatz = [Int]()\n var num = n\n while num != 1 {\n collatz.append(num)\n if num % 2 == 0 {\n num = num / 2\n } else {\n num = 3 * num + 1\n }\n }\n collatz.append(1)\n return collatz.filter { $0 % 2 != 0 }.sorted()"], ["/// You have to write a function which validates a given date string and\n/// returns true if the date is valid otherwise false.\n/// The date is valid if all of the following rules are satisfied:\n/// 1. The date string is not empty.\n/// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n/// 3. The months should not be less than 1 or higher than 12.\n/// 4. The date should be in the format: mm-dd-yyyy\n/// >>> valid_date(date: \"03-11-2000\")\n/// true\n/// >>> valid_date(date: \"15-01-2012\")\n/// false\n/// >>> valid_date(date: \"04-0-2040\")\n/// false\n/// >>> valid_date(date: \"06-04-2020\")\n/// true\n/// >>> valid_date(date: \"06/04/2020\")\n/// false\nfunc valid_date(date: String) -> Bool {\n // Check if the date string is empty\n if date.isEmpty {\n return false\n }\n \n // Split the date string into month, day, and year components\n let components = date.components(separatedBy: \"-\")\n guard components.count == 3 else {\n return false\n }\n \n // Parse the month, day, and year components\n let month = Int(components[0])\n let day = Int(components[1])\n let year = Int(components[2])\n \n // Check if the month is valid\n guard month != nil && month >= 1 && month <= 12 else {\n return false\n }\n \n // Check if the day is valid\n guard day != nil && day >= 1 else {\n return false\n }\n \n // Check if the year is valid\n guard year != nil else {\n return false\n }\n \n // Check if the number of days is valid for the given month\n switch month {\n case 1, 3, 5, 7, 8, 10, 12:\n guard day <= 31 else {\n return false\n }\n case 4, 6, 9, 11:\n guard day <= 30 else {\n return false\n }\n case 2:\n // Check if the year is a leap year\n let isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0\n guard day <= (isLeapYear ? 29 : 28) else {\n return false\n }\n default:\n return false\n }\n \n // The date is valid\n return true"], ["extension Int: Error {}\n \n/// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you\n/// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n/// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n/// Examples\n/// >>> split_words(txt: \"Hello world!\")\n/// .success([\"Hello\", \"world!\"])\n/// >>> split_words(txt: \"Hello,world!\")\n/// .success([\"Hello\", \"world!\"])\n/// >>> split_words(txt: \"abcdef\")\n/// .failure(3)\nfunc split_words(txt: String) -> Result<[String], Int> {\n if let words = txt.split(separator: \" \").map(String.init) {\n return .success(words)\n } else if let words = txt.split(separator: \",\").map(String.init) {\n return .success(words)\n } else {\n let lowercaseLetters = txt.filter { $0.isASCII && $0.isLowercase }\n let oddOrderLetters = lowercaseLetters.filter { $0.asciiValue % 2 == 1 }\n return .failure(oddOrderLetters.count)\n }"], ["/// Given an array of numbers, return whether or not they are sorted\n/// in ascending order. If array has more than 1 duplicate of the same\n/// number, return false. Assume no negative numbers and only integers.\n/// Examples\n/// >>> is_sorted(lst: [5])\n/// true\n/// >>> is_sorted(lst: [1, 2, 3, 4, 5])\n/// true\n/// >>> is_sorted(lst: [1, 3, 2, 4, 5])\n/// false\n/// >>> is_sorted(lst: [1, 2, 3, 4, 5, 6])\n/// true\n/// >>> is_sorted(lst: [1, 2, 3, 4, 5, 6, 7])\n/// true\n/// >>> is_sorted(lst: [1, 3, 2, 4, 5, 6, 7])\n/// false\n/// >>> is_sorted(lst: [1, 2, 2, 3, 3, 4])\n/// true\n/// >>> is_sorted(lst: [1, 2, 2, 2, 3, 4])\n/// false\nfunc is_sorted(lst: [Int]) -> Bool {\n var prev: Int? = nil\n for num in lst {\n if let prevNum = prev, num < prevNum {\n return false\n }\n prev = num\n }\n return true"], ["/// You are given two intervals,\n/// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n/// The given intervals are closed which means that the interval (start, end)\n/// includes both start and end.\n/// For each given interval, it is assumed that its start is less or equal its end.\n/// Your task is to determine whether the length of intersection of these two \n/// intervals is a prime number.\n/// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n/// which its length is 1, which not a prime number.\n/// If the length of the intersection is a prime number, return \"YES\",\n/// otherwise, return \"NO\".\n/// If the two intervals don't intersect, return \"NO\".\n/// [input/output] samples:\n/// >>> intersection(interval1: (1, 2), interval2: (2, 3))\n/// \"NO\"\n/// >>> intersection(interval1: (-1, 1), interval2: (0, 4))\n/// \"NO\"\n/// >>> intersection(interval1: (-3, -1), interval2: (-5, 5))\n/// \"YES\"\nfunc intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {\n let start = max(interval1.0, interval2.0)\n let end = min(interval1.1, interval2.1)\n let length = end - start + 1\n if length <= 1 {\n return \"NO\"\n }\n for i in 2..>> prod_signs(arr: [1, 2, 2, -4])\n/// 9\n/// >>> prod_signs(arr: [0, 1])\n/// 0\n/// >>> prod_signs(arr: [] as [Int])\n/// nil\nfunc prod_signs(arr: [Int]) -> Int? {\n if arr.isEmpty {\n return nil\n }\n var sum = 0\n var product = 1\n for num in arr {\n sum += abs(num)\n product *= num.sign\n }\n return sum * product"], ["/// Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n/// each cell of the grid contains a value. Every integer in the range [1, N * N]\n/// inclusive appears exactly once on the cells of the grid.\n/// You have to find the minimum path of length k in the grid. You can start\n/// from any cell, and in each step you can move to any of the neighbor cells,\n/// in other words, you can go to cells which share an edge with you current\n/// cell.\n/// Please note that a path of length k means visiting exactly k cells (not\n/// necessarily distinct).\n/// You CANNOT go off the grid.\n/// A path A (of length k) is considered less than a path B (of length k) if\n/// after making the ordered arrays of the values on the cells that A and B go\n/// through (let's call them lst_A and lst_B), lst_A is lexicographically less\n/// than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n/// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n/// lst_A[j] = lst_B[j].\n/// It is guaranteed that the answer is unique.\n/// Return an ordered array of the values on the cells that the minimum path go through.\n/// Examples: \n/// >>> minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3)\n/// [1, 2, 1]\n/// >>> minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1)\n/// [1]\nfunc minPath(grid: [[Int]], k: Int) -> [Int] {\n let n = grid.count\n var dp = Array(repeating: Array(repeating: [Int](repeating: Int.max, count: k + 1), count: n), count: n)\n dp[0][0][1] = grid[0][0]\n for i in 0.. 0 {\n dp[i][j][l] = min(dp[i][j][l], dp[i-1][j][l-1] + grid[i][j])\n }\n if j > 0 {\n dp[i][j][l] = min(dp[i][j][l], dp[i][j-1][l-1] + grid[i][j])\n }\n }\n }\n }\n var path = [Int]()\n var i = n - 1, j = n - 1, l = k\n while i > 0 || j > 0 {\n if i > 0 && dp[i][j][l] == dp[i-1][j][l-1] + grid[i][j] {\n path.append(grid[i][j])\n i -= 1\n l -= 1\n } else {\n path.append(grid[i][j])\n j -= 1\n l -= 1\n }\n }\n path.append(grid[0][0])\n return path.reversed()"], ["/// Out of array of strings, return the longest one. Return the first one in case of multiple\n/// strings of the same length. Return nil in case the input array is empty.\n/// >>> longest(strings: [] as [String])\n/// nil\n/// >>> longest(strings: [\"a\", \"b\", \"c\"])\n/// \"a\"\n/// >>> longest(strings: [\"a\", \"bb\", \"ccc\"])\n/// \"ccc\"\nfunc longest(strings: [String]) -> String? {\n guard !strings.isEmpty else { return nil }\n return strings.max(by: { $0.count < $1.count })"], ["/// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n/// the last couple centuries. However, what people don't know is Tribonacci sequence.\n/// Tribonacci sequence is defined by the recurrence:\n/// tri(1) = 3\n/// tri(n) = 1 + n / 2, if n is even.\n/// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n/// For example:\n/// tri(2) = 1 + (2 / 2) = 2\n/// tri(4) = 3\n/// tri(3) = tri(2) + tri(1) + tri(4)\n/// = 2 + 3 + 3 = 8 \n/// You are given a non-negative integer number n, you have to a return an array of the \n/// first n + 1 numbers of the Tribonacci sequence.\n/// Examples:\n/// >>> tri(n: 3)\n/// [1, 3, 2, 8]\nfunc tri(n: Int) -> [Int] {\n var result = [Int]()\n for i in 0...n {\n if i == 0 {\n result.append(1)\n } else if i == 1 {\n result.append(3)\n } else if i % 2 == 0 {\n result.append(1 + i / 2)\n } else {\n result.append(result[i-1] + result[i-2] + result[i+1])\n }\n }\n return result"], ["/// Given a positive integer n, return the product of the odd digits.\n/// Return 0 if all digits are even.\n/// For example:\n/// >>> digits(n: 1)\n/// 1\n/// >>> digits(n: 4)\n/// 0\n/// >>> digits(n: 235)\n/// 15\nfunc digits(n: Int) -> Int {\n var product = 1\n var num = n\n while num > 0 {\n let digit = num % 10\n if digit % 2 != 0 {\n product *= digit\n }\n num /= 10\n }\n return product"], ["/// Create a function that takes a string as input which contains only square brackets.\n/// The function should return true if and only if there is a valid subsequence of brackets \n/// where at least one bracket in the subsequence is nested.\n/// >>> is_nested(string: \"[[]]\")\n/// true\n/// >>> is_nested(string: \"[]]]]]]][[[[[]\")\n/// false\n/// >>> is_nested(string: \"[][]\")\n/// false\n/// >>> is_nested(string: \"[]\")\n/// false\n/// >>> is_nested(string: \"[[][]]\")\n/// true\n/// >>> is_nested(string: \"[[]][[\")\n/// true\nfunc is_nested(string: String) -> Bool {\n var stack = [Character]()\n for char in string {\n if char == \"[\" {\n stack.append(char)\n } else if char == \"]\" {\n if stack.count > 0 {\n stack.removeLast()\n } else {\n return false\n }\n }\n }\n return stack.count > 0"], ["/// You are given an array of numbers.\n/// You need to return the sum of squared numbers in the given array,\n/// round each element in the array to the upper int(Ceiling) first.\n/// Examples:\n/// >>> sum_squares(lst: [1.0, 2.0, 3.0])\n/// 14\n/// >>> sum_squares(lst: [1.0, 4.0, 9.0])\n/// 98\n/// >>> sum_squares(lst: [1.0, 3.0, 5.0, 7.0])\n/// 84\n/// >>> sum_squares(lst: [1.4, 4.2, 0.0])\n/// 29\n/// >>> sum_squares(lst: [-2.4, 1.0, 1.0])\n/// 6\nfunc sum_squares(lst: [Double]) -> Int {\n var sum = 0\n for num in lst {\n let ceilNum = Int(ceil(num))\n sum += ceilNum * ceilNum\n }\n return sum"], ["/// Create a function that returns true if the last character\n/// of a given string is an alphabetical character and is not\n/// a part of a word, and false otherwise.\n/// Note: \"word\" is a group of characters separated by space.\n/// Examples:\n/// >>> check_if_last_char_is_a_letter(txt: \"apple pie\")\n/// false\n/// >>> check_if_last_char_is_a_letter(txt: \"apple pi e\")\n/// true\n/// >>> check_if_last_char_is_a_letter(txt: \"apple pi e \")\n/// false\n/// >>> check_if_last_char_is_a_letter(txt: \"\")\n/// false\nfunc check_if_last_char_is_a_letter(txt: String) -> Bool {\n if txt.isEmpty {\n return false\n }\n let lastChar = txt.last\n if lastChar == \" \" {\n return false\n }\n return lastChar.isLetter"], ["/// Create a function which returns the largest index of an element which\n/// is not greater than or equal to the element immediately preceding it. If\n/// no such element exists then return -1. The given array will not contain\n/// duplicate values.\n/// Examples:\n/// >>> can_arrange(arr: [1, 2, 4, 3, 5])\n/// 3\n/// >>> can_arrange(arr: [1, 2, 3])\n/// -1\nfunc can_arrange(arr: [Int]) -> Int {\n for i in 1..>> largest_smallest_integers(lst: [2, 4, 1, 3, 5, 7])\n/// (nil, 1)\n/// >>> largest_smallest_integers(lst: [] as [Int])\n/// (nil, nil)\n/// >>> largest_smallest_integers(lst: [0])\n/// (nil, nil)\nfunc largest_smallest_integers(lst: [Int]) -> (Int?, Int?) {\n var largestNegative: Int? = nil\n var smallestPositive: Int? = nil\n \n for num in lst {\n if num < 0 {\n if largestNegative == nil || num > largestNegative! {\n largestNegative = num\n }\n } else if num > 0 {\n if smallestPositive == nil || num < smallestPositive! {\n smallestPositive = num\n }\n }\n }\n \n return (largestNegative, smallestPositive)"], ["enum Value: Equatable, Hashable {\n case intValue(Int)\n case doubleValue(Double)\n case stringValue(String)\n}\n\n \n/// Create a function that takes integers, floats, or strings representing\n/// real numbers, and returns the larger variable in its given variable type.\n/// Return nil if the values are equal.\n/// Note: If a real number is represented as a string, the floating point might be . or ,\n/// >>> compare_one(a: .intValue(1), b: .doubleValue(2.5))\n/// .doubleValue(2.5)\n/// >>> compare_one(a: .intValue(1), b: .stringValue(\"2,3\"))\n/// .stringValue(\"2,3\")\n/// >>> compare_one(a: .stringValue(\"5,1\"), b: .stringValue(\"6\"))\n/// .stringValue(\"6\")\n/// >>> compare_one(a: .stringValue(\"1\"), b: .intValue(1))\n/// nil\nfunc compare_one(a: Value, b: Value) -> Value? {\n switch (a, b) {\n case (.intValue(let aInt), .intValue(let bInt)):\n return aInt > bInt ? a : bInt > aInt ? b : nil\n case (.doubleValue(let aDouble), .doubleValue(let bDouble)):\n return aDouble > bDouble ? a : bDouble > aDouble ? b : nil\n case (.stringValue(let aString), .stringValue(let bString)):\n let aDouble = Double(aString.replacingOccurrences(of: \",\", with: \".\")) ?? 0\n let bDouble = Double(bString.replacingOccurrences(of: \",\", with: \".\")) ?? 0\n return aDouble > bDouble ? a : bDouble > aDouble ? b : nil\n default:\n return nil\n }"], ["/// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n/// Example\n/// >>> is_equal_to_sum_even(n: 4)\n/// false\n/// >>> is_equal_to_sum_even(n: 6)\n/// false\n/// >>> is_equal_to_sum_even(n: 8)\n/// true\nfunc is_equal_to_sum_even(n: Int) -> Bool {\n if n % 2 != 0 {\n return false\n }\n let half = n / 2\n for i in 2...half {\n for j in i+1...half {\n for k in j+1...half {\n for l in k+1...half {\n if i + j + k + l == half {\n return true\n }\n }\n }\n }\n }\n return false"], ["/// The Brazilian factorial is defined as:\n/// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n/// where n > 0\n/// For example:\n/// >>> special_factorial(n: 4)\n/// 288\n/// The function will receive an integer as input and should return the special\n/// factorial of this integer.\nfunc special_factorial(n: Int) -> Int {\n var result = 1\n for i in stride(from: n, through: 1, by: -1) {\n result *= i\n }\n return result"], ["/// Return a greatest common divisor of two integers a and b\n/// >>> greatest_common_divisor(a: 3, b: 5)\n/// 1\n/// >>> greatest_common_divisor(a: 25, b: 15)\n/// 5\nfunc greatest_common_divisor(a: Int, b: Int) -> Int {\n var x = a\n var y = b\n while y != 0 {\n let temp = y\n y = x % y\n x = temp\n }\n return x"], ["/// Given a string text, replace all spaces in it with underscores, \n/// and if a string has more than 2 consecutive spaces, \n/// then replace all consecutive spaces with - \n/// >>> fix_spaces(text: \" Example\")\n/// \"Example\"\n/// >>> fix_spaces(text: \" Example 1\")\n/// \"Example_1\"\n/// >>> fix_spaces(text: \" Example 2\")\n/// \"_Example_2\"\n/// >>> fix_spaces(text: \" Example 3\")\n/// \"_Example-3\"\nfunc fix_spaces(text: String) -> String {\n var result = text.trimmingCharacters(in: .whitespacesAndNewlines)\n result = result.replacingOccurrences(of: \" \", with: \"-\", options: .literal, range: nil)\n result = result.replacingOccurrences(of: \" \", with: \"_\", options: .literal, range: nil)\n return result"], ["/// Create a function which takes a string representing a file's name, and returns\n/// 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n/// A file's name is considered to be valid if and only if all the following conditions \n/// are met:\n/// - There should not be more than three digits ('0'-'9') in the file's name.\n/// - The file's name contains exactly one dot '.'\n/// - The substring before the dot should not be empty, and it starts with a letter from \n/// the latin alphapet ('a'-'z' and 'A'-'Z').\n/// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n/// Examples:\n/// >>> file_name_check(file_name: \"example.txt\")\n/// \"Yes\"\n/// >>> file_name_check(file_name: \"1example.dll\")\n/// \"No\"\nfunc file_name_check(file_name: String) -> String {\n let valid_extensions = [\"txt\", \"exe\", \"dll\"]\n let parts = file_name.components(separatedBy: \".\")\n if parts.count != 2 {\n return \"No\"\n }\n let name = parts[0]\n let extension = parts[1]\n if name.count > 3 || name.isEmpty || !name.first?.isLetter() ?? false {\n return \"No\"\n }\n if !valid_extensions.contains(extension) {\n return \"No\"\n }\n return \"Yes\""], ["/// You are given a string representing a sentence,\n/// the sentence contains some words separated by a space,\n/// and you have to return a string that contains the words from the original sentence,\n/// whose lengths are prime numbers,\n/// the order of the words in the new string should be the same as the original one.\n/// Example 1:\n/// >>> words_in_sentence(sentence: \"This is a test\")\n/// \"is\"\n/// Example 2:\n/// >>> words_in_sentence(sentence: \"lets go for swimming\")\n/// \"go for\"\n/// Constraints:\n/// * 1 <= len(sentence) <= 100\n/// * sentence contains only letters\nfunc words_in_sentence(sentence: String) -> String {\n let words = sentence.split(separator: \" \")\n var result = \"\"\n for word in words {\n if isPrime(word.count) {\n result += word + \" \"\n }\n }\n return result.trimmingCharacters(in: .whitespaces)"], ["/// Your task is to implement a function that will simplify the expression\n/// x * n. The function returns true if x * n evaluates to a whole number and false\n/// otherwise. Both x and n, are string representation of a fraction, and have the following format,\n/// / where both numerator and denominator are positive whole numbers.\n/// You can assume that x, and n are valid fractions, and do not have zero as denominator.\n/// >>> simplify(x: \"1/5\", n: \"5/1\")\n/// true\n/// >>> simplify(x: \"1/6\", n: \"2/1\")\n/// false\n/// >>> simplify(x: \"7/10\", n: \"10/2\")\n/// false\nfunc simplify(x: String, n: String) -> Bool {\n let xComponents = x.components(separatedBy: \"/\")\n let nComponents = n.components(separatedBy: \"/\")\n let xNumerator = Int(xComponents[0]) ?? 0\n let xDenominator = Int(xComponents[1]) ?? 1\n let nNumerator = Int(nComponents[0]) ?? 0\n let nDenominator = Int(nComponents[1]) ?? 1\n let result = (xNumerator * nDenominator) % (xDenominator * nNumerator)\n return result == 0"], ["/// Write a function which sorts the given array of integers\n/// in ascending order according to the sum of their digits.\n/// Note: if there are several items with similar sum of their digits,\n/// order them based on their index in original array.\n/// For example:\n/// >>> order_by_points(nums: [1, 11, -1, -11, -12])\n/// [-1, -11, 1, -12, 11]\n/// >>> order_by_points(nums: [] as [Int])\n/// [] as [Int]\nfunc order_by_points(nums: [Int]) -> [Int] {\n var sortedNums = nums.sorted { (a, b) -> Bool in\n let sumA = String(a).reduce(0) { $0 + Int(String($1))?.description.reduce(0) { $0 + Int(String($1))? } ?? 0 }\n let sumB = String(b).reduce(0) { $0 + Int(String($1))?.description.reduce(0) { $0 + Int(String($1))? } ?? 0 }\n if sumA == sumB {\n return nums.firstIndex(of: a)! < nums.firstIndex(of: b)!\n } else {\n return sumA < sumB\n }\n }\n return sortedNums"], ["/// Write a function that takes an array of numbers as input and returns \n/// the number of elements in the array that are greater than 10 and both \n/// first and last digits of a number are odd (1, 3, 5, 7, 9).\n/// For example:\n/// >>> specialFilter(nums: [15, -73, 14, -15])\n/// 1\n/// >>> specialFilter(nums: [33, -2, -3, 45, 21, 109])\n/// 2\nfunc specialFilter(nums: [Int]) -> Int {\n var count = 0\n for num in nums {\n if num > 10 && abs(num) % 2 == 1 && abs(num) % 10 % 2 == 1 {\n count += 1\n }\n }\n return count"], ["/// You are given a positive integer n. You have to create an integer array a of length n.\n/// For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n/// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n/// and a[i] + a[j] + a[k] is a multiple of 3.\n/// Example :\n/// >>> get_max_triples(n: 5)\n/// 1\n/// Explanation: \n/// a = [1, 3, 7, 13, 21]\n/// The only valid triple is (1, 7, 13).\nfunc get_max_triples(n: Int) -> Int {\n var count = 0\n for i in 1...n {\n for j in i+1...n {\n for k in j+1...n {\n let sum = i*i - i + 1 + j*j - j + 1 + k*k - k + 1\n if sum % 3 == 0 {\n count += 1\n }\n }\n }\n }\n return count"], ["/// Write a function that accepts an array of strings as a parameter,\n/// deletes the strings that have odd lengths from it,\n/// and returns the resulted array with a sorted order,\n/// The array is always an array of strings and never an array of numbers,\n/// and it may contain duplicates.\n/// The order of the array should be ascending by length of each word, and you\n/// should return the array sorted by that rule.\n/// If two words have the same length, sort the array alphabetically.\n/// The function should return an array of strings in sorted order.\n/// You may assume that all words will have the same length.\n/// For example:\n/// >>> sorted_list_sum(lst: [\"aa\", \"a\", \"aaa\"])\n/// [\"aa\"]\n/// >>> sorted_list_sum(lst: [\"ab\", \"a\", \"aaa\", \"cd\"])\n/// [\"ab\", \"cd\"]\nfunc sorted_list_sum(lst: [String]) -> [String] {\n let evenLengthStrings = lst.filter { $0.count % 2 == 0 }\n let sortedStrings = evenLengthStrings.sorted { $0.count == $1.count ? $0 < $1 : $0.count < $1.count }\n return sortedStrings"], ["/// Return array of all prefixes from shortest to longest of the input string\n/// >>> all_prefixes(string: \"abc\")\n/// [\"a\", \"ab\", \"abc\"]\nfunc all_prefixes(string: String) -> [String] {\n var prefixes = [String]()\n for i in 1...string.count {\n prefixes.append(String(string[0..>> x_or_y(n: 7, x: 34, y: 12)\n/// 34\n/// >>> x_or_y(n: 15, x: 8, y: 5)\n/// 5\nfunc x_or_y(n: Int, x: Int, y: Int) -> Int {\n if isPrime(n) {\n return x\n } else {\n return y\n }"], ["/// Given an array of numbers, return the sum of squares of the numbers\n/// in the array that are odd. Ignore numbers that are negative or not integers.\n/// >>> double_the_difference(lst: [1, 3, 2, 0])\n/// 10\n/// >>> double_the_difference(lst: [-1, -2, 0])\n/// 0\n/// >>> double_the_difference(lst: [9, -2])\n/// 81\n/// >>> double_the_difference(lst: [0])\n/// 0\n/// If the input array is empty, return 0.\nfunc double_the_difference(lst: [Double]) -> Int {\n var sum = 0\n for num in lst {\n if num.truncatingRemainder(dividingBy: 2) != 0 && num.isInteger {\n sum += Int(pow(num, 2))\n }\n }\n return sum"], ["/// I think we all remember that feeling when the result of some long-awaited\n/// event is finally known. The feelings and thoughts you have at that moment are\n/// definitely worth noting down and comparing.\n/// Your task is to determine if a person correctly guessed the results of a number of matches.\n/// You are given two arrays of scores and guesses of equal length, where each index shows a match. \n/// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,\n/// the value is 0, and if not, the value is the absolute difference between the guess and the score.\n/// example:\n/// >>> compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2])\n/// [0, 0, 0, 0, 3, 3]\n/// >>> compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2])\n/// [4, 4, 1, 0, 0, 6]\nfunc compare(game: [Int], guess: [Int]) -> [Int] {\n var result = [Int]()\n for i in 0..>> Strongest_Extension(class_name: \"my_class\", extensions: [\"AA\", \"Be\", \"CC\"])\n/// \"my_class.AA\"\nfunc Strongest_Extension(class_name: String, extensions: [String]) -> String {\n var strongest_extension = \"\"\n var strongest_strength = Double.infinity\n for extension in extensions {\n var cap_count = 0\n var sm_count = 0\n for char in extension {\n if char.isUppercase {\n cap_count += 1\n } else if char.isLowercase {\n sm_count += 1\n }\n }\n let strength = Double(cap_count) - Double(sm_count)\n if strength < strongest_strength {\n strongest_strength = strength\n strongest_extension = extension\n }\n }\n return \"\\(class_name).\\(strongest_extension)\""], ["/// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word\n/// >>> cycpattern_check(a: \"abcd\", b: \"abd\")\n/// false\n/// >>> cycpattern_check(a: \"hello\", b: \"ell\")\n/// true\n/// >>> cycpattern_check(a: \"whassup\", b: \"psus\")\n/// false\n/// >>> cycpattern_check(a: \"abab\", b: \"baa\")\n/// true\n/// >>> cycpattern_check(a: \"efef\", b: \"eeff\")\n/// false\n/// >>> cycpattern_check(a: \"himenss\", b: \"simen\")\n/// true\nfunc cycpattern_check(a: String, b: String) -> Bool {\n let rotations = (0..>> even_odd_count(num: -12)\n/// (1, 1)\n/// >>> even_odd_count(num: 123)\n/// (1, 2)\nfunc even_odd_count(num: Int) -> (Int, Int) {\n var evenCount = 0\n var oddCount = 0\n var n = abs(num)\n while n > 0 {\n let digit = n % 10\n if digit % 2 == 0 {\n evenCount += 1\n } else {\n oddCount += 1\n }\n n /= 10\n }\n return (evenCount, oddCount)"], ["/// Given a positive integer, obtain its roman numeral equivalent as a string,\n/// and return it in lowercase.\n/// Restrictions: 1 <= num <= 1000\n/// Examples:\n/// >>> int_to_mini_roman(number: 19)\n/// \"xix\"\n/// >>> int_to_mini_roman(number: 152)\n/// \"clii\"\n/// >>> int_to_mini_roman(number: 426)\n/// \"cdxxvi\"\nfunc int_to_mini_roman(number: Int) -> String {\n let romanNumerals = [\n (1000, \"m\"),\n (900, \"cm\"),\n (500, \"d\"),\n (400, \"cd\"),\n (100, \"c\"),\n (90, \"xc\"),\n (50, \"l\"),\n (40, \"xl\"),\n (10, \"x\"),\n (9, \"ix\"),\n (5, \"v\"),\n (4, \"iv\"),\n (1, \"i\")\n ]\n var result = \"\"\n var num = number\n for (value, symbol) in romanNumerals {\n while num >= value {\n result += symbol\n num -= value\n }\n }\n return result.lowercased()"], ["/// Given the lengths of the three sides of a triangle. Return true if the three\n/// sides form a right-angled triangle, false otherwise.\n/// A right-angled triangle is a triangle in which one angle is right angle or \n/// 90 degree.\n/// Example:\n/// >>> right_angle_triangle(a: 3, b: 4, c: 5)\n/// true\n/// >>> right_angle_triangle(a: 1, b: 2, c: 3)\n/// false\nfunc right_angle_triangle(a: Int, b: Int, c: Int) -> Bool {\n let sides = [a, b, c].sorted()\n return sides[0]^2 + sides[1]^2 == sides[2]^2"], ["/// Write a function that accepts an array of strings.\n/// The array contains different words. Return the word with maximum number\n/// of unique characters. If multiple strings have maximum number of unique\n/// characters, return the one which comes first in lexicographical order.\n/// >>> find_max(words: [\"name\", \"of\", \"string\"])\n/// \"string\"\n/// >>> find_max(words: [\"name\", \"enam\", \"game\"])\n/// \"enam\"\n/// >>> find_max(words: [\"aaaaaaa\", \"bb\", \"cc\"])\n/// \"aaaaaaa\"\nfunc find_max(words: [String]) -> String {\n var maxWord = \"\"\n var maxUniqueChars = 0\n for word in words {\n let uniqueChars = Set(word)\n if uniqueChars.count > maxUniqueChars || (uniqueChars.count == maxUniqueChars && word < maxWord) {\n maxWord = word\n maxUniqueChars = uniqueChars.count\n }\n }\n return maxWord"], ["/// You're a hungry rabbit, and you already have eaten a certain number of carrots,\n/// but now you need to eat more carrots to complete the day's meals.\n/// you should return an array of [ total number of eaten carrots after your meals,\n/// the number of carrots left after your meals ]\n/// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n/// Example:\n/// >>> eat(number: 5, need: 6, remaining: 10)\n/// [11, 4]\n/// >>> eat(number: 4, need: 8, remaining: 9)\n/// [12, 1]\n/// >>> eat(number: 1, need: 10, remaining: 10)\n/// [11, 0]\n/// >>> eat(number: 2, need: 11, remaining: 5)\n/// [7, 0]\n/// Variables:\n/// @number : integer\n/// the number of carrots that you have eaten.\n/// @need : integer\n/// the number of carrots that you need to eat.\n/// @remaining : integer\n/// the number of remaining carrots thet exist in stock\n/// Constrain:\n/// * 0 <= number <= 1000\n/// * 0 <= need <= 1000\n/// * 0 <= remaining <= 1000\n/// Have fun :)\nfunc eat(number: Int, need: Int, remaining: Int) -> [Int] {\n let totalEaten = number + need\n let remainingCarrots = remaining - need\n if remainingCarrots < 0 {\n return [totalEaten, 0]\n } else {\n return [totalEaten, remainingCarrots]\n }"], ["/// Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n/// >>> string_sequence(n: 0)\n/// \"0\"\n/// >>> string_sequence(n: 5)\n/// \"0 1 2 3 4 5\"\nfunc string_sequence(n: Int) -> String {\n return (0...n).map { String($0) }.joined(separator: \" \")"], ["/// Given two arrays operator, and operand. The first array has basic algebra operations, and \n/// the second array is an array of integers. Use the two given arrays to build the algebric \n/// expression and return the evaluation of this expression.\n/// The basic algebra operations:\n/// Addition ( + ) \n/// Subtraction ( - ) \n/// Multiplication ( * ) \n/// Floor division ( // ) \n/// Exponentiation ( ** ) \n/// Example:\n/// operator['+', '*', '-']\n/// array = [2, 3, 4, 5]\n/// result = 2 + 3 * 4 - 5\n/// => result = 9\n/// Note:\n/// The length of operator array is equal to the length of operand array minus one.\n/// Operand is an array of of non-negative integers.\n/// Operator array has at least one operator, and operand array has at least two operands.\nfunc do_algebra(operator: [String], operand: [Int]) -> Int {\n var result = operand[0]\n for i in 0..>> solve(s: \"1234\")\n/// \"4321\"\n/// >>> solve(s: \"ab\")\n/// \"AB\"\n/// >>> solve(s: \"#a@C\")\n/// \"#A@c\"\nfunc solve(s: String) -> String {\n var result = \"\"\n var hasLetters = false\n for char in s {\n if char.isLetter {\n hasLetters = true\n if char.isUppercase {\n result.append(char.lowercased())\n } else {\n result.append(char.uppercased())\n }\n } else {\n result.append(char)\n }\n }\n if !hasLetters {\n result = String(result.reversed())\n }\n return result"], ["/// Given a string 'text', return its md5 hash equivalent string.\n/// If 'text' is an empty string, return nil.\n/// >>> string_to_md5(text: \"Hello world\")\n/// \"3e25960a79dbc69b674cd4ec67a72c62\"\nfunc string_to_md5(text: String) -> String? {\n guard !text.isEmpty else { return nil }\n let data = text.data(using: .utf8)!\n let hash = data.md5\n return hash.map { String(format: \"%02x\", $0) }.joined()"], ["/// Given two positive integers a and b, return the even digits between a\n/// and b, in ascending order.\n/// For example:\n/// >>> generate_integers(a: 2, b: 8)\n/// [2, 4, 6, 8]\n/// >>> generate_integers(a: 8, b: 2)\n/// [2, 4, 6, 8]\n/// >>> generate_integers(a: 10, b: 14)\n/// [] as [Int]\nfunc generate_integers(a: Int, b: Int) -> [Int] {\n let start = min(a, b)\n let end = max(a, b)\n var result = [Int]()\n for i in start...end {\n if i % 2 == 0 {\n result.append(i)\n }\n }\n return result"], ["/// Given a string, find out how many distinct characters (regardless of case) does it consist of\n/// >>> count_distinct_characters(string: \"xyzXYZ\")\n/// 3\n/// >>> count_distinct_characters(string: \"Jerry\")\n/// 4\nfunc count_distinct_characters(string: String) -> Int {\n return Set(string.lowercased()).count"], ["/// Input to this function is a string representing musical notes in a special ASCII format.\n/// Your task is to parse this string and return array of integers corresponding to how many beats does each\n/// not last.\n/// Here is a legend:\n/// 'o' - whole note, lasts four beats\n/// 'o|' - half note, lasts two beats\n/// '.|' - quater note, lasts one beat\n/// >>> parse_music(music_string: \"o o| .| o| o| .| .| .| .| o o\")\n/// [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\nfunc parse_music(music_string: String) -> [Int] {\n var beats = [Int]()\n for note in music_string.split(separator: \" \") {\n switch note {\n case \"o\":\n beats.append(4)\n case \"o|\":\n beats.append(2)\n case \".|\":\n beats.append(1)\n default:\n break\n }\n }\n return beats"], ["/// Find how many times a given substring can be found in the original string. Count overlaping cases.\n/// >>> how_many_times(string: \"\", substring: \"a\")\n/// 0\n/// >>> how_many_times(string: \"aaa\", substring: \"a\")\n/// 3\n/// >>> how_many_times(string: \"aaaa\", substring: \"aa\")\n/// 3\nfunc how_many_times(string: String, substring: String) -> Int {\n var count = 0\n var index = string.startIndex\n while index < string.endIndex {\n if let range = string[index...].range(of: substring) {\n count += 1\n index = range.upperBound\n } else {\n break\n }\n }\n return count"], ["/// Input is a space-delimited string of numberals from 'zero' to 'nine'.\n/// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n/// Return the string with numbers sorted from smallest to largest\n/// >>> sort_numbers(numbers: \"three one five\")\n/// \"one three five\"\nfunc sort_numbers(numbers: String) -> String {\n let numberWords = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n let numberArray = numbers.split(separator: \" \").map { numberWords.firstIndex(of: $0)! }\n let sortedArray = numberArray.sorted()\n let sortedWords = sortedArray.map { numberWords[$0] }\n return sortedWords.joined(separator: \" \")"], ["/// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n/// separate those group into separate strings and return the array of those.\n/// Separate groups are balanced (each open brace is properly closed) and not nested within each other\n/// Ignore any spaces in the input string.\n/// >>> separate_paren_groups(paren_string: \"( ) (( )) (( )( ))\")\n/// [\"()\", \"(())\", \"(()())\"]\nfunc separate_paren_groups(paren_string: String) -> [String] {\n var groups = [String]()\n var current_group = \"\"\n var open_count = 0\n \n for char in paren_string {\n if char == \"(\" {\n open_count += 1\n } else if char == \")\" {\n open_count -= 1\n }\n \n if open_count == 0 && char == \")\" {\n groups.append(current_group)\n current_group = \"\"\n } else if char != \" \" {\n current_group.append(char)\n }\n }\n \n return groups"], ["/// From a supplied array of numbers (of length at least two) select and return two that are the closest to each\n/// other and return them in order (smaller number, larger number).\n/// >>> find_closest_elements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n/// (2.0, 2.2)\n/// >>> find_closest_elements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n/// (2.0, 2.0)\nfunc find_closest_elements(numbers: [Double]) -> (Double, Double) {\n var closestPair = (numbers[0], numbers[1])\n var minDifference = abs(numbers[0] - numbers[1])\n \n for i in 0..>> rescale_to_unit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0])\n/// [0.0, 0.25, 0.5, 0.75, 1.0]\nfunc rescale_to_unit(numbers: [Double]) -> [Double] {\n let min = numbers.min()!\n let max = numbers.max()!\n let range = max - min\n return numbers.map { ($0 - min) / range }"], ["/// Filter given array of any swiftthon values only for integers\n/// >>> filter_integers(values: [\"a\", 3.14, 5])\n/// [5]\n/// >>> filter_integers(values: [1, 2, 3, \"abc\", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]])\n/// [1, 2, 3]\nfunc filter_integers(values: [AnyHashable]) -> [Int] {\n return values.flatMap { $0 as? Int }"], ["/// Return length of given string\n/// >>> strlen(string: \"\")\n/// 0\n/// >>> strlen(string: \"abc\")\n/// 3\nfunc strlen(string: String) -> Int {\n return string.count"], ["/// For a given number n, find the largest number that divides n evenly, smaller than n\n/// >>> largest_divisor(n: 15)\n/// 5\nfunc largest_divisor(n: Int) -> Int {\n var divisor = n - 1\n while divisor > 0 {\n if n % divisor == 0 {\n return divisor\n }\n divisor -= 1\n }\n return 1"], ["/// Return array of prime factors of given integer in the order from smallest to largest.\n/// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.\n/// Input number should be equal to the product of all factors\n/// >>> factorize(n: 8)\n/// [2, 2, 2]\n/// >>> factorize(n: 25)\n/// [5, 5]\n/// >>> factorize(n: 70)\n/// [2, 5, 7]\nfunc factorize(n: Int) -> [Int] {\n var factors = [Int]()\n var divisor = 2\n var number = n\n \n while divisor <= number {\n if number % divisor == 0 {\n factors.append(divisor)\n number /= divisor\n } else {\n divisor += 1\n }\n }\n \n return factors"], ["/// From an array of integers, remove all elements that occur more than once.\n/// Keep order of elements left the same as in the input.\n/// >>> remove_duplicates(numbers: [1, 2, 3, 2, 4])\n/// [1, 3, 4]\nfunc remove_duplicates(numbers: [Int]) -> [Int] {\n var result: [Int] = []\n for num in numbers {\n if !result.contains(num) {\n result.append(num)\n }\n }\n return result"], ["/// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n/// >>> flip_case(string: \"Hello\")\n/// \"hELLO\"\nfunc flip_case(string: String) -> String {\n var flippedString = \"\"\n for char in string {\n if char.isUppercase {\n flippedString += String(char.lowercased())\n } else if char.isLowercase {\n flippedString += String(char.uppercased())\n } else {\n flippedString += String(char)\n }\n }\n return flippedString"], ["/// Concatenate array of strings into a single string\n/// >>> concatenate(strings: [] as [String])\n/// \"\"\n/// >>> concatenate(strings: [\"a\", \"b\", \"c\"])\n/// \"abc\"\nfunc concatenate(strings: [String]) -> String {\n return strings.joined()"], ["/// Filter an input array of strings only for ones that start with a given prefix.\n/// >>> filter_by_prefix(strings: [] as [String], prefix: \"a\")\n/// [] as [String]\n/// >>> filter_by_prefix(strings: [\"abc\", \"bcd\", \"cde\", \"array\"], prefix: \"a\")\n/// [\"abc\", \"array\"]\nfunc filter_by_prefix(strings: [String], prefix: String) -> [String] {\n return strings.filter { $0.hasPrefix(prefix) }"], ["/// Given a positive floating point number, it can be decomposed into\n/// and integer part (largest integer smaller than given number) and decimals\n/// (leftover part always smaller than 1).\n/// Return the decimal part of the number.\n/// >>> truncate_number(number: 3.5)\n/// 0.5\nfunc truncate_number(number: Double) -> Double {\n return number - Double(Int(number))"], ["/// Return only positive numbers in the array.\n/// >>> get_positive(l: [-1, 2, -4, 5, 6])\n/// [2, 5, 6]\n/// >>> get_positive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n/// [5, 3, 2, 3, 9, 123, 1]\nfunc get_positive(l: [Int]) -> [Int] {\n return l.filter { $0 > 0 }"], ["/// Return true if a given number is prime, and false otherwise.\n/// >>> is_prime(n: 6)\n/// false\n/// >>> is_prime(n: 101)\n/// true\n/// >>> is_prime(n: 11)\n/// true\n/// >>> is_prime(n: 13441)\n/// true\n/// >>> is_prime(n: 61)\n/// true\n/// >>> is_prime(n: 4)\n/// false\n/// >>> is_prime(n: 1)\n/// false\nfunc is_prime(n: Int) -> Bool {\n if n <= 1 {\n return false\n }\n for i in 2..>> sort_third(l: [1, 2, 3])\n/// [1, 2, 3]\n/// >>> sort_third(l: [5, 6, 3, 4, 8, 9, 2])\n/// [2, 6, 3, 4, 8, 9, 5]\nfunc sort_third(l: [Int]) -> [Int] {\n var l_prime = l\n var divisible_by_three = [Int]()\n for (index, value) in l.enumerated() {\n if index % 3 == 0 {\n divisible_by_three.append(value)\n }\n }\n divisible_by_three.sort()\n var index = 0\n for (index, value) in l.enumerated() {\n if index % 3 == 0 {\n l_prime[index] = divisible_by_three[index/3]\n }\n }\n return l_prime"], ["/// Return sorted unique elements in an array\n/// >>> unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123])\n/// [0, 2, 3, 5, 9, 123]\nfunc unique(l: [Int]) -> [Int] {\n return Array(Set(l)).sorted()"], ["/// Return maximum element in the array.\n/// >>> max_element(l: [1, 2, 3])\n/// 3\n/// >>> max_element(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n/// 123\nfunc max_element(l: [Int]) -> Int {\n return l.max() ?? 0"], ["/// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n/// >>> fizz_buzz(n: 50)\n/// 0\n/// >>> fizz_buzz(n: 78)\n/// 2\n/// >>> fizz_buzz(n: 79)\n/// 3\nfunc fizz_buzz(n: Int) -> Int {\n var count = 0\n for i in 1...n {\n if (i % 11 == 0 || i % 13 == 0) && String(i).contains(\"7\") {\n count += 1\n }\n }\n return count"], ["/// This function takes an array l and returns an array l' such that\n/// l' is identical to l in the odd indicies, while its values at the even indicies are equal\n/// to the values of the even indicies of l, but sorted.\n/// >>> sort_even(l: [1, 2, 3])\n/// [1, 2, 3]\n/// >>> sort_even(l: [5, 6, 3, 4])\n/// [3, 6, 5, 4]\nfunc sort_even(l: [Int]) -> [Int] {\n var l_prime = l\n var even_values = [Int]()\n for i in stride(from: 0, to: l.count, by: 2) {\n even_values.append(l[i])\n }\n even_values.sort()\n for i in stride(from: 0, to: l.count, by: 2) {\n l_prime[i] = even_values.removeFirst()\n }\n return l_prime"], ["/// prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n/// >>> prime_fib(n: 1)\n/// 2\n/// >>> prime_fib(n: 2)\n/// 3\n/// >>> prime_fib(n: 3)\n/// 5\n/// >>> prime_fib(n: 4)\n/// 13\n/// >>> prime_fib(n: 5)\n/// 89\nfunc prime_fib(n: Int) -> Int {\n var count = 0\n var fib1 = 0\n var fib2 = 1\n while count < n {\n let nextFib = fib1 + fib2\n fib1 = fib2\n fib2 = nextFib\n if isPrime(nextFib) {\n count += 1\n }\n }\n return fib1"], ["/// You're given an array of deposit and withdrawal operations on a bank account that starts with\n/// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n/// at that point function should return true. Otherwise it should return false.\n/// >>> below_zero(operations: [1, 2, 3])\n/// false\n/// >>> below_zero(operations: [1, 2, -4, 5])\n/// true\nfunc below_zero(operations: [Int]) -> Bool {\n var balance = 0\n for operation in operations {\n balance += operation\n if balance < 0 {\n return true\n }\n }\n return false"], ["/// triples_sum_to_zero takes an array of integers as an input.\n/// it returns true if there are three distinct elements in the array that\n/// sum to zero, and false otherwise.\n/// >>> triples_sum_to_zero(l: [1, 3, 5, 0])\n/// false\n/// >>> triples_sum_to_zero(l: [1, 3, -2, 1])\n/// true\n/// >>> triples_sum_to_zero(l: [1, 2, 3, 7])\n/// false\n/// >>> triples_sum_to_zero(l: [2, 4, -5, 3, 9, 7])\n/// true\n/// >>> triples_sum_to_zero(l: [1])\n/// false\nfunc triples_sum_to_zero(l: [Int]) -> Bool {\n for i in 0.. Int {\n return n"], ["/// Return array with elements incremented by 1.\n/// >>> incr_list(l: [1, 2, 3])\n/// [2, 3, 4]\n/// >>> incr_list(l: [5, 3, 5, 2, 3, 3, 9, 0, 123])\n/// [6, 4, 6, 3, 4, 4, 10, 1, 124]\nfunc incr_list(l: [Int]) -> [Int] {\n return l.map { $0 + 1 }"], ["/// pairs_sum_to_zero takes an array of integers as an input.\n/// it returns true if there are two distinct elements in the array that\n/// sum to zero, and false otherwise.\n/// >>> pairs_sum_to_zero(l: [1, 3, 5, 0])\n/// false\n/// >>> pairs_sum_to_zero(l: [1, 3, -2, 1])\n/// false\n/// >>> pairs_sum_to_zero(l: [1, 2, 3, 7])\n/// false\n/// >>> pairs_sum_to_zero(l: [2, 4, -5, 3, 5, 7])\n/// true\n/// >>> pairs_sum_to_zero(l: [1])\n/// false\nfunc pairs_sum_to_zero(l: [Int]) -> Bool {\n for i in 0..>> change_base(x: 8, base: 3)\n/// \"22\"\n/// >>> change_base(x: 8, base: 2)\n/// \"1000\"\n/// >>> change_base(x: 7, base: 2)\n/// \"111\"\nfunc change_base(x: Int, base: Int) -> String {\n var result = \"\"\n var quotient = x\n while quotient > 0 {\n let remainder = quotient % base\n result = String(remainder) + result\n quotient = quotient / base\n }\n return result"], ["/// Given length of a side and high return area for a triangle.\n/// >>> triangle_area(a: 5, h: 3)\n/// 7.5\nfunc triangle_area(a: Int, h: Int) -> Double {\n return 0.5 * Double(a) * Double(h)"], ["/// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n/// fib4(0) -> 0\n/// fib4(1) -> 0\n/// fib4(2) -> 2\n/// fib4(3) -> 0\n/// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n/// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n/// >>> fib4(n: 5)\n/// 4\n/// >>> fib4(n: 6)\n/// 8\n/// >>> fib4(n: 7)\n/// 14\nfunc fib4(n: Int) -> Int {\n var fibs = [0, 0, 2, 0]\n for i in 4...n {\n fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])\n }\n return fibs[n]"], ["/// Return median of elements in the array l.\n/// >>> median(l: [3, 1, 2, 4, 5])\n/// 3\n/// >>> median(l: [-10, 4, 6, 1000, 10, 20])\n/// 15.0\nfunc median(l: [Int]) -> Double {\n let sorted = l.sorted()\n let mid = sorted.count / 2\n return sorted.count % 2 == 0 ? Double(sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid])"], ["/// Checks if given string is a palindrome\n/// >>> is_palindrome(text: \"\")\n/// true\n/// >>> is_palindrome(text: \"aba\")\n/// true\n/// >>> is_palindrome(text: \"aaaaa\")\n/// true\n/// >>> is_palindrome(text: \"zbcd\")\n/// false\nfunc is_palindrome(text: String) -> Bool {\n let reversedText = String(text.reversed())\n return text == reversedText"], ["/// Return 2^n modulo p (be aware of numerics).\n/// >>> modp(n: 3, p: 5)\n/// 3\n/// >>> modp(n: 1101, p: 101)\n/// 2\n/// >>> modp(n: 0, p: 101)\n/// 1\n/// >>> modp(n: 3, p: 11)\n/// 8\n/// >>> modp(n: 100, p: 101)\n/// 1\nfunc modp(n: Int, p: Int) -> Int {\n return pow(2, n, p)"], ["/// For a given array of input numbers, calculate Mean Absolute Deviation\n/// around the mean of this dataset.\n/// Mean Absolute Deviation is the average absolute difference between each\n/// element and a centerpoint (mean in this case):\n/// MAD = average | x - x_mean |\n/// >>> mean_absolute_deviation(numbers: [1.0, 2.0, 3.0, 4.0])\n/// 1.0\nfunc mean_absolute_deviation(numbers: [Double]) -> Double {\n let mean = numbers.reduce(0, +) / Double(numbers.count)\n let deviations = numbers.map { abs($0 - mean) }\n let mad = deviations.reduce(0, +) / Double(deviations.count)\n return mad"], ["/// remove_vowels is a function that takes string and returns string without vowels.\n/// >>> remove_vowels(text: \"\")\n/// \"\"\n/// >>> remove_vowels(text: \"abcdef\")\n/// \"bcdf\"\n/// >>> remove_vowels(text: \"aaaaa\")\n/// \"\"\n/// >>> remove_vowels(text: \"aaBAA\")\n/// \"B\"\n/// >>> remove_vowels(text: \"zbcd\")\n/// \"zbcd\"\nfunc remove_vowels(text: String) -> String {\n let vowels = \"aeiouAEIOU\"\n var result = \"\"\n for char in text {\n if vowels.contains(char) == false {\n result.append(char)\n }\n }\n return result"], ["/// Return true if all numbers in the array l are below threshold t.\n/// >>> below_threshold(l: [1, 2, 4, 10], t: 100)\n/// true\n/// >>> below_threshold(l: [1, 20, 4, 10], t: 5)\n/// false\nfunc below_threshold(l: [Int], t: Int) -> Bool {\n for num in l {\n if num >= t {\n return false\n }\n }\n return true"], ["/// Add two numbers x and y\n/// >>> add(x: 2, y: 3)\n/// 5\n/// >>> add(x: 5, y: 7)\n/// 12\nfunc add(x: Int, y: Int) -> Int {\n return x + y"], ["/// Check if two words have the same characters.\n/// >>> same_chars(s0: \"eabcdzzzz\", s1: \"dddzzzzzzzddeddabc\")\n/// true\n/// >>> same_chars(s0: \"abcd\", s1: \"dddddddabc\")\n/// true\n/// >>> same_chars(s0: \"dddddddabc\", s1: \"abcd\")\n/// true\n/// >>> same_chars(s0: \"eabcd\", s1: \"dddddddabc\")\n/// false\n/// >>> same_chars(s0: \"abcd\", s1: \"dddddddabce\")\n/// false\n/// >>> same_chars(s0: \"eabcdzzzz\", s1: \"dddzzzzzzzddddabc\")\n/// false\nfunc same_chars(s0: String, s1: String) -> Bool {\n let sorted0 = Array(s0).sorted()\n let sorted1 = Array(s1).sorted()\n return sorted0 == sorted1"], ["/// Return n-th Fibonacci number.\n/// >>> fib(n: 10)\n/// 55\n/// >>> fib(n: 1)\n/// 1\n/// >>> fib(n: 8)\n/// 21\nfunc fib(n: Int) -> Int {\n if n <= 1 {\n return n\n }\n var a = 0\n var b = 1\n for _ in 2..\".\n/// return true if every opening bracket has a corresponding closing bracket.\n/// >>> correct_bracketing(brackets: \"<\")\n/// false\n/// >>> correct_bracketing(brackets: \"<>\")\n/// true\n/// >>> correct_bracketing(brackets: \"<<><>>\")\n/// true\n/// >>> correct_bracketing(brackets: \"><<>\")\n/// false\nfunc correct_bracketing(brackets: String) -> Bool {\n var stack = [Character]()\n for bracket in brackets {\n if bracket == \"<\" {\n stack.append(bracket)\n } else if bracket == \">\" {\n if stack.count == 0 {\n return false\n }\n stack.removeLast()\n }\n }\n return stack.count == 0"], ["/// Return true is array elements are monotonically increasing or decreasing.\n/// >>> monotonic(l: [1, 2, 4, 20])\n/// true\n/// >>> monotonic(l: [1, 20, 4, 10])\n/// false\n/// >>> monotonic(l: [4, 1, 0, -10])\n/// true\nfunc monotonic(l: [Int]) -> Bool {\n var increasing = true\n var decreasing = true\n for i in 1.. l[i-1] {\n decreasing = false\n } else if l[i] < l[i-1] {\n increasing = false\n }\n }\n return increasing || decreasing"], ["/// Return sorted unique common elements for two arrays.\n/// >>> common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121])\n/// [1, 5, 653]\n/// >>> common(l1: [5, 3, 2, 8], l2: [3, 2])\n/// [2, 3]\nfunc common(l1: [Int], l2: [Int]) -> [Int] {\n let set1 = Set(l1)\n let set2 = Set(l2)\n let commonSet = set1.intersection(set2)\n let commonArray = Array(commonSet)\n let sortedArray = commonArray.sorted()\n return sortedArray"], ["/// Return the largest prime factor of n. Assume n > 1 and is not a prime.\n/// >>> largest_prime_factor(n: 13195)\n/// 29\n/// >>> largest_prime_factor(n: 2048)\n/// 2\nfunc largest_prime_factor(n: Int) -> Int {\n var factor = 2\n var largest_factor = 1\n\n while factor * factor <= n {\n if n % factor == 0 {\n n /= factor\n largest_factor = factor\n } else {\n factor += 1\n }\n }\n\n if n > largest_factor {\n largest_factor = n\n }\n\n return largest_factor"], ["/// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'\n/// >>> intersperse(numbers: [] as [Int], delimeter: 4)\n/// [] as [Int]\n/// >>> intersperse(numbers: [1, 2, 3], delimeter: 4)\n/// [1, 4, 2, 4, 3]\nfunc intersperse(numbers: [Int], delimeter: Int) -> [Int] {\n var result: [Int] = []\n for i in 0..>> sum_to_n(n: 30)\n/// 465\n/// >>> sum_to_n(n: 100)\n/// 5050\n/// >>> sum_to_n(n: 5)\n/// 15\n/// >>> sum_to_n(n: 10)\n/// 55\n/// >>> sum_to_n(n: 1)\n/// 1\nfunc sum_to_n(n: Int) -> Int {\n return n * (n + 1) / 2"], ["/// brackets is a string of \"(\" and \")\".\n/// return true if every opening bracket has a corresponding closing bracket.\n/// >>> correct_bracketing(brackets: \"(\")\n/// false\n/// >>> correct_bracketing(brackets: \"()\")\n/// true\n/// >>> correct_bracketing(brackets: \"(()())\")\n/// true\n/// >>> correct_bracketing(brackets: \")(()\")\n/// false\nfunc correct_bracketing(brackets: String) -> Bool {\n var stack = [Character]()\n for bracket in brackets {\n if bracket == \"(\" {\n stack.append(bracket)\n } else if bracket == \")\" {\n if stack.count == 0 {\n return false\n }\n stack.removeLast()\n }\n }\n return stack.count == 0"], ["/// xs represent coefficients of a polynomial.\n/// xs[0] + xs[1] * x + xs[2] * x^2 + ....\n/// Return derivative of this polynomial in the same form.\n/// >>> derivative(xs: [3, 1, 2, 4, 5])\n/// [1, 4, 12, 20]\n/// >>> derivative(xs: [1, 2, 3])\n/// [2, 6]\nfunc derivative(xs: [Int]) -> [Int] {\n var result = [Int]()\n for (index, value) in xs.enumerated() {\n if index == 0 {\n continue\n }\n result.append(value * index)\n }\n return result"], ["/// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n/// fibfib(0) == 0\n/// fibfib(1) == 0\n/// fibfib(2) == 1\n/// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n/// Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n/// >>> fibfib(n: 1)\n/// 0\n/// >>> fibfib(n: 5)\n/// 4\n/// >>> fibfib(n: 8)\n/// 24\nfunc fibfib(n: Int) -> Int {\n var fibfib = [Int](repeating: 0, count: n+1)\n fibfib[1] = 0\n fibfib[2] = 1\n for i in 3..>> vowels_count(s: \"abcde\")\n/// 2\n/// >>> vowels_count(s: \"ACEDY\")\n/// 3\nfunc vowels_count(s: String) -> Int {\n let vowels = Set([\"a\", \"e\", \"i\", \"o\", \"u\", \"y\"])\n var count = 0\n for char in s.lowercased() {\n if vowels.contains(String(char)) {\n count += 1\n }\n }\n return count"], ["/// Circular shift the digits of the integer x, shift the digits right by shift\n/// and return the result as a string.\n/// If shift > number of digits, return digits reversed.\n/// >>> circular_shift(x: 12, shift: 1)\n/// \"21\"\n/// >>> circular_shift(x: 12, shift: 2)\n/// \"12\"\nfunc circular_shift(x: Int, shift: Int) -> String {\n let digits = String(x)\n let n = digits.count\n let shiftMod = shift % n\n let shifted = digits.suffix(n - shiftMod) + digits.prefix(shiftMod)\n return shifted"], ["/// Task\n/// Write a function that takes a string as input and returns the sum of the upper characters only'\n/// ASCII codes.\n/// Examples:\n/// >>> digitSum(s: \"\")\n/// 0\n/// >>> digitSum(s: \"abAB\")\n/// 131\n/// >>> digitSum(s: \"abcCd\")\n/// 67\n/// >>> digitSum(s: \"helloE\")\n/// 69\n/// >>> digitSum(s: \"woArBld\")\n/// 131\n/// >>> digitSum(s: \"aAaaaXa\")\n/// 153\nfunc digitSum(s: String) -> Int {\n var sum = 0\n for char in s {\n if char.isUppercase {\n sum += Int(char.asciiValue!)\n }\n }\n return sum"], ["/// In this task, you will be given a string that represents a number of apples and oranges \n/// that are distributed in a basket of fruit this basket contains \n/// apples, oranges, and mango fruits. Given the string that represents the total number of \n/// the oranges and apples and an integer that represent the total number of the fruits \n/// in the basket return the number of the mango fruits in the basket.\n/// for examble:\n/// >>> fruit_distribution(s: \"5 apples and 6 oranges\", n: 19)\n/// 8\n/// >>> fruit_distribution(s: \"0 apples and 1 oranges\", n: 3)\n/// 2\n/// >>> fruit_distribution(s: \"2 apples and 3 oranges\", n: 100)\n/// 95\n/// >>> fruit_distribution(s: \"100 apples and 1 oranges\", n: 120)\n/// 19\nfunc fruit_distribution(s: String, n: Int) -> Int {\n let components = s.components(separatedBy: \" \")\n let apples = Int(components[0]) ?? 0\n let oranges = Int(components[3]) ?? 0\n let mangoes = n - apples - oranges\n return mangoes"], ["/// \"Given an array representing a branch of a tree that has non-negative integer nodes\n/// your task is to pluck one of the nodes and return it.\n/// The plucked node should be the node with the smallest even value.\n/// If multiple nodes with the same smallest even value are found return the node that has smallest index.\n/// The plucked node should be returned in an array, [ smalest_value, its index ],\n/// If there are no even values or the given array is empty, return [].\n/// Example 1:\n/// >>> pluck(arr: [4, 2, 3])\n/// [2, 1]\n/// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n/// Example 2:\n/// >>> pluck(arr: [1, 2, 3])\n/// [2, 1]\n/// Explanation: 2 has the smallest even value, and 2 has the smallest index.\n/// Example 3:\n/// >>> pluck(arr: [] as [Int])\n/// [] as [Int]\n/// Example 4:\n/// >>> pluck(arr: [5, 0, 3, 0, 4, 2])\n/// [0, 1]\n/// Explanation: 0 is the smallest value, but there are two zeros,\n/// so we will choose the first zero, which has the smallest index.\n/// Constraints:\n/// * 1 <= nodes.length <= 10000\n/// * 0 <= node.value\nfunc pluck(arr: [Int]) -> [Int] {\n var smallestEvenValue = Int.max\n var smallestEvenIndex = Int.max\n for (index, value) in arr.enumerated() {\n if value % 2 == 0 && value < smallestEvenValue {\n smallestEvenValue = value\n smallestEvenIndex = index\n }\n }\n if smallestEvenValue == Int.max {\n return []\n } else {\n return [smallestEvenValue, smallestEvenIndex]\n }"], ["/// You are given a non-empty array of positive integers. Return the greatest integer that is greater than \n/// zero, and has a frequency greater than or equal to the value of the integer itself. \n/// The frequency of an integer is the number of times it appears in the array.\n/// If no such a value exist, return -1.\n/// Examples:\n/// >>> search(lst: [4, 1, 2, 2, 3, 1])\n/// 2\n/// >>> search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])\n/// 3\n/// >>> search(lst: [5, 5, 4, 4, 4])\n/// -1\nfunc search(lst: [Int]) -> Int {\n var freq = [Int: Int]()\n for num in lst {\n freq[num, default: 0] += 1\n }\n for num in freq.keys.sorted(by: >) {\n if freq[num] >= num {\n return num\n }\n }\n return -1"], ["/// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n/// For each of the group, output the deepest level of nesting of parentheses.\n/// E.g. (()()) has maximum two levels of nesting while ((())) has three.\n/// >>> parse_nested_parens(paren_string: \"(()()) ((())) () ((())()())\")\n/// [2, 3, 1, 3]\nfunc parse_nested_parens(paren_string: String) -> [Int] {\n var result: [Int] = []\n var stack: [Int] = []\n var maxDepth = 0\n for char in paren_string {\n if char == \"(\" {\n stack.append(0)\n } else if char == \")\" {\n let depth = stack.popLast() ?? 0\n maxDepth = max(maxDepth, depth)\n if stack.count > 0 {\n stack[stack.count - 1] = max(stack[stack.count - 1], depth + 1)\n }\n }\n }\n result.append(maxDepth)\n return result"], ["/// Given array of integers, return array in strange order.\n/// Strange sorting, is when you start with the minimum value,\n/// then maximum of the remaining integers, then minimum and so on.\n/// Examples:\n/// >>> strange_sort_list(lst: [1, 2, 3, 4])\n/// [1, 4, 2, 3]\n/// >>> strange_sort_list(lst: [5, 5, 5, 5])\n/// [5, 5, 5, 5]\n/// >>> strange_sort_list(lst: [] as [Int])\n/// [] as [Int]\nfunc strange_sort_list(lst: [Int]) -> [Int] {\n var sortedList = lst\n sortedList.sort()\n var result = [Int]()\n var isMin = true\n while !sortedList.isEmpty {\n if isMin {\n result.append(sortedList.removeFirst())\n } else {\n result.append(sortedList.removeLast())\n }\n isMin = !isMin\n }\n return result"], ["/// Given the lengths of the three sides of a triangle. Return the area of\n/// the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n/// Otherwise return -1\n/// Three sides make a valid triangle when the sum of any two sides is greater \n/// than the third side.\n/// Example:\n/// >>> triangle_area(a: 3, b: 4, c: 5)\n/// 6.0\n/// >>> triangle_area(a: 1, b: 2, c: 10)\n/// -1\nfunc triangle_area(a: Int, b: Int, c: Int) -> Double {\n let sides = [a, b, c]\n let sortedSides = sides.sorted()\n if sortedSides[0] + sortedSides[1] > sortedSides[2] {\n let s = Double(sides.reduce(0, +)) / 2.0\n let area = sqrt(s * (s - Double(sides[0])) * (s - Double(sides[1])) * (s - Double(sides[2])))\n return Double(round(100 * area) / 100)\n } else {\n return -1\n }"], ["/// Write a function that returns true if the object q will fly, and false otherwise.\n/// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.\n/// Example:\n/// >>> will_it_fly(q: [1, 2], w: 5)\n/// false\n/// # 1+2 is less than the maximum possible weight, but it's unbalanced.\n/// >>> will_it_fly(q: [3, 2, 3], w: 1)\n/// false\n/// # it's balanced, but 3+2+3 is more than the maximum possible weight.\n/// >>> will_it_fly(q: [3, 2, 3], w: 9)\n/// true\n/// # 3+2+3 is less than the maximum possible weight, and it's balanced.\n/// >>> will_it_fly(q: [3], w: 5)\n/// true\n/// # 3 is less than the maximum possible weight, and it's balanced.\nfunc will_it_fly(q: [Int], w: Int) -> Bool {\n var sum = 0\n for i in 0.. w {\n return false\n }\n for i in 0..>> smallest_change(arr: [1, 2, 3, 5, 4, 7, 9, 6])\n/// 4\n/// >>> smallest_change(arr: [1, 2, 3, 4, 3, 2, 2])\n/// 1\n/// >>> smallest_change(arr: [1, 2, 3, 2, 1])\n/// 0\nfunc smallest_change(arr: [Int]) -> Int {\n var count = 0\n var i = 0\n var j = arr.count - 1\n while i < j {\n if arr[i] != arr[j] {\n count += 1\n }\n i += 1\n j -= 1\n }\n return count"], ["/// Write a function that accepts two arrays of strings and returns the array that has \n/// total number of chars in the all strings of the array less than the other array.\n/// if the two arrays have the same number of chars, return the first array.\n/// Examples\n/// >>> total_match(lst1: [] as [String], lst2: [] as [String])\n/// [] as [String]\n/// >>> total_match(lst1: [\"hi\", \"admin\"], lst2: [\"hI\", \"Hi\"])\n/// [\"hI\", \"Hi\"]\n/// >>> total_match(lst1: [\"hi\", \"admin\"], lst2: [\"hi\", \"hi\", \"admin\", \"project\"])\n/// [\"hi\", \"admin\"]\n/// >>> total_match(lst1: [\"hi\", \"admin\"], lst2: [\"hI\", \"hi\", \"hi\"])\n/// [\"hI\", \"hi\", \"hi\"]\n/// >>> total_match(lst1: [\"4\"], lst2: [\"1\", \"2\", \"3\", \"4\", \"5\"])\n/// [\"4\"]\nfunc total_match(lst1: [String], lst2: [String]) -> [String] {\n let lst1Chars = lst1.reduce(0) { $0 + $1.count }\n let lst2Chars = lst2.reduce(0) { $0 + $1.count }\n if lst1Chars < lst2Chars {\n return lst1\n } else if lst1Chars > lst2Chars {\n return lst2\n } else {\n return lst1\n }"], ["/// Write a function that returns true if the given number is the multiplication of 3 prime numbers\n/// and false otherwise.\n/// Knowing that (a) is less then 100. \n/// Example:\n/// >>> is_multiply_prime(a: 30)\n/// true\n/// 30 = 2 * 3 * 5\nfunc is_multiply_prime(a: Int) -> Bool {\n let 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]\n var count = 0\n var product = 1\n for prime in primes {\n if a % prime == 0 {\n count += 1\n product *= prime\n }\n if count == 3 {\n break\n }\n }\n return count == 3 && product == a"], ["/// Your task is to write a function that returns true if a number x is a simple\n/// power of n and false in other cases.\n/// x is a simple power of n if n**int=x\n/// For example:\n/// >>> is_simple_power(x: 1, n: 4)\n/// true\n/// >>> is_simple_power(x: 2, n: 2)\n/// true\n/// >>> is_simple_power(x: 8, n: 2)\n/// true\n/// >>> is_simple_power(x: 3, n: 2)\n/// false\n/// >>> is_simple_power(x: 3, n: 1)\n/// false\n/// >>> is_simple_power(x: 5, n: 3)\n/// false\nfunc is_simple_power(x: Int, n: Int) -> Bool {\n var power = 0\n var result = 1\n while result < x {\n result *= n\n power += 1\n }\n return result == x"], ["/// Write a function that takes an integer a and returns true \n/// if this ingeger is a cube of some integer number.\n/// Note: you may assume the input is always valid.\n/// Examples:\n/// >>> iscube(a: 1)\n/// true\n/// >>> iscube(a: 2)\n/// false\n/// >>> iscube(a: -1)\n/// true\n/// >>> iscube(a: 64)\n/// true\n/// >>> iscube(a: 0)\n/// true\n/// >>> iscube(a: 180)\n/// false\nfunc iscube(a: Int) -> Bool {\n let cubeRoot = Int(pow(Double(a), 1.0/3.0))\n return cubeRoot * cubeRoot * cubeRoot == a"], ["/// You have been tasked to write a function that receives \n/// a hexadecimal number as a string and counts the number of hexadecimal \n/// digits that are primes (prime number, or a prime, is a natural number \n/// greater than 1 that is not a product of two smaller natural numbers).\n/// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n/// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n/// So you have to determine a number of the following digits: 2, 3, 5, 7, \n/// B (=decimal 11), D (=decimal 13).\n/// Note: you may assume the input is always correct or empty string, \n/// and symbols A,B,C,D,E,F are always uppercase.\n/// Examples:\n/// >>> hex_key(num: \"AB\")\n/// 1\n/// >>> hex_key(num: \"1077E\")\n/// 2\n/// >>> hex_key(num: \"ABED1A33\")\n/// 4\n/// >>> hex_key(num: \"123456789ABCDEF0\")\n/// 6\n/// >>> hex_key(num: \"2020\")\n/// 2\nfunc hex_key(num: String) -> Int {\n let primes = Set([2, 3, 5, 7, 11, 13, 17])\n var count = 0\n for char in num {\n if let digit = Int(String(char), radix: 16) {\n if primes.contains(digit) {\n count += 1\n }\n }\n }\n return count"], ["/// You will be given a number in decimal form and your task is to convert it to\n/// binary format. The function should return a string, with each character representing a binary\n/// number. Each character in the string will be '0' or '1'.\n/// There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n/// The extra characters are there to help with the format.\n/// Examples:\n/// >>> decimal_to_binary(decimal: 15)\n/// \"db1111db\"\n/// >>> decimal_to_binary(decimal: 32)\n/// \"db100000db\"\nfunc decimal_to_binary(decimal: Int) -> String {\n let binary = String(decimal, radix: 2)\n return \"db\\(binary)db\""], ["/// Filter an input array of strings only for ones that contain given substring\n/// >>> filter_by_substring(strings: [] as [String], substring: \"a\")\n/// [] as [String]\n/// >>> filter_by_substring(strings: [\"abc\", \"bacd\", \"cde\", \"array\"], substring: \"a\")\n/// [\"abc\", \"bacd\", \"array\"]\nfunc filter_by_substring(strings: [String], substring: String) -> [String] {\n return strings.filter { $0.contains(substring) }"], ["/// You are given a string s.\n/// Your task is to check if the string is hapswift or not.\n/// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct\n/// For example:\n/// >>> is_happy(s: \"a\")\n/// false\n/// >>> is_happy(s: \"aa\")\n/// false\n/// >>> is_happy(s: \"abcd\")\n/// true\n/// >>> is_happy(s: \"aabb\")\n/// false\n/// >>> is_happy(s: \"adb\")\n/// true\n/// >>> is_happy(s: \"xyy\")\n/// false\nfunc is_happy(s: String) -> Bool {\n if s.count < 3 {\n return false\n }\n for i in 0.. 3.7 A \n/// > 3.3 A- \n/// > 3.0 B+\n/// > 2.7 B \n/// > 2.3 B-\n/// > 2.0 C+\n/// > 1.7 C\n/// > 1.3 C-\n/// > 1.0 D+ \n/// > 0.7 D \n/// > 0.0 D-\n/// 0.0 E\n/// Example:\n/// >>> numerical_letter_grade(grades: [4.0, 3, 1.7, 2, 3.5])\n/// [\"A+\", \"B\", \"C-\", \"C\", \"A-\"]\nfunc numerical_letter_grade(grades: [Double]) -> [String] {\n var letterGrades = [String]()\n for gpa in grades {\n if gpa == 4.0 {\n letterGrades.append(\"A+\")\n } else if gpa > 3.7 {\n letterGrades.append(\"A\")\n } else if gpa > 3.3 {\n letterGrades.append(\"A-\")\n } else if gpa > 3.0 {\n letterGrades.append(\"B+\")\n } else if gpa > 2.7 {\n letterGrades.append(\"B\")\n } else if gpa > 2.3 {\n letterGrades.append(\"B-\")\n } else if gpa > 2.0 {\n letterGrades.append(\"C+\")\n } else if gpa > 1.7 {\n letterGrades.append(\"C\")\n } else if gpa > 1.3 {\n letterGrades.append(\"C-\")\n } else if gpa > 1.0 {\n letterGrades.append(\"D+\")\n } else if gpa > 0.7 {\n letterGrades.append(\"D\")\n } else if gpa > 0.0 {\n letterGrades.append(\"D-\")\n } else {\n letterGrades.append(\"E\")\n }\n }\n return letterGrades"], ["/// Write a function that takes a string and returns true if the string\n/// length is a prime number or false otherwise\n/// Examples\n/// >>> prime_length(string: \"Hello\")\n/// true\n/// >>> prime_length(string: \"abcdcba\")\n/// true\n/// >>> prime_length(string: \"kittens\")\n/// true\n/// >>> prime_length(string: \"orange\")\n/// false\nfunc prime_length(string: String) -> Bool {\n let length = string.count\n if length < 2 {\n return false\n }\n for i in 2.. Int {\n if n == 1 {\n return 1\n }\n let count = 10 * pow(10, n as Double - 2)\n return Int(count)"], ["/// Given a positive integer N, return the total sum of its digits in binary.\n/// Example\n/// >>> solve(N: 1000)\n/// \"1\"\n/// >>> solve(N: 150)\n/// \"110\"\n/// >>> solve(N: 147)\n/// \"1100\"\n/// Variables:\n/// @N integer\n/// Constraints: 0 \u2264 N \u2264 10000.\n/// Output:\n/// a string of binary number\nfunc solve(N: Int) -> String {\n var sum = 0\n var n = N\n while n > 0 {\n sum += n % 10\n n /= 10\n }\n return String(sum, radix: 2)"], ["/// Given a non-empty array of integers lst. add the even elements that are at odd indices..\n/// Examples:\n/// >>> add(lst: [4, 2, 6, 7])\n/// 2\nfunc add(lst: [Int]) -> Int {\n var sum = 0\n for (index, value) in lst.enumerated() {\n if index % 2 != 0 && value % 2 == 0 {\n sum += value\n }\n }\n return sum"], ["/// Write a function that takes a string and returns an ordered version of it.\n/// Ordered version of string, is a string where all words (separated by space)\n/// are replaced by a new word where all the characters arranged in\n/// ascending order based on ascii value.\n/// Note: You should keep the order of words and blank spaces in the sentence.\n/// For example:\n/// >>> anti_shuffle(s: \"Hi\")\n/// \"Hi\"\n/// >>> anti_shuffle(s: \"hello\")\n/// \"ehllo\"\n/// >>> anti_shuffle(s: \"Hello World!!!\")\n/// \"Hello !!!Wdlor\"\nfunc anti_shuffle(s: String) -> String {\n var result = \"\"\n for word in s.split(separator: \" \") {\n let sortedWord = String(word.sorted())\n result += sortedWord + \" \"\n }\n return result.trimmingCharacters(in: .whitespacesAndNewlines)"], ["/// You are given a 2 dimensional data, as a nested arrays,\n/// which is similar to matrix, however, unlike matrices,\n/// each row may contain a different number of columns.\n/// Given lst, and integer x, find integers x in the array,\n/// and return array of tuples, [(x1, y1), (x2, y2) ...] such that\n/// each tuple is a coordinate - (row, columns), starting with 0.\n/// Sort coordinates initially by rows in ascending order.\n/// Also, sort coordinates of the row by columns in descending order.\n/// Examples:\n/// >>> get_row(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1)\n/// [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n/// >>> get_row(lst: [] as [[Int]], x: 1)\n/// [] as [(Int, Int)]\n/// >>> get_row(lst: [[] as [Int], [1], [1, 2, 3]], x: 3)\n/// [(2, 2)]\nfunc get_row(lst: [[Int]], x: Int) -> [(Int, Int)] {\n var result: [(Int, Int)] = []\n for (row, columns) in lst.enumerated() {\n for (column, value) in columns.enumerated() {\n if value == x {\n result.append((row, column))\n }\n }\n }\n result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.1) }\n return result"], ["/// Given an array of non-negative integers, return a coswift of the given array after sorting,\n/// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n/// or sort it in descending order if the sum( first index value, last index value) is even.\n/// Note:\n/// * don't change the given array.\n/// Examples:\n/// >>> sort_array(array: [] as [Int])\n/// [] as [Int]\n/// >>> sort_array(array: [5])\n/// [5]\n/// >>> sort_array(array: [2, 4, 3, 0, 1, 5])\n/// [0, 1, 2, 3, 4, 5]\n/// >>> sort_array(array: [2, 4, 3, 0, 1, 5, 6])\n/// [6, 5, 4, 3, 2, 1, 0]\nfunc sort_array(array: [Int]) -> [Int] {\n var sortedArray = array\n if array.count > 0 {\n let sum = array[0] + array[array.count - 1]\n if sum % 2 == 0 {\n sortedArray.sort(by: >)\n } else {\n sortedArray.sort()\n }\n }\n return sortedArray"], ["/// Create a function encrypt that takes a string as an argument and\n/// returns a string encrypted with the alphabet being rotated. \n/// The alphabet should be rotated in a manner such that the letters \n/// shift down by two multiplied to two places.\n/// For example:\n/// >>> encrypt(s: \"hi\")\n/// \"lm\"\n/// >>> encrypt(s: \"asdfghjkl\")\n/// \"ewhjklnop\"\n/// >>> encrypt(s: \"gf\")\n/// \"kj\"\n/// >>> encrypt(s: \"et\")\n/// \"ix\"\nfunc encrypt(s: String) -> String {\n var encryptedString = \"\"\n for char in s {\n let asciiValue = char.asciiValue\n let shiftedValue = asciiValue + 2*2\n let encryptedChar = Character(UnicodeScalar(shiftedValue)!)\n encryptedString += String(encryptedChar)\n }\n return encryptedString"], ["/// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.\n/// Empty sum should be equal to 0 and empty product should be equal to 1.\n/// >>> sum_product(numbers: [] as [Int])\n/// (0, 1)\n/// >>> sum_product(numbers: [1, 2, 3, 4])\n/// (10, 24)\nfunc sum_product(numbers: [Int]) -> (Int, Int) {\n var sum = 0\n var product = 1\n for number in numbers {\n sum += number\n product *= number\n }\n return (sum, product)"], ["/// You are given an array of integers.\n/// Write a function next_smallest() that returns the 2nd smallest element of the array.\n/// Return nil if there is no such element.\n/// >>> next_smallest(lst: [1, 2, 3, 4, 5])\n/// 2\n/// >>> next_smallest(lst: [5, 1, 4, 3, 2])\n/// 2\n/// >>> next_smallest(lst: [] as [Int])\n/// nil\n/// >>> next_smallest(lst: [1, 1])\n/// nil\nfunc next_smallest(lst: [Int]) -> Int? {\n if lst.count < 2 {\n return nil\n }\n var smallest = lst[0]\n var secondSmallest = lst[1]\n if smallest > secondSmallest {\n let temp = smallest\n smallest = secondSmallest\n secondSmallest = temp\n }\n for i in 2..>> is_bored(S: \"Hello world\")\n/// 0\n/// >>> is_bored(S: \"The sky is blue. The sun is shining. I love this weather\")\n/// 1\nfunc is_bored(S: String) -> Int {\n var count = 0\n var sentences = S.components(separatedBy: \".!?\")\n for sentence in sentences {\n if sentence.hasPrefix(\"I\") {\n count += 1\n }\n }\n return count"], ["/// Create a function that takes 3 numbers.\n/// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n/// Returns false in any other cases.\n/// Examples\n/// >>> any_int(x: 5, y: 2, z: 7)\n/// true\n/// >>> any_int(x: 3, y: 2, z: 2)\n/// false\n/// >>> any_int(x: 3, y: -2, z: 1)\n/// true\n/// >>> any_int(x: 3.6, y: -2.2, z: 2)\n/// false\nfunc any_int(x: Double, y: Double, z: Double) -> Bool {\n if x.truncatingRemainder(dividingBy: 1) != 0 || y.truncatingRemainder(dividingBy: 1) != 0 || z.truncatingRemainder(dividingBy: 1) != 0 {\n return false\n }\n if x == y + z || y == x + z || z == x + y {\n return true\n }\n return false"], ["/// Write a function that takes a message, and encodes in such a \n/// way that it swaps case of all letters, replaces all vowels in \n/// the message with the letter that appears 2 places ahead of that \n/// vowel in the english alphabet. \n/// Assume only letters. \n/// Examples:\n/// >>> encode(message: \"test\")\n/// \"TGST\"\n/// >>> encode(message: \"This is a message\")\n/// \"tHKS KS C MGSSCGG\"\nfunc encode(message: String) -> String {\n var encodedMessage = \"\"\n let vowels = \"aeiouAEIOU\"\n for char in message {\n let newChar: Character\n if vowels.contains(char) {\n let index = vowels.index(of: char)\n let nextIndex = vowels.index(vowels.startIndex, offsetBy: (index.encodedOffset + 2) % vowels.count)\n newChar = vowels[nextIndex]\n } else {\n newChar = char.isUppercase ? char.lowercased() : char.uppercased()\n }\n encodedMessage.append(newChar)\n }\n return encodedMessage"], ["/// You are given an array of integers.\n/// You need to find the largest prime value and return the sum of its digits.\n/// Examples:\n/// >>> skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3])\n/// 10\n/// >>> skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1])\n/// 25\n/// >>> skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3])\n/// 13\n/// >>> skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6])\n/// 11\n/// >>> skjkasdkd(lst: [0, 81, 12, 3, 1, 21])\n/// 3\n/// >>> skjkasdkd(lst: [0, 8, 1, 2, 1, 7])\n/// 7\nfunc skjkasdkd(lst: [Int]) -> Int {\n var largestPrime = 0\n for num in lst {\n if isPrime(num) && num > largestPrime {\n largestPrime = num\n }\n }\n return sumOfDigits(largestPrime)"], ["/// Implement a function that takes an non-negative integer and returns an array of the first n\n/// integers that are prime numbers and less than n.\n/// for example:\n/// >>> count_up_to(n: 5)\n/// [2, 3]\n/// >>> count_up_to(n: 11)\n/// [2, 3, 5, 7]\n/// >>> count_up_to(n: 0)\n/// [] as [Int]\n/// >>> count_up_to(n: 20)\n/// [2, 3, 5, 7, 11, 13, 17, 19]\n/// >>> count_up_to(n: 1)\n/// [] as [Int]\n/// >>> count_up_to(n: 18)\n/// [2, 3, 5, 7, 11, 13, 17]\nfunc count_up_to(n: Int) -> [Int] {\n var primes = [Int]()\n for i in 2..>> multiply(a: 148, b: 412)\n/// 16\n/// >>> multiply(a: 19, b: 28)\n/// 72\n/// >>> multiply(a: 2020, b: 1851)\n/// 0\n/// >>> multiply(a: 14, b: -15)\n/// 20\nfunc multiply(a: Int, b: Int) -> Int {\n return abs(a % 10) * abs(b % 10)"], ["/// Given a string s, count the number of uppercase vowels in even indices.\n/// For example:\n/// >>> count_upper(s: \"aBCdEf\")\n/// 1\n/// >>> count_upper(s: \"abcdefg\")\n/// 0\n/// >>> count_upper(s: \"dBBE\")\n/// 0\nfunc count_upper(s: String) -> Int {\n var count = 0\n for (index, char) in s.enumerated() {\n if index % 2 == 0 && char.isUppercase && \"AEIOU\".contains(char) {\n count += 1\n }\n }\n return count"], ["/// Create a function that takes a value (string) representing a number\n/// and returns the closest integer to it. If the number is equidistant\n/// from two integers, round it away from zero.\n/// Examples\n/// >>> closest_integer(value: \"10\")\n/// 10\n/// >>> closest_integer(value: \"15.3\")\n/// 15\n/// Note:\n/// Rounding away from zero means that if the given number is equidistant\n/// from two integers, the one you should return is the one that is the\n/// farthest from zero. For example closest_integer(\"14.5\") should\n/// return 15 and closest_integer(\"-14.5\") should return -15.\nfunc closest_integer(value: String) -> Int {\n let number = Double(value)!\n let rounded = round(number)\n if rounded - number == 0.5 {\n return number > 0 ? Int(rounded + 0.5) : Int(rounded - 0.5)\n } else {\n return Int(rounded)\n }"], ["/// From a given array of integers, generate an array of rolling maximum element found until given moment\n/// in the sequence.\n/// >>> rolling_max(numbers: [1, 2, 3, 2, 3, 4, 2])\n/// [1, 2, 3, 3, 3, 4, 4]\nfunc rolling_max(numbers: [Int]) -> [Int] {\n var result = [Int]()\n var max = numbers[0]\n for number in numbers {\n if number > max {\n max = number\n }\n result.append(max)\n }\n return result"]] \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_humaneval_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_humaneval_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..c529121bc5fa4729b484e2c6adcad04f0f12588d --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_humaneval_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "humaneval": { + "pass@1": 0.7682926829268293 + }, + "config": { + "prefix": "human\n# language: Python\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "humaneval", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_humaneval_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_humaneval_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-cpp_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-cpp_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..2dcb12e2a48a041bac0757fa962788b54081ae99 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-cpp_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-cpp": { + "pass@1": 0.6521739130434783 + }, + "config": { + "prefix": "human\n// language: C++\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-cpp", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-cpp_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-cpp_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-d_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-d_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..24b54331c3479b72054302209ea46b5a34deb175 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-d_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-d": { + "pass@1": 0.24358974358974358 + }, + "config": { + "prefix": "human\n\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-d", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-d_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-d_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-java_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-java_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..fc005586386cce1325174de32ed09e4089a5f93b --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-java_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-java": { + "pass@1": 0.6075949367088608 + }, + "config": { + "prefix": "human\n// language: Java\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-java", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-java_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-java_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-jl_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-jl_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..f6397a14588b38fdbe9cb332d853100ee9115c9b --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-jl_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-jl": { + "pass@1": 0.3836477987421384 + }, + "config": { + "prefix": "human\n# language: Julia\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-jl", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-jl_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-jl_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-js_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-js_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..e1fddc08ddcf9d7136ff4b17561c11e9cf0fa260 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-js_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-js": { + "pass@1": 0.6645962732919255 + }, + "config": { + "prefix": "human\n// language: JavaScript\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-js", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-js_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-js_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-lua_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-lua_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..f5265598d0716f393675d34148b950c63c98d30d --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-lua_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-lua": { + "pass@1": 0.5279503105590062 + }, + "config": { + "prefix": "human\n// language: Lua\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-lua", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-lua_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-lua_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-php_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-php_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..c17a50213266d9ca2060a0e7b18b9391c4126f83 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-php_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-php": { + "pass@1": 0.577639751552795 + }, + "config": { + "prefix": "human\n// language: PHP\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-php", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-php_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-php_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-r_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-r_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..f9367651afada0b3d1534cb9279db33bf4e74f20 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-r_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-r": { + "pass@1": 0.40372670807453415 + }, + "config": { + "prefix": "human\n# language: R\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-r", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-r_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-r_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rkt_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rkt_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..8004d085fd6c88696ad870748e73be38da04858b --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rkt_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-rkt": { + "pass@1": 0.3416149068322981 + }, + "config": { + "prefix": "human\n; language: Racket\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-rkt", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-rkt_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-rkt_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rs_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rs_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..7787a6df7ccb4b9f09d144bf4a2c860017a43f1c --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-rs_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-rs": { + "pass@1": 0.5384615384615384 + }, + "config": { + "prefix": "human\n// language: Rust\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-rs", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-rs_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-rs_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-swift_CodeFuse-DeepSeek-33b.json b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-swift_CodeFuse-DeepSeek-33b.json new file mode 100644 index 0000000000000000000000000000000000000000..16737613c5efb7a51862ee8acd192ca3bdee4330 --- /dev/null +++ b/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/metrics_CodeFuse-DeepSeek-33b/metrics_multiple-swift_CodeFuse-DeepSeek-33b.json @@ -0,0 +1,44 @@ +{ + "multiple-swift": { + "pass@1": 0.4936708860759494 + }, + "config": { + "prefix": "human\n// language: Swift\n", + "suffix": "\nbot\n", + "add_special_tokens": false, + "do_sample": false, + "temperature": 0.2, + "top_k": 0, + "top_p": 0.95, + "n_samples": 1, + "eos": "<\uff5cend\u2581of\u2581sentence\uff5c>", + "seed": 999999999, + "model": "codefuse-ai/CodeFuse-DeepSeek-33B", + "modeltype": "causal", + "peft_model": null, + "revision": null, + "use_auth_token": true, + "trust_remote_code": true, + "tasks": "multiple-swift", + "instruction_tokens": null, + "batch_size": 1, + "max_length_generation": 2000, + "precision": "bf16", + "load_in_8bit": false, + "load_in_4bit": false, + "limit": null, + "limit_start": 0, + "postprocess": true, + "allow_code_execution": true, + "generation_only": false, + "load_generations_path": "/app/generations_multiple-swift_CodeFuse-DeepSeek-33B.json", + "load_data_path": null, + "metric_output_path": "/app/metrics_CodeFuse-DeepSeek-33B/metrics_multiple-swift_CodeFuse-DeepSeek-33B.json", + "save_generations": false, + "save_generations_path": "generations.json", + "save_references": false, + "prompt": "prompt", + "max_memory_per_gpu": null, + "check_references": false + } +} \ No newline at end of file diff --git a/data/code_eval_board.csv b/data/code_eval_board.csv index 79a213e4d0295542f8846d2ec9cbe8be9237e98c..ce4842c0fa525d1f326fd351f352d07d0fbb2bdd 100644 --- a/data/code_eval_board.csv +++ b/data/code_eval_board.csv @@ -1,42 +1,43 @@ -T,Models,Size (B),Win Rate,Throughput (tokens/s),Seq_length,#Languages,humaneval-python,java,javascript,cpp,php,julia,d,Average score,lua,r,racket,rust,swift,Throughput (tokens/s) bs=50,Peak Memory (MB),models_query,Links,Submission PR -🔴,DeepSeek-Coder-33b-instruct,33.0,39.58,25.2,16384,86,80.02,52.03,65.13,62.36,52.5,42.92,17.85,49.99,50.92,39.43,31.69,55.56,49.42,,76800.0,DeepSeek-Coder-33b-instruct,https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/42 -🔴,DeepSeek-Coder-7b-instruct,6.7,38.75,51.0,16384,86,80.22,53.34,65.8,59.66,59.4,38.84,21.59,48.17,47.78,38.56,20.87,47.73,44.22,,22922.0,DeepSeek-Coder-7b-instruct,https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-instruct,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/43 -🔶,Phind-CodeLlama-34B-v2,34.0,37.04,15.1,16384,UNK,71.95,54.06,65.34,59.59,56.26,45.12,14.12,48.7,44.27,37.7,28.7,57.67,49.63,0.0,69957.0,Phind-CodeLlama-34B-v2,https://huggingface.co/phind/Phind-CodeLlama-34B-v2, -🔶,Phind-CodeLlama-34B-v1,34.0,36.12,15.1,16384,UNK,65.85,49.47,64.45,57.81,55.53,43.23,15.5,46.9,42.05,36.71,24.89,54.1,53.27,0.0,69957.0,Phind-CodeLlama-34B-v1,https://huggingface.co/phind/Phind-CodeLlama-34B-v1, -🔶,Phind-CodeLlama-34B-Python-v1,34.0,35.27,15.1,16384,UNK,70.22,48.72,66.24,55.34,52.05,44.23,13.78,45.25,39.44,37.76,18.88,49.22,47.11,0.0,69957.0,Phind-CodeLlama-34B-Python-v1,https://huggingface.co/phind/Phind-CodeLlama-34B-Python-v1, +T,Model,Size (B),Win Rate,Throughput (tokens/s),Seq_length,#Languages,humaneval-python,java,javascript,cpp,php,julia,d,Average score,lua,r,racket,rust,swift,Throughput (tokens/s) bs=50,Peak Memory (MB),models_query,Links,Submission PR +🔴,CodeFuse-DeepSeek-33b,33.0,40.83,17.5,16384,86,76.83,60.76,66.46,65.22,57.76,38.36,24.36,51.69,52.8,40.37,34.16,53.85,49.37,,75833.0,CodeFuse-DeepSeek-33b,https://huggingface.co/codefuse-ai/CodeFuse-DeepSeek-33B,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/51 +🔴,DeepSeek-Coder-33b-instruct,33.0,39.83,25.2,16384,86,80.02,52.03,65.13,62.36,52.5,42.92,17.85,49.99,50.92,39.43,31.69,55.56,49.42,,76800.0,DeepSeek-Coder-33b-instruct,https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/42 +🔴,DeepSeek-Coder-7b-instruct,6.7,38.92,51.0,16384,86,80.22,53.34,65.8,59.66,59.4,38.84,21.59,48.17,47.78,38.56,20.87,47.73,44.22,,22922.0,DeepSeek-Coder-7b-instruct,https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-instruct,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/43 +🔶,Phind-CodeLlama-34B-v2,34.0,37.35,15.1,16384,UNK,71.95,54.06,65.34,59.59,56.26,45.12,14.12,48.7,44.27,37.7,28.7,57.67,49.63,0.0,69957.0,Phind-CodeLlama-34B-v2,https://huggingface.co/phind/Phind-CodeLlama-34B-v2, +🔶,Phind-CodeLlama-34B-v1,34.0,36.42,15.1,16384,UNK,65.85,49.47,64.45,57.81,55.53,43.23,15.5,46.9,42.05,36.71,24.89,54.1,53.27,0.0,69957.0,Phind-CodeLlama-34B-v1,https://huggingface.co/phind/Phind-CodeLlama-34B-v1, +🔶,Phind-CodeLlama-34B-Python-v1,34.0,35.42,15.1,16384,UNK,70.22,48.72,66.24,55.34,52.05,44.23,13.78,45.25,39.44,37.76,18.88,49.22,47.11,0.0,69957.0,Phind-CodeLlama-34B-Python-v1,https://huggingface.co/phind/Phind-CodeLlama-34B-Python-v1, 🔴,DeepSeek-Coder-33b-base,33.0,35.0,25.2,16384,86,52.45,43.77,51.28,51.22,41.76,32.83,17.41,38.07,36.51,26.76,23.37,43.78,35.75,,76800.0,DeepSeek-Coder-33b-base,https://huggingface.co/deepseek-ai/deepseek-coder-33b-base,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/31 -🔶,WizardCoder-Python-34B-V1.0,34.0,33.96,15.1,16384,UNK,70.73,44.94,55.28,47.2,47.2,41.51,15.38,41.95,32.3,39.75,18.63,46.15,44.3,0.0,69957.0,WizardCoder-Python-34B-V1.0,https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0, +🔶,WizardCoder-Python-34B-V1.0,34.0,34.12,15.1,16384,UNK,70.73,44.94,55.28,47.2,47.2,41.51,15.38,41.95,32.3,39.75,18.63,46.15,44.3,0.0,69957.0,WizardCoder-Python-34B-V1.0,https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0, 🔴,DeepSeek-Coder-7b-base,6.7,31.75,51.0,16384,86,45.83,37.72,45.9,45.53,36.92,28.74,19.74,33.54,33.89,28.99,18.73,34.67,25.8,,22922.0,DeepSeek-Coder-7b-base,https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/32 -🔶,CodeLlama-34b-Instruct,34.0,30.96,15.1,16384,UNK,50.79,41.53,45.85,41.53,36.98,32.65,13.63,35.09,38.87,24.25,18.09,39.26,37.63,0.0,69957.0,CodeLlama-34b-Instruct,https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf, -🔶,WizardCoder-Python-13B-V1.0,13.0,30.58,25.3,16384,UNK,62.19,41.77,48.45,42.86,42.24,38.99,11.54,35.94,32.92,27.33,16.15,34.62,32.28,0.0,28568.0,WizardCoder-Python-13B-V1.0,https://huggingface.co/WizardLM/WizardCoder-Python-13B-V1.0, -🟢,CodeLlama-34b,34.0,30.35,15.1,16384,UNK,45.11,40.19,41.66,41.42,40.43,31.4,15.27,33.89,37.49,22.71,16.94,38.73,35.28,0.0,69957.0,CodeLlama-34b,https://huggingface.co/codellama/CodeLlama-34b-hf, -🟢,CodeLlama-34b-Python,34.0,29.65,15.1,16384,UNK,53.29,39.46,44.72,39.09,39.78,31.37,17.29,33.87,31.9,22.35,13.19,39.67,34.3,0.0,69957.0,CodeLlama-34b-Python,https://huggingface.co/codellama/CodeLlama-34b-Python-hf, -🔶,WizardCoder-15B-V1.0,15.0,28.92,43.7,8192,86,58.12,35.77,41.91,38.95,39.34,33.98,12.14,32.07,27.85,22.53,13.39,33.74,27.06,1470.0,32414.0,WizardCoder-15B-V1.0,https://huggingface.co/WizardLM/WizardCoder-15B-V1.0, -🔶,CodeLlama-13b-Instruct,13.0,27.88,25.3,16384,UNK,50.6,33.99,40.92,36.36,32.07,32.23,16.29,31.29,31.6,20.14,16.66,32.82,31.75,0.0,28568.0,CodeLlama-13b-Instruct,https://huggingface.co/codellama/CodeLlama-13b-Instruct-hf, -🟢,CodeLlama-13b,13.0,26.19,25.3,16384,UNK,35.07,32.23,38.26,35.81,32.57,28.01,15.78,28.35,31.26,18.32,13.63,29.72,29.54,0.0,28568.0,CodeLlama-13b,https://huggingface.co/codellama/CodeLlama-13b-hf, -🟢,CodeLlama-13b-Python,13.0,24.73,25.3,16384,UNK,42.89,33.56,40.66,36.21,34.55,30.4,9.82,28.67,29.9,18.35,12.51,29.32,25.85,0.0,28568.0,CodeLlama-13b-Python,https://huggingface.co/codellama/CodeLlama-13b-Python-hf, -🔶,CodeLlama-7b-Instruct,7.0,23.69,33.1,16384,UNK,45.65,28.77,33.11,29.03,28.55,27.58,11.81,26.45,30.47,19.7,11.81,24.27,26.66,693.0,15853.0,CodeLlama-7b-Instruct,https://huggingface.co/codellama/CodeLlama-7b-Instruct-hf, -🟢,CodeLlama-7b,7.0,22.31,33.1,16384,UNK,29.98,29.2,31.8,27.23,25.17,25.6,11.6,24.36,30.36,18.04,11.94,25.82,25.52,693.0,15853.0,CodeLlama-7b,https://huggingface.co/codellama/CodeLlama-7b-hf, -🔴,CodeShell-7B,7.0,22.31,33.9,8194,24,34.32,30.43,33.17,28.21,30.87,22.08,8.85,24.74,22.39,20.52,17.2,24.55,24.3,639.0,18511.0,CodeShell-7B,https://huggingface.co/WisdomShell/CodeShell-7B,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/16 -🔶,OctoCoder-15B,15.0,21.15,44.4,8192,86,45.3,26.03,32.8,29.32,26.76,24.5,13.35,24.01,22.56,14.39,10.61,24.26,18.24,1520.0,32278.0,OctoCoder-15B,https://huggingface.co/bigcode/octocoder, +🔶,CodeLlama-34b-Instruct,34.0,31.04,15.1,16384,UNK,50.79,41.53,45.85,41.53,36.98,32.65,13.63,35.09,38.87,24.25,18.09,39.26,37.63,0.0,69957.0,CodeLlama-34b-Instruct,https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf, +🔶,WizardCoder-Python-13B-V1.0,13.0,30.73,25.3,16384,UNK,62.19,41.77,48.45,42.86,42.24,38.99,11.54,35.94,32.92,27.33,16.15,34.62,32.28,0.0,28568.0,WizardCoder-Python-13B-V1.0,https://huggingface.co/WizardLM/WizardCoder-Python-13B-V1.0, +🟢,CodeLlama-34b,34.0,30.42,15.1,16384,UNK,45.11,40.19,41.66,41.42,40.43,31.4,15.27,33.89,37.49,22.71,16.94,38.73,35.28,0.0,69957.0,CodeLlama-34b,https://huggingface.co/codellama/CodeLlama-34b-hf, +🟢,CodeLlama-34b-Python,34.0,29.73,15.1,16384,UNK,53.29,39.46,44.72,39.09,39.78,31.37,17.29,33.87,31.9,22.35,13.19,39.67,34.3,0.0,69957.0,CodeLlama-34b-Python,https://huggingface.co/codellama/CodeLlama-34b-Python-hf, +🔶,WizardCoder-15B-V1.0,15.0,29.0,43.7,8192,86,58.12,35.77,41.91,38.95,39.34,33.98,12.14,32.07,27.85,22.53,13.39,33.74,27.06,1470.0,32414.0,WizardCoder-15B-V1.0,https://huggingface.co/WizardLM/WizardCoder-15B-V1.0, +🔶,CodeLlama-13b-Instruct,13.0,27.96,25.3,16384,UNK,50.6,33.99,40.92,36.36,32.07,32.23,16.29,31.29,31.6,20.14,16.66,32.82,31.75,0.0,28568.0,CodeLlama-13b-Instruct,https://huggingface.co/codellama/CodeLlama-13b-Instruct-hf, +🟢,CodeLlama-13b,13.0,26.27,25.3,16384,UNK,35.07,32.23,38.26,35.81,32.57,28.01,15.78,28.35,31.26,18.32,13.63,29.72,29.54,0.0,28568.0,CodeLlama-13b,https://huggingface.co/codellama/CodeLlama-13b-hf, +🟢,CodeLlama-13b-Python,13.0,24.81,25.3,16384,UNK,42.89,33.56,40.66,36.21,34.55,30.4,9.82,28.67,29.9,18.35,12.51,29.32,25.85,0.0,28568.0,CodeLlama-13b-Python,https://huggingface.co/codellama/CodeLlama-13b-Python-hf, +🔶,CodeLlama-7b-Instruct,7.0,23.77,33.1,16384,UNK,45.65,28.77,33.11,29.03,28.55,27.58,11.81,26.45,30.47,19.7,11.81,24.27,26.66,693.0,15853.0,CodeLlama-7b-Instruct,https://huggingface.co/codellama/CodeLlama-7b-Instruct-hf, +🔴,CodeShell-7B,7.0,22.38,33.9,8194,24,34.32,30.43,33.17,28.21,30.87,22.08,8.85,24.74,22.39,20.52,17.2,24.55,24.3,639.0,18511.0,CodeShell-7B,https://huggingface.co/WisdomShell/CodeShell-7B,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/16 +🟢,CodeLlama-7b,7.0,22.38,33.1,16384,UNK,29.98,29.2,31.8,27.23,25.17,25.6,11.6,24.36,30.36,18.04,11.94,25.82,25.52,693.0,15853.0,CodeLlama-7b,https://huggingface.co/codellama/CodeLlama-7b-hf, +🔶,OctoCoder-15B,15.0,21.23,44.4,8192,86,45.3,26.03,32.8,29.32,26.76,24.5,13.35,24.01,22.56,14.39,10.61,24.26,18.24,1520.0,32278.0,OctoCoder-15B,https://huggingface.co/bigcode/octocoder, 🟢,Falcon-180B,180.0,20.9,,2048,,35.37,28.48,31.68,28.57,,24.53,14.1,24.08,26.71,,10.56,25.0,15.82,,,Falcon-180B,https://huggingface.co/tiiuae/falcon-180B, -🟢,CodeLlama-7b-Python,7.0,20.62,33.1,16384,UNK,40.48,29.15,36.34,30.34,1.08,28.53,8.94,23.5,26.15,18.25,9.04,26.96,26.75,693.0,15853.0,CodeLlama-7b-Python,https://huggingface.co/codellama/CodeLlama-7b-Python-hf, -🟢,StarCoder-15B,15.0,20.58,43.9,8192,86,33.57,30.22,30.79,31.55,26.08,23.02,13.57,22.74,23.89,15.5,0.07,21.84,22.74,1490.0,33461.0,StarCoder-15B,https://huggingface.co/bigcode/starcoder, -🟢,StarCoderBase-15B,15.0,20.15,43.8,8192,86,30.35,28.53,31.7,30.56,26.75,21.09,10.01,22.4,26.61,10.18,11.77,24.46,16.74,1460.0,32366.0,StarCoderBase-15B,https://huggingface.co/bigcode/starcoderbase, -🟢,CodeGeex2-6B,6.0,17.42,32.7,8192,100,33.49,23.46,29.9,28.45,25.27,20.93,8.44,21.23,15.94,14.58,11.75,20.45,22.06,982.0,14110.0,CodeGeex2-6B,https://huggingface.co/THUDM/codegeex2-6b, -🟢,StarCoderBase-7B,7.0,16.85,46.9,8192,86,28.37,24.44,27.35,23.3,22.12,21.77,8.1,20.17,23.35,14.51,11.08,22.6,15.1,1700.0,16512.0,StarCoderBase-7B,https://huggingface.co/bigcode/starcoderbase-7b, -🔶,OctoGeeX-7B,7.0,16.65,32.7,8192,100,42.28,19.33,28.5,23.93,25.85,22.94,9.77,20.79,16.19,13.66,12.02,17.94,17.03,982.0,14110.0,OctoGeeX-7B,https://huggingface.co/bigcode/octogeex, -🔶,WizardCoder-3B-V1.0,3.0,15.73,50.0,8192,86,32.92,24.34,26.16,24.94,24.83,19.6,7.91,20.15,21.75,13.64,9.44,20.56,15.7,1770.0,8414.0,WizardCoder-3B-V1.0,https://huggingface.co/WizardLM/WizardCoder-3B-V1.0, -🟢,CodeGen25-7B-multi,7.0,15.35,32.6,2048,86,28.7,26.01,26.27,25.75,21.98,19.11,8.84,20.04,23.44,11.59,10.37,21.84,16.62,680.0,15336.0,CodeGen25-7B-multi,https://huggingface.co/Salesforce/codegen25-7b-multi, -🔶,Refact-1.6B,1.6,14.85,50.0,4096,19,31.1,22.78,22.36,21.12,22.36,13.84,10.26,17.86,15.53,13.04,4.97,18.59,18.35,2340.0,5376.0,Refact-1.6B,https://huggingface.co/smallcloudai/Refact-1_6B-fim, +🟢,CodeLlama-7b-Python,7.0,20.69,33.1,16384,UNK,40.48,29.15,36.34,30.34,1.08,28.53,8.94,23.5,26.15,18.25,9.04,26.96,26.75,693.0,15853.0,CodeLlama-7b-Python,https://huggingface.co/codellama/CodeLlama-7b-Python-hf, +🟢,StarCoder-15B,15.0,20.65,43.9,8192,86,33.57,30.22,30.79,31.55,26.08,23.02,13.57,22.74,23.89,15.5,0.07,21.84,22.74,1490.0,33461.0,StarCoder-15B,https://huggingface.co/bigcode/starcoder, +🟢,StarCoderBase-15B,15.0,20.23,43.8,8192,86,30.35,28.53,31.7,30.56,26.75,21.09,10.01,22.4,26.61,10.18,11.77,24.46,16.74,1460.0,32366.0,StarCoderBase-15B,https://huggingface.co/bigcode/starcoderbase, +🟢,CodeGeex2-6B,6.0,17.5,32.7,8192,100,33.49,23.46,29.9,28.45,25.27,20.93,8.44,21.23,15.94,14.58,11.75,20.45,22.06,982.0,14110.0,CodeGeex2-6B,https://huggingface.co/THUDM/codegeex2-6b, +🟢,StarCoderBase-7B,7.0,16.92,46.9,8192,86,28.37,24.44,27.35,23.3,22.12,21.77,8.1,20.17,23.35,14.51,11.08,22.6,15.1,1700.0,16512.0,StarCoderBase-7B,https://huggingface.co/bigcode/starcoderbase-7b, +🔶,OctoGeeX-7B,7.0,16.73,32.7,8192,100,42.28,19.33,28.5,23.93,25.85,22.94,9.77,20.79,16.19,13.66,12.02,17.94,17.03,982.0,14110.0,OctoGeeX-7B,https://huggingface.co/bigcode/octogeex, +🔶,WizardCoder-3B-V1.0,3.0,15.81,50.0,8192,86,32.92,24.34,26.16,24.94,24.83,19.6,7.91,20.15,21.75,13.64,9.44,20.56,15.7,1770.0,8414.0,WizardCoder-3B-V1.0,https://huggingface.co/WizardLM/WizardCoder-3B-V1.0, +🟢,CodeGen25-7B-multi,7.0,15.42,32.6,2048,86,28.7,26.01,26.27,25.75,21.98,19.11,8.84,20.04,23.44,11.59,10.37,21.84,16.62,680.0,15336.0,CodeGen25-7B-multi,https://huggingface.co/Salesforce/codegen25-7b-multi, +🔶,Refact-1.6B,1.6,14.92,50.0,4096,19,31.1,22.78,22.36,21.12,22.36,13.84,10.26,17.86,15.53,13.04,4.97,18.59,18.35,2340.0,5376.0,Refact-1.6B,https://huggingface.co/smallcloudai/Refact-1_6B-fim, 🔴,DeepSeek-Coder-1b-base,1.0,14.42,,16384,UNK,32.13,27.16,28.46,27.96,22.75,15.17,9.91,19.46,19.44,11.4,9.58,18.13,11.39,,,DeepSeek-Coder-1b-base,https://huggingface.co/deepseek-ai/deepseek-coder-1.3b-base,https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/33 -🟢,StarCoderBase-3B,3.0,11.65,50.0,8192,86,21.5,19.25,21.32,19.43,18.55,16.1,4.97,15.29,18.04,10.1,7.87,16.32,9.98,1770.0,8414.0,StarCoderBase-3B,https://huggingface.co/bigcode/starcoderbase-3b, -🔶,WizardCoder-1B-V1.0,1.1,10.35,71.4,8192,86,23.17,19.68,19.13,15.94,14.71,13.85,4.64,13.89,15.52,10.01,6.51,13.91,9.59,2360.0,4586.0,WizardCoder-1B-V1.0,https://huggingface.co/WizardLM/WizardCoder-1B-V1.0, -🟢,Replit-2.7B,2.7,8.54,42.2,2048,20,20.12,21.39,20.18,20.37,16.14,1.24,6.41,11.62,2.11,7.2,3.22,15.19,5.88,577.0,7176.0,Replit-2.7B,https://huggingface.co/replit/replit-code-v1-3b, -🟢,CodeGen25-7B-mono,7.0,8.15,34.1,2048,86,33.08,19.75,23.22,18.62,16.75,4.65,4.32,12.1,6.75,4.41,4.07,7.83,1.71,687.0,15336.0,CodeGen25-7B-mono,https://huggingface.co/Salesforce/codegen25-7b-mono, -🟢,StarCoderBase-1.1B,1.1,8.12,71.4,8192,86,15.17,14.2,13.38,11.68,9.94,11.31,4.65,9.81,12.52,5.73,5.03,10.24,3.92,2360.0,4586.0,StarCoderBase-1.1B,https://huggingface.co/bigcode/starcoderbase-1b, -🟢,CodeGen-16B-Multi,16.0,7.08,17.2,2048,6,19.26,22.2,19.15,21.0,8.37,0.0,7.68,9.89,8.5,6.45,0.66,4.21,1.25,0.0,32890.0,CodeGen-16B-Multi,https://huggingface.co/Salesforce/codegen-16B-multi, +🟢,StarCoderBase-3B,3.0,11.73,50.0,8192,86,21.5,19.25,21.32,19.43,18.55,16.1,4.97,15.29,18.04,10.1,7.87,16.32,9.98,1770.0,8414.0,StarCoderBase-3B,https://huggingface.co/bigcode/starcoderbase-3b, +🔶,WizardCoder-1B-V1.0,1.1,10.42,71.4,8192,86,23.17,19.68,19.13,15.94,14.71,13.85,4.64,13.89,15.52,10.01,6.51,13.91,9.59,2360.0,4586.0,WizardCoder-1B-V1.0,https://huggingface.co/WizardLM/WizardCoder-1B-V1.0, +🟢,Replit-2.7B,2.7,8.62,42.2,2048,20,20.12,21.39,20.18,20.37,16.14,1.24,6.41,11.62,2.11,7.2,3.22,15.19,5.88,577.0,7176.0,Replit-2.7B,https://huggingface.co/replit/replit-code-v1-3b, +🟢,CodeGen25-7B-mono,7.0,8.23,34.1,2048,86,33.08,19.75,23.22,18.62,16.75,4.65,4.32,12.1,6.75,4.41,4.07,7.83,1.71,687.0,15336.0,CodeGen25-7B-mono,https://huggingface.co/Salesforce/codegen25-7b-mono, +🟢,StarCoderBase-1.1B,1.1,8.19,71.4,8192,86,15.17,14.2,13.38,11.68,9.94,11.31,4.65,9.81,12.52,5.73,5.03,10.24,3.92,2360.0,4586.0,StarCoderBase-1.1B,https://huggingface.co/bigcode/starcoderbase-1b, +🟢,CodeGen-16B-Multi,16.0,7.15,17.2,2048,6,19.26,22.2,19.15,21.0,8.37,0.0,7.68,9.89,8.5,6.45,0.66,4.21,1.25,0.0,32890.0,CodeGen-16B-Multi,https://huggingface.co/Salesforce/codegen-16B-multi, 🟢,Phi-1,1.0,6.25,,2048,1,51.22,10.76,19.25,14.29,12.42,0.63,7.05,12.15,6.21,6.21,3.11,4.49,10.13,,4941.0,Phi-1,https://huggingface.co/microsoft/phi-1, -🟢,StableCode-3B,3.0,6.04,30.2,16384,7,20.2,19.54,18.98,20.77,3.95,0.0,4.77,8.1,5.14,0.8,0.008,2.03,0.98,718.0,15730.0,StableCode-3B,https://huggingface.co/stabilityai/stablecode-completion-alpha-3b, -🟢,DeciCoder-1B,1.0,5.81,54.6,2048,3,19.32,15.3,17.85,6.87,2.01,0.0,6.08,5.86,0.0,0.1,0.47,1.72,0.63,2490.0,4436.0,DeciCoder-1B,https://huggingface.co/Deci/DeciCoder-1b, -🟢,SantaCoder-1.1B,1.1,4.58,50.8,2048,3,18.12,15.0,15.47,6.2,1.5,0.0,0.0,4.92,0.1,0.0,0.0,2.0,0.7,2270.0,4602.0,SantaCoder-1.1B,https://huggingface.co/bigcode/santacoder, +🟢,StableCode-3B,3.0,6.12,30.2,16384,7,20.2,19.54,18.98,20.77,3.95,0.0,4.77,8.1,5.14,0.8,0.008,2.03,0.98,718.0,15730.0,StableCode-3B,https://huggingface.co/stabilityai/stablecode-completion-alpha-3b, +🟢,DeciCoder-1B,1.0,5.88,54.6,2048,3,19.32,15.3,17.85,6.87,2.01,0.0,6.08,5.86,0.0,0.1,0.47,1.72,0.63,2490.0,4436.0,DeciCoder-1B,https://huggingface.co/Deci/DeciCoder-1b, +🟢,SantaCoder-1.1B,1.1,4.65,50.8,2048,3,18.12,15.0,15.47,6.2,1.5,0.0,0.0,4.92,0.1,0.0,0.0,2.0,0.7,2270.0,4602.0,SantaCoder-1.1B,https://huggingface.co/bigcode/santacoder, diff --git a/data/raw_scores.csv b/data/raw_scores.csv index 20d16214d94ca890fbff343e0ac38a25a38086e0..70e5bd13532def956d82d47fde685133e5769838 100644 --- a/data/raw_scores.csv +++ b/data/raw_scores.csv @@ -1,4 +1,4 @@ -Models,Size (B),Throughput (tokens/s),Seq_length,#Languages,humaneval-python,java,javascript,cpp,php,julia,d,lua,r,racket,rust,swift,Throughput (tokens/s) bs=50,Peak Memory (MB) +Model,Size (B),Throughput (tokens/s),Seq_length,#Languages,humaneval-python,java,javascript,cpp,php,julia,d,lua,r,racket,rust,swift,Throughput (tokens/s) bs=50,Peak Memory (MB) CodeGen-16B-Multi,16.0,17.2,2048,6,19.26,22.2,19.15,21.0,8.37,0.0,7.68,8.5,6.45,0.66,4.21,1.25,0.0,32890 StarCoder-15B,15.0,43.9,8192,86,33.57,30.22,30.79,31.55,26.08,23.02,13.57,23.89,15.5,0.07,21.84,22.74,1490.0,33461 StarCoderBase-15B,15.0,43.8,8192,86,30.35,28.53,31.7,30.56,26.75,21.09,10.01,26.61,10.18,11.77,24.46,16.74,1460.0,32366 @@ -40,3 +40,4 @@ DeepSeek-Coder-7b-base,6.7,51.0,16384,86,45.83,37.72,45.9,45.53,36.92,28.74,19.7 DeepSeek-Coder-33b-base,33,25.2,16384,86,52.45,43.77,51.28,51.22,41.76,32.83,17.41,36.51,26.76,23.37,43.78,35.75,,76800 DeepSeek-Coder-7b-instruct,6.7,51.0,16384,86,80.22,53.34,65.8,59.66,59.4,38.84,21.59,47.78,38.56,20.87,47.73,44.22,,22922 DeepSeek-Coder-33b-instruct,33,25.2,16384,86,80.02,52.03,65.13,62.36,52.5,42.92,17.85,50.92,39.43,31.69,55.56,49.42,,76800 +CodeFuse-DeepSeek-33b,33,17.5,16384,86,76.83,60.76,66.46,65.22,57.76,38.36,24.36,52.8,40.37,34.16,53.85,49.37,,75833 diff --git a/src/add_json_csv.py b/src/add_json_csv.py index 14e52f10649d1eda9fbbdcb43c1542ba3eb1318c..abfd8e0e34bd8eb5a8f81f49065b8d9abfe0dc7d 100644 --- a/src/add_json_csv.py +++ b/src/add_json_csv.py @@ -16,9 +16,10 @@ mapping = { "multiple-d": "d", "multiple-swift": "swift" } -BASE_PATH = "/fsx/loubna/pr/bigcode-models-leaderboard" +BASE_PATH = "/fsx/loubna/projects/bigcode-models-leaderboard" # JSON Data (replace this with your actual loaded JSON) -json_path = f"{BASE_PATH}/community_results/deepseek-ai_deepseek-coder-33b-instruct_zqh11/deepseek-ai_deepseek-coder-33b-instruct_zqh11.json" + +json_path = f"{BASE_PATH}/community_results/codefuse-ai_codefuse-deepseek-33b_codefuse-admin/codefuse-ai_CodeFuse-DeepSeek-33b_codefuse-admin.json" with open(json_path, "r") as f: json_data = json.load(f) parsed_data = json_data['results'] diff --git a/src/build.py b/src/build.py index 6e0db4c4904e4b31bef07434aeb0cb0509152434..b142c91cc051fcee2ecda9f27b072ef2f8289be5 100644 --- a/src/build.py +++ b/src/build.py @@ -23,7 +23,7 @@ def add_model_readme(df): df = pd.read_csv("data/raw_scores.csv") COLS = df.columns.to_list() # add column models_query with same values a smodels at the end of columns -df.insert(len(COLS), "models_query", df["Models"]) +df.insert(len(COLS), "models_query", df["Model"]) print(f"all cols {df.columns.to_list()}") # average score mean_columns = df.iloc[:,5:-3] @@ -39,7 +39,7 @@ for col in df.columns[6:-2]: df[col + " rank"] = len(df) - (df[col + " rank"] - 1) df["Win Rate"] = df.iloc[:, old_size:].mean(axis=1).round(2) df = df.drop(df.columns[old_size:-1], axis=1) -df = df[["Models", "Size (B)", "Win Rate"] + df.columns[2:-1].tolist()] +df = df[["Model", "Size (B)", "Win Rate"] + df.columns[2:-1].tolist()] # sort with regard to column win rate df = df.sort_values(by=["Win Rate"], ascending=False) @@ -79,27 +79,29 @@ links = { "DeepSeek-Coder-33b-base": "https://huggingface.co/deepseek-ai/deepseek-coder-33b-base", "DeepSeek-Coder-7b-instruct": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-instruct", "DeepSeek-Coder-33b-instruct": "https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct", + "CodeFuse-DeepSeek-33b": "https://huggingface.co/codefuse-ai/CodeFuse-DeepSeek-33B", } codellamas = ['CodeLlama-7b', 'CodeLlama-7b-Python', 'CodeLlama-7b-Instruct', 'CodeLlama-13b', 'CodeLlama-13b-Python', 'CodeLlama-13b-Instruct', 'CodeLlama-34b', 'CodeLlama-34b-Python', 'CodeLlama-34b-Instruct'] for codellama in codellamas: links[codellama] = f"https://huggingface.co/codellama/{codellama}-hf" -df["Links"] = df["Models"].map(links) +df["Links"] = df["Model"].map(links) df.insert(0, "T", "🟢") patterns = ["WizardCoder", "Octo", "Instruct", "Phind", "Refact"] -df.loc[df["Models"].str.contains('|'.join(patterns)), "T"] = "🔶" -df.loc[df["Models"].str.contains('|'.join(patterns)), "T"] = "🔶" -df.loc[df["Models"].str.contains('|'.join(["CodeShell", "DeepSeek"])), "T"] = "🔴" +df.loc[df["Model"].str.contains('|'.join(patterns)), "T"] = "🔶" +df.loc[df["Model"].str.contains('|'.join(patterns)), "T"] = "🔶" +df.loc[df["Model"].str.contains('|'.join(["CodeShell", "DeepSeek", "CodeFuse"])), "T"] = "🔴" # add clumn submission_pr with empty fiels except for CodeShell with link AA df["Submission PR"] = "" -df.loc[df["Models"].str.contains('|'.join(["CodeShell"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/16" -df.loc[df["Models"].str.contains('|'.join(["DeepSeek-Coder-1b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/33" -df.loc[df["Models"].str.contains('|'.join(["DeepSeek-Coder-7b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/32" -df.loc[df["Models"].str.contains('|'.join(["DeepSeek-Coder-33b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/31" -df.loc[df["Models"].str.contains('|'.join(["DeepSeek-Coder-7b-instruct"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/43" -df.loc[df["Models"].str.contains('|'.join(["DeepSeek-Coder-33b-instruct"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/42" +df.loc[df["Model"].str.contains('|'.join(["CodeShell"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/16" +df.loc[df["Model"].str.contains('|'.join(["DeepSeek-Coder-1b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/33" +df.loc[df["Model"].str.contains('|'.join(["DeepSeek-Coder-7b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/32" +df.loc[df["Model"].str.contains('|'.join(["DeepSeek-Coder-33b-base"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/31" +df.loc[df["Model"].str.contains('|'.join(["DeepSeek-Coder-7b-instruct"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/43" +df.loc[df["Model"].str.contains('|'.join(["DeepSeek-Coder-33b-instruct"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/42" +df.loc[df["Model"].str.contains('|'.join(["CodeFuse"])), "Submission PR"] = "https://huggingface.co/spaces/bigcode/bigcode-models-leaderboard/discussions/51" # print first 5 rows and 10 cols diff --git a/src/utils.py b/src/utils.py index 71021e33285dedbbf2fbe114a4c66f69f292e015..0807ebc2ba7bcff9389c5cebf8c8a65aa5ce7bb0 100644 --- a/src/utils.py +++ b/src/utils.py @@ -22,7 +22,7 @@ def fields(raw_class): @dataclass(frozen=True) class AutoEvalColumn: # Auto evals column model_type_symbol = ColumnContent("T", "str", True) - model = ColumnContent("Models", "markdown", True) + model = ColumnContent("Model", "markdown", True) win_rate = ColumnContent("Win Rate", "number", True) average = ColumnContent("Average score", "number", False) humaneval_python = ColumnContent("humaneval-python", "number", True) @@ -43,8 +43,8 @@ class AutoEvalColumn: # Auto evals column peak_memory = ColumnContent("Peak Memory (MB)", "number", False) seq_length = ColumnContent("Seq_length", "number", False) link = ColumnContent("Links", "str", False) - dummy = ColumnContent("Models", "str", True) - pr = ColumnContent("Submission PR", "str", False) + dummy = ColumnContent("Model", "str", True) + pr = ColumnContent("Submission PR", "markdown", False) def model_hyperlink(link, model_name): @@ -52,8 +52,8 @@ def model_hyperlink(link, model_name): def make_clickable_names(df): - df["Models"] = df.apply( - lambda row: model_hyperlink(row["Links"], row["Models"]), axis=1 + df["Model"] = df.apply( + lambda row: model_hyperlink(row["Links"], row["Model"]), axis=1 ) return df @@ -65,24 +65,25 @@ def plot_throughput(df, bs=1): df["symbol"] = 2 # Triangle df["color"] = "" - df.loc[df["Models"].str.contains("StarCoder|SantaCoder"), "color"] = "orange" - df.loc[df["Models"].str.contains("CodeGen"), "color"] = "pink" - df.loc[df["Models"].str.contains("Replit"), "color"] = "purple" - df.loc[df["Models"].str.contains("WizardCoder"), "color"] = "peru" - df.loc[df["Models"].str.contains("CodeGeex"), "color"] = "cornflowerblue" - df.loc[df["Models"].str.contains("StableCode"), "color"] = "cadetblue" - df.loc[df["Models"].str.contains("OctoCoder"), "color"] = "lime" - df.loc[df["Models"].str.contains("OctoGeeX"), "color"] = "wheat" - df.loc[df["Models"].str.contains("Deci"), "color"] = "salmon" - df.loc[df["Models"].str.contains("CodeLlama"), "color"] = "palevioletred" - df.loc[df["Models"].str.contains("CodeGuru"), "color"] = "burlywood" - df.loc[df["Models"].str.contains("Phind"), "color"] = "crimson" - df.loc[df["Models"].str.contains("Falcon"), "color"] = "dimgray" - df.loc[df["Models"].str.contains("Refact"), "color"] = "yellow" - df.loc[df["Models"].str.contains("Phi"), "color"] = "gray" - df.loc[df["Models"].str.contains("CodeShell"), "color"] = "lightskyblue" - df.loc[df["Models"].str.contains("CodeShell"), "color"] = "lightskyblue" - df.loc[df["Models"].str.contains("DeepSeek"), "color"] = "lightgreen" + df.loc[df["Model"].str.contains("StarCoder|SantaCoder"), "color"] = "orange" + df.loc[df["Model"].str.contains("CodeGen"), "color"] = "pink" + df.loc[df["Model"].str.contains("Replit"), "color"] = "purple" + df.loc[df["Model"].str.contains("WizardCoder"), "color"] = "peru" + df.loc[df["Model"].str.contains("CodeGeex"), "color"] = "cornflowerblue" + df.loc[df["Model"].str.contains("StableCode"), "color"] = "cadetblue" + df.loc[df["Model"].str.contains("OctoCoder"), "color"] = "lime" + df.loc[df["Model"].str.contains("OctoGeeX"), "color"] = "wheat" + df.loc[df["Model"].str.contains("Deci"), "color"] = "salmon" + df.loc[df["Model"].str.contains("CodeLlama"), "color"] = "palevioletred" + df.loc[df["Model"].str.contains("CodeGuru"), "color"] = "burlywood" + df.loc[df["Model"].str.contains("Phind"), "color"] = "crimson" + df.loc[df["Model"].str.contains("Falcon"), "color"] = "dimgray" + df.loc[df["Model"].str.contains("Refact"), "color"] = "yellow" + df.loc[df["Model"].str.contains("Phi"), "color"] = "gray" + df.loc[df["Model"].str.contains("CodeShell"), "color"] = "lightskyblue" + df.loc[df["Model"].str.contains("CodeShell"), "color"] = "lightskyblue" + df.loc[df["Model"].str.contains("DeepSeek"), "color"] = "lightgreen" + df.loc[df["Model"].str.contains("CodeFuse"), "color"] = "olive" fig = go.Figure() for i in df.index: @@ -96,7 +97,7 @@ def plot_throughput(df, bs=1): color=df.loc[i, "color"], symbol=df.loc[i, "symbol"], ), - name=df.loc[i, "Models"], + name=df.loc[i, "Model"], hovertemplate="%{text}

" + f"{throughput_column}: %{{x}}
" + "Average Score: %{y}
" @@ -105,7 +106,7 @@ def plot_throughput(df, bs=1): + "
" + "Human Eval (Python): " + str(df.loc[i, "humaneval-python"]), - text=[df.loc[i, "Models"]], + text=[df.loc[i, "Model"]], showlegend=True, ) )