prompt
stringlengths
96
1.46k
canonical_solution
stringlengths
16
1.4k
lang
stringclasses
5 values
source
stringclasses
1 value
/* For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sumProduct([]) (0, 1) >>> sumProduct([1, 2, 3, 4]) (10, 24) */ const sumProduct = (numbers, int) => {
var sum_value = 0, prod_value = 1; for (const n of numbers) { sum_value += n; prod_value *= n; } return [sum_value, prod_value]; }
javascript
THUDM/humaneval-x
/* From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rollingMax([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] */ const rollingMax = (numbers) => {
var running_max, result = []; for (const n of numbers) { if (running_max == undefined) running_max = n; else running_max = Math.max(running_max, n); result.push(running_max); } return result; }
javascript
THUDM/humaneval-x
/* Test if gniven strig is a palindrome */ const isPalindrome = (string) => { return string == string.split('').reverse().join(''); } /* Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> makePalindrome('') '' >>> makePalindrome('cat') 'catac' >>> makePalindrome('cata') 'catac' */ const makePalindrome = (string) => {
if (string == '') return ''; var beginning_of_suffix = 0; while (!isPalindrome(string.slice(beginning_of_suffix))) beginning_of_suffix += 1; return string + string.slice(0, beginning_of_suffix).split('').reverse().join(''); }
javascript
THUDM/humaneval-x
/* Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> stringXor('010', '110') '100' */ const stringXor = (a, b) => {
var xor = function (i, j) { if (i == j) return '0'; else return '1'; } return a.split('').map((item, index) => xor(item, b[index])).join(''); }
javascript
THUDM/humaneval-x
/* Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return null in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' */ const longest = (strings) => {
if (!Array.isArray(strings) || strings.length == 0) return null; var maxlen = Math.max(...strings.map(x => x.length)); for (const s of strings) { if (s.length == maxlen) { return s; } } }
javascript
THUDM/humaneval-x
/* Return a greatest common divisor of two integers a and b >>> greatestCommonDivisor(3, 5) 1 >>> greatestCommonDivisor(25, 15) 5 */ const greatestCommonDivisor = (a, b) => {
while (b != 0) { let temp = a; a = b; b = temp % b; } return a; }
javascript
THUDM/humaneval-x
/* Return list of all prefixes from shortest to longest of the input string >>> allPrefixes('abc') ['a', 'ab', 'abc'] */ const allPrefixes = (string) => {
var result = []; for (let i = 0; i < string.length; i++) { result.push(string.slice(0, i+1)); } return result; }
javascript
THUDM/humaneval-x
/* Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> stringSequence(0) '0' >>> stringSequence(5) '0 1 2 3 4 5' */ const stringSequence = (n) => {
return [...Array(n).keys(), n].join(' ') }
javascript
THUDM/humaneval-x
/* Given a string, find out how many distinct characters (regardless of case) does it consist of >>> countDistinctCharacters('xyzXYZ') 3 >>> countDistinctCharacters('Jerry') 4 */ const countDistinctCharacters = (string) => {
return (new Set(string.toLowerCase())).size; }
javascript
THUDM/humaneval-x
/* Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parseMusic('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] */ const parseMusic = (music_string) => {
const note_map = {'o': 4, 'o|': 2, '.|': 1}; return music_string.split(' ').filter(x => x != '').map(x => note_map[x]); }
javascript
THUDM/humaneval-x
/* Find how many times a given substring can be found in the original string. Count overlaping cases. >>> howManyTimes('', 'a') 0 >>> howManyTimes('aaa', 'a') 3 >>> howManyTimes('aaaa', 'aa') 3 */ const howManyTimes = (string, substring) => {
var times = 0; for (let i = 0; i < string.length - substring.length + 1; i++) { if (string.slice(i, i+substring.length) == substring) { times += 1; } } return times; }
javascript
THUDM/humaneval-x
/* Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sortNumbers('three one five') 'one three five' */ const sortNumbers = (numbers) => {
const value_map = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9 }; return numbers.split(' ') .filter(x => x != '') .sort((a, b) => value_map[a] - value_map[b]) .join(' '); }
javascript
THUDM/humaneval-x
/* From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) */ const findClosestElements = (numbers) => {
var closest_pair, distance; for (let i = 0; i < numbers.length; i++) for (let j = 0; j < numbers.length; j++) if (i != j) { let a = numbers[i], b = numbers[j]; if (distance == null) { distance = Math.abs(a - b); closest_pair = [Math.min(a, b), Math.max(a, b)]; } else { let new_distance = Math.abs(a - b); if (new_distance < distance) { distance = new_distance; closest_pair = [Math.min(a, b), Math.max(a, b)]; } } } return closest_pair; }
javascript
THUDM/humaneval-x
/* Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescaleToUnit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0] */ const rescaleToUnit = (numbers) => {
var min_number = Math.min(...numbers); var max_number = Math.max(...numbers); return numbers.map(x => (x - min_number) / (max_number - min_number)); }
javascript
THUDM/humaneval-x
/* Filter given list of any python values only for integers >>> filterIntegers(['a', 3.14, 5]) [5] >>> filterIntegers([1, 2, 3, 'abc', {}, []]) [1, 2, 3] */ const filterIntegers = (values) => {
return values.filter(x => Number.isInteger(x)); }
javascript
THUDM/humaneval-x
/* Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 */ const strlen = (string) => {
return string.length; }
javascript
THUDM/humaneval-x
/* For a given number n, find the largest number that divides n evenly, smaller than n >>> largestDivisor(15) 5 */ const largestDivisor = (n) => {
for (let i = n - 1; i >= 0; i--) if (n % i == 0) return i; }
javascript
THUDM/humaneval-x
/* Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] */ const factorize = (n) => {
var fact = [], i = 2; while (i <= Math.sqrt(n) + 1) { if (n % i == 0) { fact.push(i); n = n / i; } else { i += 1; } } if (n > 1) fact.push(n); return fact; }
javascript
THUDM/humaneval-x
/* From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> removeDuplicates([1, 2, 3, 2, 4]) [1, 3, 4] */ const removeDuplicates = (numbers) => {
var dict = new Object(); for (const num of numbers) { if (num in dict) { dict[num] += 1; } else { dict[num] = 1; } } return numbers.filter(x => dict[x] <= 1); }
javascript
THUDM/humaneval-x
/* For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flipCase('Hello') 'hELLO' */ const flipCase = (string) => {
return string.split('') .map(x => (x.toUpperCase() == x ? x.toLowerCase() : x.toUpperCase())) .join(''); }
javascript
THUDM/humaneval-x
/* Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' */ const concatenate = (strings) => {
return strings.join(''); }
javascript
THUDM/humaneval-x
/* Filter an input list of strings only for ones that start with a given prefix. >>> filterByPrefix([], 'a') [] >>> filterByPrefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] */ const filterByPrefix = (strings, prefix) => {
return strings.filter(x => x.startsWith(prefix)); }
javascript
THUDM/humaneval-x
/*Return only positive numbers in the list. >>> getPositive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> getPositive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1] */ const getPositive = (l) => {
return l.filter(e => e > 0); }
javascript
THUDM/humaneval-x
/*Return true if a given number is prime, and false otherwise. >>> isPrime(6) false >>> isPrime(101) true >>> isPrime(11) true >>> isPrime(13441) true >>> isPrime(61) true >>> isPrime(4) false >>> isPrime(1) false */ const isPrime = (n) => {
if (n < 2) return false; for (let k = 2; k < n - 1; k++) if (n % k == 0) return false; return true; }
javascript
THUDM/humaneval-x
/* Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n */ const poly = (xs, x) => { return xs.reduce((prev, item, index) => { return prev + item * Math.pow(x, index); }, 0); } /* xs are coefficients of a polynomial. findZero find x such that poly(x) = 0. findZero returns only only zero point, even if there are many. Moreover, findZero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. >>> round(findZero([1, 2]), 2) # f(x) = 1 + 2x -0.5 >>> round(findZero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3 1.0 */ const findZero = (xs) => {
var begin = -1.0, end = 1.0; while (poly(xs, begin) * poly(xs, end) > 0) { begin *= 2.0; end *= 2.0; } while (end - begin > 1e-10) { let center = (begin + end) / 2.0; if (poly(xs, center) * poly(xs, begin) > 0) begin = center; else end = center; } return begin; }
javascript
THUDM/humaneval-x
/*This function takes a list l and returns a list l' such that 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 to the values of the corresponding indicies of l, but sorted. >>> sortThird([1, 2, 3]) [1, 2, 3] >>> sortThird([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] */ const sortThird = (l) => {
var three = l.filter((item, index) => index % 3 == 0); three.sort((a, b) => (a - b)); return l.map((item, index) => (index % 3 == 0 ? three[index / 3] : item)); }
javascript
THUDM/humaneval-x
/*Return sorted unique elements in a list >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123]) [0, 2, 3, 5, 9, 123] */ const unique = (l) => {
return Array.from(new Set(l)).sort((a, b) => (a - b)); }
javascript
THUDM/humaneval-x
/*Return maximum element in the list. >>> maxElement([1, 2, 3]) 3 >>> maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 */ const maxElement = (l) => {
return Math.max(...l); }
javascript
THUDM/humaneval-x
/*Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizzBuzz(50) 0 >>> fizzBuzz(78) 2 >>> fizzBuzz(79) 3 */ const fizzBuzz = (n) => {
var ns = [], ans = 0; for (let i = 0; i < n; i++) if (i % 11 == 0 || i % 13 == 0) ns.push(i); var s = ns.map(x => x.toString()).join(''); for (const c of s) ans += (c == '7'); return ans; }
javascript
THUDM/humaneval-x
/*This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sortEven([1, 2, 3]) [1, 2, 3] >>> sortEven([5, 6, 3, 4]) [3, 6, 5, 4] */ const sortEven = (l) => {
var even = l.filter((item, index) => index % 2 == 0); even.sort((a, b) => (a - b)); return l.map((item, index) => (index % 2 == 0 ? even[index / 2] : item)); }
javascript
THUDM/humaneval-x
/* returns encoded string by cycling groups of three characters. */ const encodeCyclic = (s) => { var groups = [], groups2 = []; for (let i = 0; i < Math.floor((s.length + 2) / 3); i++) { groups.push(s.slice(3 * i, Math.min((3 * i + 3), s.length))); } for (const group of groups) { if (group.length == 3) groups2.push(group.slice(1) + group[0]); else groups2.push(group); } return groups2.join(''); } /* takes as input string encoded with encode_cyclic function. Returns decoded string. */ const decodeCyclic = (s) => {
return encodeCyclic(encodeCyclic(s)); }
javascript
THUDM/humaneval-x
/* primeFib returns n-th number that is a Fibonacci number and it's also prime. >>> primeFib(1) 2 >>> primeFib(2) 3 >>> primeFib(3) 5 >>> primeFib(4) 13 >>> primeFib(5) 89 */ const primeFib = (n) => {
var isPrime = function (p) { if (p < 2) return false; for (let k = 2; k < Math.min(Math.floor(Math.sqrt(p)) + 1, p - 1); k++) { if (p % k == 0) return false; } return true; } var f = [0, 1]; while (true) { f.push(f.at(-1) + f.at(-2)); if (isPrime(f.at(-1))) n -= 1; if (n == 0) return f.at(-1); } }
javascript
THUDM/humaneval-x
/* triplesSumToZero takes a list of integers as an input. it returns true if there are three distinct elements in the list that sum to zero, and false otherwise. >>> triplesSumToZero([1, 3, 5, 0]) false >>> triplesSumToZero([1, 3, -2, 1]) true >>> triplesSumToZero([1, 2, 3, 7]) false >>> triplesSumToZero([2, 4, -5, 3, 9, 7]) true >>> triplesSumToZero([1]) false */ const triplesSumToZero = (l) => {
for (let i = 0; i < l.length; i++) for (let j = i + 1; j < l.length; j++) for (let k = j + 1; k < l.length; k++) if (l[i] + l[j] + l[k] == 0) return true; return false; }
javascript
THUDM/humaneval-x
/* Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. */ const carRaceCollision = (n) => {
return Math.pow(n, 2); }
javascript
THUDM/humaneval-x
/*Return list with elements incremented by 1. >>> incrList([1, 2, 3]) [2, 3, 4] >>> incrList([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124] */ const incrList = (l) => {
return l.map(e => e + 1); }
javascript
THUDM/humaneval-x
/* pairsSumToZero takes a list of integers as an input. it returns true if there are two distinct elements in the list that sum to zero, and false otherwise. >>> pairsSumToZero([1, 3, 5, 0]) false >>> pairsSumToZero([1, 3, -2, 1]) false >>> pairsSumToZero([1, 2, 3, 7]) false >>> pairsSumToZero([2, 4, -5, 3, 5, 7]) true >>> pairsSumToZero([1]) false */ const pairsSumToZero = (l) => {
for (let i = 0; i < l.length; i++) for (let j = i + 1; j < l.length; j++) if (l[i] + l[j] == 0) return true; return false; }
javascript
THUDM/humaneval-x
/*Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> changeBase(8, 3) '22' >>> changeBase(8, 2) '1000' >>> changeBase(7, 2) '111' */ const changeBase = (x, base) => {
var ret = ""; while (x > 0) { ret = (x % base).toString() + ret; x = Math.floor(x / base); } return ret; }
javascript
THUDM/humaneval-x
/*Given length of a side and high return area for a triangle. >>> triangleArea(5, 3) 7.5 */ const triangleArea = (a, h) => {
return a * h / 2.0; }
javascript
THUDM/humaneval-x
/*The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 */ const fib4 = (n) => {
var results = [0, 0, 2, 0]; if (n < 4) return results[n]; for (let i = 4; i < n + 1; i++) { results.push(results.at(-1) + results.at(-2) + results.at(-3) + results.at(-4)); results.shift(); } return results.pop(); }
javascript
THUDM/humaneval-x
/*Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 8.0 */ const median = (l) => {
l.sort((a, b) => a - b); var len = l.length; if (l.length % 2 == 1) return l[Math.floor(len / 2)]; else return (l[len / 2 - 1] + l[len / 2]) / 2.0; }
javascript
THUDM/humaneval-x
/* Checks if given string is a palindrome >>> isPalindrome('') true >>> isPalindrome('aba') true >>> isPalindrome('aaaaa') true >>> isPalindrome('zbcd') false */ const isPalindrome = (text) => {
for (let i = 0; i < text.length; i++) if (text[i] != text.at(-i-1)) return false; return true; }
javascript
THUDM/humaneval-x
/*Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 */ const modp = (n, p) => {
var ret = 1; for (let i = 0; i < n; i++) ret = (2 * ret) % p; return ret; }
javascript
THUDM/humaneval-x
/* returns encoded string by shifting every character by 5 in the alphabet. */ const encodeShift = (s) => { return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) + 5 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0) )).join(""); } /* takes as input string encoded with encode_shift function. Returns decoded string. */ const decodeShift = (s) => {
return s.split("").map(ch => String.fromCharCode( ((ch.charCodeAt(0) - 5 + 26 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0) )).join(""); }
javascript
THUDM/humaneval-x
/* removeVowels is a function that takes string and returns string without vowels. >>> removeVowels('') '' >>> removeVowels("abcdef\nghijklm") 'bcdf\nghjklm' >>> removeVowels('abcdef') 'bcdf' >>> removeVowels('aaaaa') '' >>> removeVowels('aaBAA') 'B' >>> removeVowels('zbcd') 'zbcd' */ const removeVowels = (text) => {
return text.split("") .filter(s => !["a", "e", "i", "o", "u"] .includes(s.toLowerCase()) ) .join("") }
javascript
THUDM/humaneval-x
/*Return true if all numbers in the list l are below threshold t. >>> belowThreshold([1, 2, 4, 10], 100) true >>> belowThreshold([1, 20, 4, 10], 5) false */ const belowThreshold = (l, t) => {
for (const e of l) if (e >= t) return false; return true; }
javascript
THUDM/humaneval-x
/*Add two numbers x and y >>> add(2, 3) 5 >>> add(5, 7) 12 */ const add = (x, y) => {
return x + y; }
javascript
THUDM/humaneval-x
/* Check if two words have the same characters. >>> sameChars('eabcdzzzz', 'dddzzzzzzzddeddabc') true >>> sameChars('abcd', 'dddddddabc') true >>> sameChars('dddddddabc', 'abcd') true >>> sameChars('eabcd', 'dddddddabc') false >>> sameChars('abcd', 'dddddddabce') false >>> sameChars('eabcdzzzz', 'dddzzzzzzzddddabc') false */ const sameChars = (s0, s1) => {
return JSON.stringify([...new Set(s0)].sort()) === JSON.stringify([...new Set(s1)].sort()); }
javascript
THUDM/humaneval-x
/*Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 */ const fib = (n) => {
if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); }
javascript
THUDM/humaneval-x
/* brackets is a string of "<" and ">". return false if every opening bracket has a corresponding closing bracket. >>> correctBracketing("<") false >>> correctBracketing("<>") false >>> correctBracketing("<<><>>") false >>> correctBracketing("><<>") false */ const correctBracketing = (brackets) => {
var depth = 0; for (const b of brackets) { if (b == "<") depth += 1; else depth -= 1; if (depth < 0) return false; } return depth == 0; }
javascript
THUDM/humaneval-x
/*Return true is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) true >>> monotonic([1, 20, 4, 10]) false >>> monotonic([4, 1, 0, -10]) true */ const monotonic = (l) => {
var sort1 = [...l].sort((a, b) => a - b); var sort2 = [...l].sort((a, b) => b - a); if (JSON.stringify(l) === JSON.stringify(sort1) || JSON.stringify(l) === JSON.stringify(sort2)) return true; return false; }
javascript
THUDM/humaneval-x
/*Return sorted unique common elements for two lists. >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) [1, 5, 653] >>> common([5, 3, 2, 8], [3, 2]) [2, 3] */ const common = (l1, l2) => {
var ret = new Set(); for (const e1 of l1) for (const e2 of l2) if (e1 == e2) ret.add(e1); return [...ret].sort(); }
javascript
THUDM/humaneval-x
/*Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largestPrimeFactor(13195) 29 >>> largestPrimeFactor(2048) 2 */ const largestPrimeFactor = (n) => {
var isPrime = function (k) { if (k < 2) return false; for (let i = 2; i < k - 1; i++) if (k % i == 0) return false; return true; } var largest = 1; for (let j = 2; j < n + 1; j++) if (n % j == 0 && isPrime(j)) largest = Math.max(largest, j); return largest; }
javascript
THUDM/humaneval-x
/*sumToN is a function that sums numbers from 1 to n. >>> sumToN(30) 465 >>> sumToN(100) 5050 >>> sumToN(5) 15 >>> sumToN(10) 55 >>> sumToN(1) 1 */ const sumToN = (n) => {
return n * (n + 1) / 2; }
javascript
THUDM/humaneval-x
/* brackets is a string of "(" and ")". return true if every opening bracket has a corresponding closing bracket. >>> correctBracketing("(") false >>> correctBracketing("()") true >>> correctBracketing("(()())") true >>> correctBracketing(")(()") false */ const correctBracketing = (brackets) => {
var depth = 0; for (const b of brackets) { if (b == "(") depth += 1; else depth -= 1; if (depth < 0) return false; } return depth == 0; }
javascript
THUDM/humaneval-x
/* xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] */ const derivative = (xs) => {
return xs.map((x, i) => x * i).slice(1); }
javascript
THUDM/humaneval-x
/*The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Please write a function to efficiently compute the n-th element of the fibfib number sequence. >>> fibfib(1) 0 >>> fibfib(5) 4 >>> fibfib(8) 24 */ const fibfib = (n) => {
if (n == 0 || n == 1) return 0; if (n == 2) return 1; return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3); }
javascript
THUDM/humaneval-x
/*Write a function vowelsCount which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowelsCount("abcde") 2 >>> vowelsCount("ACEDY") 3 */ const vowelsCount = (s) => {
var vowels = "aeiouAEIOU"; var n_vowels = s.split('').reduce((prev, item) => { return prev + (vowels.includes(item)); }, 0); if (s.at(-1) == 'y' || s.at(-1) == 'Y') n_vowels += 1; return n_vowels; }
javascript
THUDM/humaneval-x
/*Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circularShift(12, 1) "21" >>> circularShift(12, 2) "12" */ const circularShift = (x, shift) => {
s = x.toString(); if (shift > s.length) return s.split('').reverse().join(''); else return s.slice(-shift) + s.slice(0, -shift); }
javascript
THUDM/humaneval-x
/*Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153 */ const digitSum = (s) => {
if (s == '') return 0; return s.split('').reduce((prev, char) => { let ord_char = char.charCodeAt(0) return prev + (ord_char > 64 && ord_char < 91 ? ord_char : 0); }, 0); }
javascript
THUDM/humaneval-x
/* In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: fruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 */ const fruitDistribution = (s, n) => {
var lis = []; for (const i of s.split(" ")) if (!isNaN(i)) lis.push(Number(i)) return n - lis.reduce(((prev, item) => prev + item), 0); }
javascript
THUDM/humaneval-x
/* "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: Input: [4,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: Input: [1,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: Input: [] Output: [] Example 4: Input: [5, 0, 3, 0, 4, 2] Output: [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value */ const pluck = (arr) => {
if (arr.length == 0) return []; var evens = arr.filter(x => x % 2 == 0); if (evens.length == 0) return []; return [Math.min(...evens), arr.indexOf(Math.min(...evens))]; }
javascript
THUDM/humaneval-x
/* You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: search([4, 1, 2, 2, 3, 1])) == 2 search([1, 2, 2, 3, 3, 3, 4, 4, 4])) == 3 search([5, 5, 4, 4, 4])) == -1 */ const search = (lst) => {
var frq = new Array(Math.max(...lst) + 1).fill(0); for (const i of lst) frq[i] += 1; var ans = -1; for (let i = 1; i < frq.length; i++) if (frq[i] >= i) ans = i; return ans; }
javascript
THUDM/humaneval-x
/* Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strangeSortList([1, 2, 3, 4]) == [1, 4, 2, 3] strangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5] strangeSortList([]) == [] */ const strangeSortList = (lst) => {
var res = [], sw = true; while (lst.length) { res.push(sw ? Math.min(...lst) : Math.max(...lst)); lst.splice(lst.indexOf(res.at(-1)), 1); sw = !sw; } return res; }
javascript
THUDM/humaneval-x
/* Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangleArea(3, 4, 5) == 6.00 triangleArea(1, 2, 10) == -1 */ const triangleArea = (a, b, c) => {
if (a + b <= c || a + c <= b || b + c <= a) return -1; var s = (a + b + c) / 2; var area = Math.pow(s * (s - a) * (s - b) * (s - c), 0.5); area = area.toFixed(2); return area; }
javascript
THUDM/humaneval-x
/* Write a function that returns true if the object q will fly, and false otherwise. 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. Example: willItFly([1, 2], 5) ➞ false # 1+2 is less than the maximum possible weight, but it's unbalanced. willItFly([3, 2, 3], 1) ➞ false # it's balanced, but 3+2+3 is more than the maximum possible weight. willItFly([3, 2, 3], 9) ➞ true # 3+2+3 is less than the maximum possible weight, and it's balanced. willItFly([3], 5) ➞ true # 3 is less than the maximum possible weight, and it's balanced. */ const willItFly = (q, w) => {
if (q.reduce(((prev, item) => prev + item), 0) > w) return false; var i = 0, j = q.length - 1; while (i < j) { if (q[i] != q[j]) return false; i++; j--; } return true; }
javascript
THUDM/humaneval-x
/* Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallestChange([1,2,3,5,4,7,9,6]) == 4 smallestChange([1, 2, 3, 4, 3, 2, 2]) == 1 smallestChange([1, 2, 3, 2, 1]) == 0 */ const smallestChange = (arr) => {
var ans = 0; for (let i = 0; i < Math.floor(arr.length / 2); i++) if (arr[i] != arr.at(-i - 1)) ans++; return ans; }
javascript
THUDM/humaneval-x
/* Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples totalMatch([], []) ➞ [] totalMatch(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi'] totalMatch(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin'] totalMatch(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi'] totalMatch(['4'], ['1', '2', '3', '4', '5']) ➞ ['4'] */ const totalMatch = (lst1, lst2) => {
var l1 = lst1.reduce(((prev, item) => prev + item.length), 0); var l2 = lst2.reduce(((prev, item) => prev + item.length), 0); if (l1 <= l2) return lst1; else return lst2; }
javascript
THUDM/humaneval-x
/*Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: isMultiplyPrime(30) == true 30 = 2 * 3 * 5 */ const isMultiplyPrime = (a) => {
var isPrime = function (n) { for (let j = 2; j < n; j++) if (n % j == 0) return false; return true; } for (let i = 2; i < 101; i++) { if (!isPrime(i)) continue; for (let j = 2; j < 101; j++) { if (!isPrime(j)) continue; for (let k = 2; k < 101; k++) { if (!isPrime(k)) continue; if (i*j*k == a) return true; } } } return false; }
javascript
THUDM/humaneval-x
/*Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: isSimplePower(1, 4) => true isSimplePower(2, 2) => true isSimplePower(8, 2) => true isSimplePower(3, 2) => false isSimplePower(3, 1) => false isSimplePower(5, 3) => false */ const isSimplePower = (x, n) => {
if (n == 1) return (x == 1); var power = 1; while (power < x) power = power * n; return (power == x); }
javascript
THUDM/humaneval-x
/* Write a function that takes an integer a and returns true if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: iscube(1) ==> true iscube(2) ==> false iscube(-1) ==> true iscube(64) ==> true iscube(0) ==> true iscube(180) ==> false */ const iscube = (a) => {
a = Math.abs(a); return (Math.pow(Math.round(Math.pow(a, 1.0 / 3.0)), 3) == a); }
javascript
THUDM/humaneval-x
/*You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number=== or a prime=== is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0=== 1=== 2=== 3=== 4=== 5=== 6=== 7=== 8=== 9=== A=== B=== C=== D=== E=== F. Prime numbers are 2=== 3=== 5=== 7=== 11=== 13=== 17===... So you have to determine a number of the following digits: 2=== 3=== 5=== 7=== B (=decimal 11)=== D (=decimal 13). Note: you may assume the input is always correct or empty string=== and symbols A===B===C===D===E===F are always uppercase. Examples: For num = "AB" the output should be 1. For num = "1077E" the output should be 2. For num = "ABED1A33" the output should be 4. For num = "123456789ABCDEF0" the output should be 6. For num = "2020" the output should be 2. */ const hexKey = (num) => {
var primes = "2357BD", total = 0; for (let i = 0; i < num.length; i++) if (primes.includes(num[i])) total++; return total; }
javascript
THUDM/humaneval-x
/*You will be given a number in decimal form and your task is to convert it to binary format. The function should return a string, with each character representing a binary number. Each character in the string will be '0' or '1'. There will be an extra couple of characters 'db' at the beginning and at the end of the string. The extra characters are there to help with the format. Examples: decimalToBinary(15) # returns "db1111db" decimalToBinary(32) # returns "db100000db" */ const decimalToBinary = (decimal) => {
return "db" + decimal.toString(2) + "db"; }
javascript
THUDM/humaneval-x
/*You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct For example: isHappy(a) => false isHappy(aa) => false isHappy(abcd) => true isHappy(aabb) => false isHappy(adb) => true isHappy(xyy) => false */ const isHappy = (s) => {
if (s.length < 3) return false; for (let i = 0; i < s.length - 2; i++) if (s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2]) return false; return true; }
javascript
THUDM/humaneval-x
/*It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: numericalLetterGrade([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-'] */ const numericalLetterGrade = (grades) => {
let letter_grade = [] for (let i = 0, len = grades.length; i < len; i++) { let gpa = grades[i] if (gpa == 4.0) { letter_grade.push('A+') } else if (gpa > 3.7) { letter_grade.push('A') } else if (gpa > 3.3) { letter_grade.push('A-') } else if (gpa > 3.0) { letter_grade.push('B+') } else if (gpa > 2.7) { letter_grade.push('B') } else if (gpa > 2.3) { letter_grade.push('B-') } else if (gpa > 2.0) { letter_grade.push('C+') } else if (gpa > 1.7) { letter_grade.push('C') } else if (gpa > 1.3) { letter_grade.push('C-') } else if (gpa > 1.0) { letter_grade.push('D+') } else if (gpa > 0.7) { letter_grade.push('D') } else if (gpa > 0.0) { letter_grade.push('D-') } else { letter_grade.push('E') } } return letter_grade }
javascript
THUDM/humaneval-x
/*Write a function that takes a string and returns true if the string length is a prime number or false otherwise Examples primeLength('Hello') == true primeLength('abcdcba') == true primeLength('kittens') == true primeLength('orange') == false */ const primeLength = (string) => {
let len = string.length if (len == 1 || len == 0) { return false } for (let i = 2; i * i <= len; i++) { if (len % i == 0) { return false } } return true }
javascript
THUDM/humaneval-x
/* Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1. */ const startsOneEnds = (n) => {
if (n == 1) { return 1 } let t = 18 for (let i = 2; i < n; i++) { t = t * 10 } return t }
javascript
THUDM/humaneval-x
/*Given a positive integer N, return the total sum of its digits in binary. Example For N = 1000, the sum of digits will be 1 the output should be "1". For N = 150, the sum of digits will be 6 the output should be "110". For N = 147, the sum of digits will be 12 the output should be "1100". Variables: @N integer Constraints: 0 ≀ N ≀ 10000. Output: a string of binary number */ const solve = (N) => {
let t = 0 while (N > 0) { t += N % 10 N = (N - N % 10) / 10 } return t.toString(2) }
javascript
THUDM/humaneval-x
/*Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add([4, 2, 6, 7]) ==> 2 */ const add = (lst) => {
let t = 0 for (let i = 1; i < lst.length; i += 2) { if (lst[i] % 2 == 0) { t += lst[i] } } return t }
javascript
THUDM/humaneval-x
/* Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: antiShuffle('Hi') returns 'Hi' antiShuffle('hello') returns 'ehllo' antiShuffle('Hello World!!!') returns 'Hello !!!Wdlor' */ const antiShuffle = (s) => {
let arr = s.split(/\s/) for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { let ind = j for (let k = j + 1; k < arr[i].length; k++) { if (arr[i][k].charCodeAt() < arr[i][ind].charCodeAt()) { ind = k } } if (ind > j) { arr[i] = arr[i].slice(0, j) + arr[i][ind] + arr[i].slice(j + 1, ind) + arr[i][j] + arr[i].slice(ind + 1, arr[i].length) } } } let t = '' for (let i = 0; i < arr.length; i++) { if (i > 0) { t = t + ' ' } t = t + arr[i] } return t }
javascript
THUDM/humaneval-x
/* You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: getRow([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] getRow([], 1) == [] getRow([[], [1], [1, 2, 3]], 3) == [(2, 2)] */ const getRow = (lst, x) => {
let t = [] for (let i = 0; i < lst.length; i++) { for (let j = lst[i].length - 1; j >= 0; j--) { if (lst[i][j] == x) { t.push((i, j)) } } } return t }
javascript
THUDM/humaneval-x
/* Given an array of non-negative integers, return a copy of the given array after sorting, you will sort the given array in ascending order if the sum( first index value, last index value) is odd, or sort it in descending order if the sum( first index value, last index value) is even. Note: * don't change the given array. Examples: * sortArray([]) => [] * sortArray([5]) => [5] * sortArray([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5] * sortArray([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0] */ const sortArray = (array) => {
let arr = array let tot = arr[0] + arr[arr.length-1] for (let j = 0; j < arr.length; j++) { let ind = j for (let k = j + 1; k < arr.length; k++) { if ((tot % 2 == 1 && arr[k] < arr[ind]) || (tot % 2 == 0 && arr[k] > arr[ind])) { ind = k } } let tmp = arr[j] arr[j] = arr[ind] arr[ind] = tmp } return arr }
javascript
THUDM/humaneval-x
/*Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. For example: encrypt('hi') returns 'lm' encrypt('asdfghjkl') returns 'ewhjklnop' encrypt('gf') returns 'kj' encrypt('et') returns 'ix' */ const encrypt = (s) => {
let t = '' for (let i = 0; i < s.length; i++) { let p = s[i].charCodeAt() + 4 if (p > 122) { p -= 26 } t += String.fromCharCode(p) } return t }
javascript
THUDM/humaneval-x
/* You are given a list of integers. Write a function nextSmallest() that returns the 2nd smallest element of the list. Return null if there is no such element. nextSmallest([1, 2, 3, 4, 5]) == 2 nextSmallest([5, 1, 4, 3, 2]) == 2 nextSmallest([]) == null nextSmallest([1, 1]) == null */ const nextSmallest = (lst) => {
let arr = lst for (let j = 0; j < arr.length; j++) { let ind = j for (let k = j + 1; k < arr.length; k++) { if (arr[k] < arr[ind]) { ind = k } } let tmp = arr[j] arr[j] = arr[ind] arr[ind] = tmp } let smallest = arr[0] let pt = 1 while(pt<arr.length){ if(arr[pt]>smallest){ return arr[pt] } pt++ } return null }
javascript
THUDM/humaneval-x
/* You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For example: >>> isBored("Hello world") 0 >>> isBored("The sky is blue. The sun is shining. I love this weather") 1 */ const isBored = (S) => {
let t = 0 if (S[0] == 'I' && S[1] == ' ') { t = 1 } for (let i = 0; i < S.length; i++) { if (S[i] == '.' || S[i] == '!' || S[i] == '?') { if (S[i + 1] == ' ' && S[i + 2] == 'I' && S[i + 3] == ' ') { t++ } } } return t }
javascript
THUDM/humaneval-x
/* Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples anyInt(5, 2, 7) ➞ true anyInt(3, 2, 2) ➞ false anyInt(3, -2, 1) ➞ true anyInt(3.6, -2.2, 2) ➞ false */ const anyInt = (x, y, z) => {
if (x % 1 === 0 && y % 1 === 0 && z % 1 === 0 && (x + y === z || x + z === y || x === y + z)) { return true } return false }
javascript
THUDM/humaneval-x
/* Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' */ const encode = (message) => {
let t = '' for (let i = 0; i < message.length; i++) { let p = message[i].charCodeAt() if (p > 96) { p -= 32 } else if (p!=32 && p < 96) { p += 32 } if (p == 65 || p == 97 || p == 69 || p == 101 || p == 73 || p == 105 || p == 79 || p == 111 || p == 85 || p == 117) { p += 2 } t += String.fromCharCode(p) } return t }
javascript
THUDM/humaneval-x
/*You are given a list of integers. You need to find the largest prime value and return the sum of its digits. Examples: 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 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 For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13 For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11 For lst = [0,81,12,3,1,21] the output should be 3 For lst = [0,8,1,2,1,7] the output should be 7 */ const skjkasdkd = (lst) => {
let t = 0 for (let i = 0; i < lst.length; i++) { let p = 1 for (let j = 2; j * j <= lst[i]; j++) { if (lst[i] % j == 0) { p = 0; break } } if (p == 1 && lst[i] > t) { t = lst[i] } } let k = 0 while (t != 0) { k += t % 10 t = (t - t % 10) / 10 } return k }
javascript
THUDM/humaneval-x
/* Given a dictionary, return true if all keys are strings in lower case or all keys are strings in upper case, else return false. The function should return false is the given dictionary is empty. Examples: checkDictCase({"a":"apple", "b":"banana"}) should return true. checkDictCase({"a":"apple", "A":"banana", "B":"banana"}) should return false. checkDictCase({"a":"apple", 8:"banana", "a":"apple"}) should return false. checkDictCase({"Name":"John", "Age":"36", "City":"Houston"}) should return false. checkDictCase({"STATE":"NC", "ZIP":"12345" }) should return true. */ const checkDictCase = (dict) => {
let c = 0 let lo = 1 let hi = 1 for (let key in dict) { c++ for (let i = 0; i < key.length; i++) { if (key[i].charCodeAt() < 65 || key[i].charCodeAt() > 90) { hi = 0 } if (key[i].charCodeAt() < 97 || key[i].charCodeAt() > 122) { lo = 0 } } } if ((lo == 0 && hi == 0) || c == 0) { return false } return true }
javascript
THUDM/humaneval-x
/*Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: countUpTo(5) => [2,3] countUpTo(11) => [2,3,5,7] countUpTo(0) => [] countUpTo(20) => [2,3,5,7,11,13,17,19] countUpTo(1) => [] countUpTo(18) => [2,3,5,7,11,13,17] */ const countUpTo = (n) => {
let t = [] for (let i = 2; i < n; i++) { let p = 1 for (let j = 2; j * j <= i; j++) { if (i % j == 0) { p = 0; break } } if (p == 1) { t.push(i) } } return t }
javascript
THUDM/humaneval-x
/*Complete the function that takes two integers and returns the product of their unit digits. Assume the input is always valid. Examples: multiply(148, 412) should return 16. multiply(19, 28) should return 72. multiply(2020, 1851) should return 0. multiply(14,-15) should return 20. */ const multiply = (a, b) => {
if (a < 0) { a = -a } if (b < 0) { b = -b } return (a % 10) * (b % 10) }
javascript
THUDM/humaneval-x
/* Given a string s, count the number of uppercase vowels in even indices. For example: countUpper('aBCdEf') returns 1 countUpper('abcdefg') returns 0 countUpper('dBBE') returns 0 */ const countUpper = (s) => {
let p = 0 for (let i = 0; i < s.length; i += 2) { if (s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U') { p++ } } return p }
javascript
THUDM/humaneval-x
/* Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closestInteger("10") 10 >>> closestInteger("15.3") 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closestInteger("14.5") should return 15 and closestInteger("-14.5") should return -15. */ const closestInteger = (value) => {
value = Number(value) let t = value % 1 if (t < 0.5 && t > -0.5) { value -= t } else { value += t } return value }
javascript
THUDM/humaneval-x
/* Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a list, where element at index i represents the number of stones in the level (i+1). Examples: >>> makeAPile(3) [3, 5, 7] */ const makeAPile = (n) => {
let t = [] for (let i = n; i < n * 3; i += 2) { t.push(i) } return t }
javascript
THUDM/humaneval-x
/* You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return an array of the words. For example: wordsString("Hi, my name is John") == ["Hi", "my", "name", "is", "John"] wordsString("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"] */ const wordsString = (s) => {
let t = '' let p = [] let k = 0 for (let i = 0; i < s.length; i++) { if (s[i] == ' ' || s[i] == ',') { if (k == 0) { k = 1; p.push(t); t = ''; } } else { k = 0; t += s[i] } } if (t != '') { p.push(t); } return p }
javascript
THUDM/humaneval-x
/*This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: chooseNum(12, 15) = 14 chooseNum(13, 12) = -1 */ const chooseNum = (x, y) => {
for (let i = y; i >= x; i--) { if (i % 2 == 0) {return i } } return -1 }
javascript
THUDM/humaneval-x
/*You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer and convert that to binary. If n is greater than m, return -1. Example: roundedAvg(1, 5) => "0b11" roundedAvg(7, 5) => -1 roundedAvg(10, 20) => "0b1111" roundedAvg(20, 33) => "0b11010" */ const roundedAvg = (n, m) => {
if (n > m) { return -1 } let k = (n + m) / 2 if (k % 1 != 0) { k = (n + m + 1) / 2 } return '0b' + k.toString(2) }
javascript
THUDM/humaneval-x
/*Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing order. For example: >>> uniqueDigits([15, 33, 1422, 1]) [1, 15, 33] >>> uniqueDigits([152, 323, 1422, 10]) [] */ const uniqueDigits = (x) => {
let p = [] for (let i = 0; i < x.length; i++) { let h = x[i] let boo = 1 while (h > 0) { let r = h % 10 if (r % 2 == 0) { boo = 0; break; } h = (h - r) / 10 } if (boo) { p.push(x[i]) } } for (let j = 0; j < p.length; j++) { let ind = j for (let k = j + 1; k < p.length; k++) { if (p[k] < p[ind]) { ind = k } } if (ind > j) { let tmp = p[j] p[j] = p[ind] p[ind] = tmp } } return p }
javascript
THUDM/humaneval-x
/* Given an array of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting array, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". For example: arr = [2, 1, 1, 4, 5, 8, 2, 3] -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1] return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] If the array is empty, return an empty array: arr = [] return [] If the array has any strange number ignore it: arr = [1, -1 , 55] -> sort arr -> [-1, 1, 55] -> reverse arr -> [55, 1, -1] return = ['One'] */ const byLength = (arr) => {
p = [] for (let i = 0; i < arr.length; i++) { if (arr[i] > 0 && arr[i] < 10) { p.push(arr[i]) } } for (let j = 0; j < p.length; j++) { let ind = j for (let k = j + 1; k < p.length; k++) { if (p[k] > p[ind]) { ind = k } } if (ind > j) { let tmp = p[j] p[j] = p[ind] p[ind] = tmp } } let l = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] let t = [] for (let j = 0; j < p.length; j++) { t.push(l[p[j]-1]) } return t }
javascript
THUDM/humaneval-x
/* Implement the function f that takes n as a parameter, 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 or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: f(5) == [1, 2, 6, 24, 15] */ const f = (n) => {
let f = 1 let p = 0 let k = [] for (let i = 1; i <= n; i++) { p += i; f *= i; if (i % 2 == 0) { k.push(f) } else { k.push(p) } } return k }
javascript
THUDM/humaneval-x
/* Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. */ const evenOddPalindrome = (n) => {
let e = 0 let o = 0 for (let i = 1; i <= n; i++) { let k = i.toString() let p = 1 for (let j = 0; j < k.length; j++) { if (k[j] != k[k.length - j - 1]) { p = 0; break; } } if (p == 1) { if (k % 2 == 0) { e++ } else { o++ } } } return (e, o) }
javascript
THUDM/humaneval-x