name
stringlengths
34
63
language
stringclasses
3 values
prompt
stringlengths
91
2.81k
suffix
stringlengths
0
1.57k
canonical_solution
stringlengths
1
219
tests
stringlengths
149
4.98k
humaneval-HumanEval_26_remove_duplicates.json-L9
js
//From an array of integers, remove all elements that occur more than once. // Keep order of elements left the same as in the input. // >>> remove_duplicates([1, 2, 3, 2, 4]) // [1, 3, 4] function remove_duplicates(numbers){ let result = []; numbers.forEach(function(value){ if(numbers.indexOf(value) === numbers.lastIndexOf(value)){
} }); return result; }
result.push(value);
const assert = require('node:assert'); function test() { let candidate = remove_duplicates; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4]),[1, 2, 3, 4]); assert.deepEqual(candidate([1, 2, 3, 2, 4, 3, 5]),[1, 4, 5]); } test();
humaneval-HumanEval_37_sort_even.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // This function takes an array array list l and returns an array array 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((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>(); ArrayList<Long> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } index++; } Collections.sort(evenIndexed); index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else { res.add(num); }
} return res; } }
index++;
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_131_digits.json-L26
js
//Given a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits(1) // 1 // >>> digits(4) // 0 // >>> digits(235) // 15 function digits(n){ if(!n){ return "error"; } if(n < 0){ return "error"; } var temp = 0; var prod = 1; var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp; odd = false; }
if(odd){ return 0; } return prod; }
}
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_93_encode.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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") public static String encode(String message) { char[] arr = message.toCharArray();
for (int i = 0; i < arr.length; i++) { if (Arrays.binarySearch(vowels, arr[i]) > -1) { arr[i] = (char) (arr[i] + 2); } if (Character.isUpperCase(arr[i])) { arr[i] = Character.toLowerCase(arr[i]); } else { arr[i] = Character.toUpperCase(arr[i]); } } return new String(arr); } }
char[] vowels = "AEIOUaeiou".toCharArray();
} public static void main(String[] args) { assert(encode(("TEST")).equals(("tgst"))); assert(encode(("Mudasir")).equals(("mWDCSKR"))); assert(encode(("YES")).equals(("ygs"))); assert(encode(("This is a message")).equals(("tHKS KS C MGSSCGG"))); assert(encode(("I DoNt KnOw WhAt tO WrItE")).equals(("k dQnT kNqW wHcT Tq wRkTg"))); } }
humaneval-HumanEval_9_rolling_max.json-L7
js
//From a given array of integers, generate an array of rolling maximum element found until given moment // in the sequence. // >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) // [1, 2, 3, 3, 3, 4, 4] function rolling_max(numbers){ let max = [];
for(let i = 0; i < numbers.length; i++){ if(tempMax < numbers[i]){ tempMax = numbers[i]; } max.push(tempMax); } return max; }
let tempMax = 0;
const assert = require('node:assert'); function test() { let candidate = rolling_max; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4]),[1, 2, 3, 4]); assert.deepEqual(candidate([4, 3, 2, 1]),[4, 4, 4, 4]); assert.deepEqual(candidate([3, 2, 3, 100, 3]),[3, 3, 3, 100, 100]); } test();
humaneval-HumanEval_36_fizz_buzz.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. // >>> fizzBuzz((50l)) // (0l) // >>> fizzBuzz((78l)) // (2l) // >>> fizzBuzz((79l)) // (3l) public static long fizzBuzz(long n) { long res = 0; for (long i = 0; i < n; i++) { if (i % 11 == 0 || i % 13 == 0) { String s = String.valueOf(i); for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '7') { res++; }
} } return res; } }
}
} public static void main(String[] args) { assert(fizzBuzz((50l)) == (0l)); assert(fizzBuzz((78l)) == (2l)); assert(fizzBuzz((79l)) == (3l)); assert(fizzBuzz((100l)) == (3l)); assert(fizzBuzz((200l)) == (6l)); assert(fizzBuzz((4000l)) == (192l)); assert(fizzBuzz((10000l)) == (639l)); assert(fizzBuzz((100000l)) == (8026l)); } }
humaneval-HumanEval_59_largest_prime_factor.json-L18
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return the largest prime factor of n. Assume n > 1 and is not a prime. // >>> largestPrimeFactor((13195l)) // (29l) // >>> largestPrimeFactor((2048l)) // (2l) public static long largestPrimeFactor(long n) { List<Long> primes = new ArrayList<>(); long x = n; for (long i = 2; i * i <= x; i++) {
primes.add(i); x /= i; i--; } } if (x > 1) { primes.add(x); } return primes.get(primes.size() - 1); } }
if (x % i == 0) {
} public static void main(String[] args) { assert(largestPrimeFactor((15l)) == (5l)); assert(largestPrimeFactor((27l)) == (3l)); assert(largestPrimeFactor((63l)) == (7l)); assert(largestPrimeFactor((330l)) == (11l)); assert(largestPrimeFactor((13195l)) == (29l)); } }
humaneval-HumanEval_25_factorize.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return array list of prime factors of given integer in the order from smallest to largest. // Each of the factors should be array 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((8l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))) // >>> factorize((25l)) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l))) // >>> factorize((70l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)7l))) public static ArrayList<Long> factorize(long n) { ArrayList<Long> factors = new ArrayList<Long>();
while (n % d == 0) { factors.add(d); n /= d; } } if (n > 1) factors.add(n); return factors; } }
for (long d = 2; d*d <= n; d++) {
} public static void main(String[] args) { assert(factorize((2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(factorize((4l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(factorize((8l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))))); assert(factorize((57l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l))))); assert(factorize((3249l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)19l, (long)19l))))); assert(factorize((185193l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((20577l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)3l))))); } }
humaneval-HumanEval_146_specialFilter.json-L17
py
from typing import List def specialFilter(nums: List[int]) -> int: """Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: >>> specialFilter([15, -73, 14, -15]) 1 >>> specialFilter([33, -2, -3, 45, 21, 109]) 2 """ count = 0 for num in nums: if num < 10: continue
rev = int(str(num)[::-1]) if num % 2 != 0 and rev % 2 != 0: count += 1 return count
else:
def check(candidate): assert candidate([5, -2, 1, -5]) == 0 assert candidate([15, -73, 14, -15]) == 1 assert candidate([33, -2, -3, 45, 21, 109]) == 2 assert candidate([43, -12, 93, 125, 121, 109]) == 4 assert candidate([71, -2, -33, 75, 21, 19]) == 3 assert candidate([1]) == 0 assert candidate([]) == 0 def test_check(): check(specialFilter) test_check()
humaneval-HumanEval_139_special_factorial.json-L16
py
def special_factorial(n: int) -> int: """The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. """ def factorial(n): if n <= 1: return 1
return n * factorial(n-1) if n <= 1: return 1 else: return n * special_factorial(n-1) * factorial(n-1)
else:
def check(candidate): assert candidate(4) == 288 assert candidate(5) == 34560 assert candidate(7) == 125411328000 assert candidate(1) == 1 def test_check(): check(special_factorial) test_check()
humaneval-HumanEval_146_specialFilter.json-L14
py
from typing import List def specialFilter(nums: List[int]) -> int: """Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: >>> specialFilter([15, -73, 14, -15]) 1 >>> specialFilter([33, -2, -3, 45, 21, 109]) 2 """ count = 0
if num < 10: continue else: rev = int(str(num)[::-1]) if num % 2 != 0 and rev % 2 != 0: count += 1 return count
for num in nums:
def check(candidate): assert candidate([5, -2, 1, -5]) == 0 assert candidate([15, -73, 14, -15]) == 1 assert candidate([33, -2, -3, 45, 21, 109]) == 2 assert candidate([43, -12, 93, 125, 121, 109]) == 4 assert candidate([71, -2, -33, 75, 21, 19]) == 3 assert candidate([1]) == 0 assert candidate([]) == 0 def test_check(): check(specialFilter) test_check()
humaneval-HumanEval_122_add_elements.json-L17
js
//Given a non-empty array of integers arr and an integer k, return // the sum of the elements with at most two digits from the first k elements of arr. // Example: // >>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4) // 24 // Constraints: // 1. 1 <= len(arr) <= 100 // 2. 1 <= k <= len(arr) function add_elements(arr, k){ var sum = 0; for(var i = 0; i < k; i++){ if(arr[i] < 100){ sum += arr[i]; } } return sum;
}
const assert = require('node:assert'); function test() { let candidate = add_elements; assert.deepEqual(candidate([1, -2, -3, 41, 57, 76, 87, 88, 99], 3),-4); assert.deepEqual(candidate([111, 121, 3, 4000, 5, 6], 2),0); assert.deepEqual(candidate([11, 21, 3, 90, 5, 6, 7, 8, 9], 4),125); assert.deepEqual(candidate([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4),24); assert.deepEqual(candidate([1], 1),1); } test();
humaneval-HumanEval_13_greatest_common_divisor.json-L14
js
//Return a greatest common divisor of two integers a and b // >>> greatest_common_divisor(3, 5) // 1 // >>> greatest_common_divisor(25, 15) // 5 function greatest_common_divisor(a, b){ let max = Math.max(a, b) let min = Math.min(a, b) if (max % min == 0) { return min } else { return greatest_common_divisor(min, max % min) }
}
const assert = require('node:assert'); function test() { let candidate = greatest_common_divisor; assert.deepEqual(candidate(3, 7),1); assert.deepEqual(candidate(10, 15),5); assert.deepEqual(candidate(49, 14),7); assert.deepEqual(candidate(144, 60),12); } test();
humaneval-HumanEval_95_check_dict_case.json-L34
js
//Given an object, 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 object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; } } else if (case_type == 1){
return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } } else{ return false; } } return true; }
if (key != key.toUpperCase()){
const assert = require('node:assert'); function test() { let candidate = check_dict_case; assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true); assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false); assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false); assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false); assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true); assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true); assert.deepEqual(candidate({}),false); } test();
humaneval-HumanEval_118_get_closest_vowel.json-L29
js
//You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> get_closest_vowel("yogurt") // "u" // >>> get_closest_vowel("FULL") // "U" // >>> get_closest_vowel("quick") // "" // >>> get_closest_vowel("ab") // "" function get_closest_vowel(word){ let vowels = ["a", "e", "i", "o", "u"]; let i = word.length - 1; let result = []; if (word.length === 1) { return "" } else { while (i >= 0) { if (vowels.includes(word[i])) { if (i > 0 && i < word.length - 1) { if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) { result.push(word[i]); } }
i--; } if (result.length === 0) { return "" } else { return result[0]; } } }
}
const assert = require('node:assert'); function test() { let candidate = get_closest_vowel; assert.deepEqual(candidate("yogurt"),"u"); assert.deepEqual(candidate("full"),"u"); assert.deepEqual(candidate("easy"),""); assert.deepEqual(candidate("eAsy"),""); assert.deepEqual(candidate("ali"),""); assert.deepEqual(candidate("bad"),"a"); assert.deepEqual(candidate("most"),"o"); assert.deepEqual(candidate("ab"),""); assert.deepEqual(candidate("ba"),""); assert.deepEqual(candidate("quick"),""); assert.deepEqual(candidate("anime"),"i"); assert.deepEqual(candidate("Asia"),""); assert.deepEqual(candidate("Above"),"o"); } test();
humaneval-HumanEval_124_valid_date.json-L30
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 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. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){ return false; }
return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; } return false; }
}else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_141_file_name_check.json-L26
py
def file_name_check(file_name: str) -> str: """Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and returns 'No' otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] Examples: >>> file_name_check('example.txt') 'Yes' >>> file_name_check('1example.dll') 'No' """ if not file_name: return 'No' s_count = 0 e_count = 0 for i in file_name: if i.isdigit(): s_count += 1 if i == '.': e_count += 1
return 'No' s_name = file_name.split('.')[0] e_name = file_name.split('.')[1] if not s_name or not e_name or not s_name[0].isalpha(): return 'No' if e_name not in ['txt', 'exe', 'dll']: return 'No' return 'Yes'
if s_count > 3 or e_count != 1:
def check(candidate): assert candidate('example.txt') == 'Yes' assert candidate('1example.dll') == 'No' assert candidate('s1sdf3.asd') == 'No' assert candidate('K.dll') == 'Yes' assert candidate('MY16FILE3.exe') == 'Yes' assert candidate('His12FILE94.exe') == 'No' assert candidate('_Y.txt') == 'No' assert candidate('?aREYA.exe') == 'No' assert candidate('/this_is_valid.dll') == 'No' assert candidate('this_is_valid.wow') == 'No' assert candidate('this_is_valid.txt') == 'Yes' assert candidate('this_is_valid.txtexe') == 'No' assert candidate('#this2_i4s_5valid.ten') == 'No' assert candidate('@this1_is6_valid.exe') == 'No' assert candidate('this_is_12valid.6exe4.txt') == 'No' assert candidate('all.exe.txt') == 'No' assert candidate('I563_No.exe') == 'Yes' assert candidate('Is3youfault.txt') == 'Yes' assert candidate('no_one#knows.dll') == 'Yes' assert candidate('1I563_Yes3.exe') == 'No' assert candidate('I563_Yes3.txtt') == 'No' assert candidate('final..txt') == 'No' assert candidate('final132') == 'No' assert candidate('_f4indsartal132.') == 'No' assert candidate('.txt') == 'No' assert candidate('s.') == 'No' def test_check(): check(file_name_check) test_check()
humaneval-HumanEval_37_sort_even.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // This function takes an array array list l and returns an array array 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((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>(); ArrayList<Long> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } index++;
Collections.sort(evenIndexed); index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else { res.add(num); } index++; } return res; } }
}
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_96_count_up_to.json-L27
py
from typing import List def count_up_to(n: int) -> List[int]: """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: >>> count_up_to(5) [2, 3] >>> count_up_to(11) [2, 3, 5, 7] >>> count_up_to(0) [] >>> count_up_to(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> count_up_to(1) [] >>> count_up_to(18) [2, 3, 5, 7, 11, 13, 17] """ if n <= 1: return [] result = [] for number in range(2, n): is_prime = True for divisor in range(2, number): if number % divisor == 0:
break if is_prime: result.append(number) return result
is_prime = False
def check(candidate): assert candidate(5) == [2, 3] assert candidate(6) == [2, 3, 5] assert candidate(7) == [2, 3, 5] assert candidate(10) == [2, 3, 5, 7] assert candidate(0) == [] assert candidate(22) == [2, 3, 5, 7, 11, 13, 17, 19] assert candidate(1) == [] assert candidate(18) == [2, 3, 5, 7, 11, 13, 17] assert candidate(47) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43] assert candidate(101) == [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] def test_check(): check(count_up_to) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L50
js
//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 an array of GPAs for some students and you have to write // a function that can output an array 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: // >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) // ["A+", "B", "C-", "C", "A-"] function numerical_letter_grade(grades){ var grades_array = []; for (var i = 0; i < grades.length; i++){ if (grades[i] >= 4.0){ grades_array.push("A+"); } else if (grades[i] > 3.7){ grades_array.push("A"); } else if (grades[i] > 3.3){ grades_array.push("A-"); } else if (grades[i] > 3.0){ grades_array.push("B+"); } else if (grades[i] > 2.7){ grades_array.push("B"); } else if (grades[i] > 2.3){ grades_array.push("B-"); } else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); }
grades_array.push("C-"); } else if (grades[i] > 1.0){ grades_array.push("D+"); } else if (grades[i] > 0.7){ grades_array.push("D"); } else if (grades[i] > 0.0){ grades_array.push("D-"); } else if (grades[i] == 0.0){ grades_array.push("E"); } } return grades_array; }
else if (grades[i] > 1.3){
const assert = require('node:assert'); function test() { let candidate = numerical_letter_grade; assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]); assert.deepEqual(candidate([1.2]),["D+"]); assert.deepEqual(candidate([0.5]),["D-"]); assert.deepEqual(candidate([0.0]),["E"]); assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]); assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]); } test();
humaneval-HumanEval_124_valid_date.json-L22
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 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. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]);
var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){ return false; } }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; } return false; }
var day = parseInt(date_arr[1]);
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_41_car_race_collision.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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. public static long carRaceCollision(long n) { BigInteger nBigInteger = BigInteger.valueOf(n); BigInteger nSquared = nBigInteger.multiply(nBigInteger); return nSquared.longValue();
}
}
} public static void main(String[] args) { assert(carRaceCollision((2l)) == (4l)); assert(carRaceCollision((3l)) == (9l)); assert(carRaceCollision((4l)) == (16l)); assert(carRaceCollision((8l)) == (64l)); assert(carRaceCollision((10l)) == (100l)); } }
humaneval-HumanEval_104_unique_digits.json-L22
py
from typing import List def unique_digits(x: List[int]) -> List[int]: """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: >>> unique_digits([15, 33, 1422, 1]) [1, 15, 33] >>> unique_digits([152, 323, 1422, 10]) [] """ s=[] for i in x: temp=i while temp: if temp%2==0: s.append(i) break
for i in s: x.remove(i) return sorted(x)
temp=temp//10
def check(candidate): assert candidate([15, 33, 1422, 1]) == [1, 15, 33] assert candidate([152, 323, 1422, 10]) == [] assert candidate([12345, 2033, 111, 151]) == [111, 151] assert candidate([135, 103, 31]) == [31, 135] def test_check(): check(unique_digits) test_check()
humaneval-HumanEval_139_special_factorial.json-L15
py
def special_factorial(n: int) -> int: """The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. """ def factorial(n): if n <= 1:
else: return n * factorial(n-1) if n <= 1: return 1 else: return n * special_factorial(n-1) * factorial(n-1)
return 1
def check(candidate): assert candidate(4) == 288 assert candidate(5) == 34560 assert candidate(7) == 125411328000 assert candidate(1) == 1 def test_check(): check(special_factorial) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L51
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50;
if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
}
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_151_double_the_difference.json-L14
js
//Given an array of numbers, return the sum of squares of the numbers // in the array that are odd. Ignore numbers that are negative or not integers. // >>> double_the_difference([1, 3, 2, 0]) // 10 // >>> double_the_difference([-1, -2, 0]) // 0 // >>> double_the_difference([9, -2]) // 81 // >>> double_the_difference([0]) // 0 // If the input array is empty, return 0. function double_the_difference(lst){ sum = 0;
if(lst[i] % 2 == 1 && lst[i] > 0){ sum += lst[i] ** 2; } } return sum; }
for (var i = 0; i < lst.length; i++){
const assert = require('node:assert'); function test() { let candidate = double_the_difference; assert.deepEqual(candidate([]),0); assert.deepEqual(candidate([5.0, 4.0]),25); assert.deepEqual(candidate([0.1, 0.2, 0.3]),0); assert.deepEqual(candidate([-10.0, -20.0, -30.0]),0); assert.deepEqual(candidate([-1.0, -2.0, 8.0]),0); assert.deepEqual(candidate([0.2, 3.0, 5.0]),34); assert.deepEqual(candidate([-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0]),165); } test();
humaneval-HumanEval_117_select_words.json-L46
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) { ret.add(word);
} return ret; } }
}
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_128_prod_signs.json-L30
py
from typing import List, Optional def prod_signs(arr: List[int]) -> Optional[int]: """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -4]) 9 >>> prod_signs([0, 1]) 0 >>> prod_signs([]) None """ def product(lst: List[int]) -> int: out = 1 for item in lst: out *= item return out if len(arr) == 0: return None else: sign_arr = [] for num in arr: if num > 0:
elif num < 0: sign_arr.append(-1) else: sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
sign_arr.append(1)
def check(candidate): assert candidate([1, 2, 2, -4]) == -9 assert candidate([0, 1]) == 0 assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10 assert candidate([]) == None assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20 assert candidate([-1, 1, -1, 1]) == 4 assert candidate([-1, 1, 1, 1]) == -4 assert candidate([-1, 1, 1, 0]) == 0 def test_check(): check(prod_signs) test_check()
humaneval-HumanEval_99_closest_integer.json-L27
js
//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 // >>> closest_integer("10") // 10 // >>> closest_integer("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 closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){ return Math.floor(value); }else{ return Math.ceil(value); } }else{ if(value - Math.floor(value) > -0.5){ return Math.floor(value); }else{ return Math.ceil(value);
} }
}
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_146_specialFilter.json-L19
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes an array array list of numbers as input and returns // the number of elements in the array array list that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) // (1l) // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) // (2l) public static long specialFilter(ArrayList<Long> nums) { class helper {
long[] digits = getDigits(n); return digits[0]; } public long getLastDigit(long n) { long[] digits = getDigits(n); return digits[digits.length - 1]; } public long[] getDigits(long n) { ArrayList<Long> digits = new ArrayList<Long>(); while (n != 0) { digits.add(n % 10); n /= 10; } Collections.reverse(digits); return digits.stream().mapToLong(i -> i).toArray(); } } helper h = new helper(); return nums.stream().filter(x -> x > 10).filter(x -> { long firstDigit = h.getFirstDigit(x); long lastDigit = h.getLastDigit(x); return firstDigit % 2 != 0 && lastDigit % 2 != 0; }).count(); } }
public long getFirstDigit(long n) {
} public static void main(String[] args) { assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)5l, (long)-2l, (long)1l, (long)-5l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) == (1l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) == (2l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)43l, (long)-12l, (long)93l, (long)125l, (long)121l, (long)109l)))) == (4l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)71l, (long)-2l, (long)-33l, (long)75l, (long)21l, (long)19l)))) == (3l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList()))) == (0l)); } }
humaneval-HumanEval_137_compare_one.json-L23
js
//Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return undefined if the values are equal. // Note: If a real number is represented as a string, the floating point might be . or , // >>> compare_one(1, 2.5) // 2.5 // >>> compare_one(1, "2,3") // "2,3" // >>> compare_one("5,1", "6") // "6" // >>> compare_one("1", 1) // undefined function compare_one(a, b){ if (typeof a === typeof b){ if (a > b) { return a; } else if (a < b) { return b; } else { return undefined; } }
if (a[0] > b){ return a; } else if (a[0] < b){ return b; } else { return undefined; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){ return a; } else if (a < b[0]){ return b; } else { return undefined; } } }
else if (typeof a === "string" && typeof b === "number"){
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_7_filter_by_substring.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Filter an input array list of strings only for ones that contain given substring // >>> filterBySubstring((new ArrayList<String>(Arrays.asList())), ("a")) // (new ArrayList<String>(Arrays.asList())) // >>> filterBySubstring((new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"cde", (String)"array"))), ("a")) // (new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"array"))) public static ArrayList<String> filterBySubstring(ArrayList<String> strings, String substring) { return new ArrayList<String>(strings.stream().filter(s -> s.contains(substring)).collect(Collectors.toList()));
}
}
} public static void main(String[] args) { assert(filterBySubstring((new ArrayList<String>(Arrays.asList())), ("john")).equals((new ArrayList<String>(Arrays.asList())))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"asd", (String)"xxy", (String)"john doe", (String)"xxxAAA", (String)"xxx"))), ("xxx")).equals((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"xxxAAA", (String)"xxx"))))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"asd", (String)"aaaxxy", (String)"john doe", (String)"xxxAAA", (String)"xxx"))), ("xx")).equals((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"aaaxxy", (String)"xxxAAA", (String)"xxx"))))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"grunt", (String)"trumpet", (String)"prune", (String)"gruesome"))), ("run")).equals((new ArrayList<String>(Arrays.asList((String)"grunt", (String)"prune"))))); } }
humaneval-HumanEval_33_sort_third.json-L28
js
//This function takes an array l and returns an array 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. // >>> sort_third([1, 2, 3]) // [1, 2, 3] // >>> sort_third([5, 6, 3, 4, 8, 9, 2]) // [2, 6, 3, 4, 8, 9, 5] function sort_third(l){ let x=[]; let y=[]; let k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ y[k]=l[i]; k=k+1; } else{ x[i]=l[i]; } } y.sort(); k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ x[i]=y[k]; k=k+1; }
return x; }
}
const assert = require('node:assert'); function test() { let candidate = sort_third; assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2]),[2, 6, 3, 4, 8, 9, 5]); assert.deepEqual(candidate([5, 8, 3, 4, 6, 9, 2]),[2, 8, 3, 4, 6, 9, 5]); assert.deepEqual(candidate([5, 6, 9, 4, 8, 3, 2]),[2, 6, 9, 4, 8, 3, 5]); assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2, 1]),[2, 6, 3, 4, 8, 9, 5, 1]); } test();
humaneval-HumanEval_147_get_max_triples.json-L28
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0 j = 1 k = 2 count = 0 while (i < n - 2): while (j < n - 1): while (k < n): if (a[i] + a[j] + a[k]) % 3 == 0: count += 1 k += 1 j += 1 k = j + 1
j = i + 1 k = j + 1 return count
i += 1
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_27_flip_case.json-L14
js
//For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flip_case("Hello") // "hELLO" function flip_case(string){ var result = ""; for(var i = 0; i < string.length; i++){ if(string[i] == string[i].toUpperCase()){ result += string[i].toLowerCase(); }else{ result += string[i].toUpperCase(); } } return result;
}
const assert = require('node:assert'); function test() { let candidate = flip_case; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hello!"),"hELLO!"); assert.deepEqual(candidate("These violent delights have violent ends"),"tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"); } test();
humaneval-HumanEval_17_parse_music.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string representing musical notes in a special ASCII format. // Your task is to parse this string and return array 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")) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l))) public static ArrayList<Long> parseMusic(String music_string) { ArrayList<Long> res = new ArrayList<Long>(); char[] chars = music_string.toCharArray();
if (chars[i] == 'o') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)2l); i += 1; } else { res.add((long)4l); } } else if (chars[i] == '.') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)1l); i += 1; } } } return res; } }
for (int i = 0; i < chars.length; i++) {
} public static void main(String[] args) { assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList())))); assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))); assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l))))); } }
humaneval-HumanEval_68_pluck.json-L37
py
from typing import List def pluck(arr: List[int]) -> List[int]: """ "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: >>> pluck([4, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: >>> pluck([1, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: >>> pluck([]) [] Example 4: >>> pluck([5, 0, 3, 0, 4, 2]) [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 """
return [] evens = [e for e in arr if e % 2 == 0] if len(evens) == 0: return [] return [min(evens), arr.index(min(evens))]
if len(arr) == 0:
def check(candidate): assert candidate([4, 2, 3]) == [2, 1] assert candidate([1, 2, 3]) == [2, 1] assert candidate([]) == [] assert candidate([5, 0, 3, 0, 4, 2]) == [0, 1] assert candidate([1, 2, 3, 0, 5, 3]) == [0, 3] assert candidate([5, 4, 8, 4, 8]) == [4, 1] assert candidate([7, 6, 7, 1]) == [6, 1] assert candidate([7, 9, 7, 1]) == [] def test_check(): check(pluck) test_check()
humaneval-HumanEval_4_mean_absolute_deviation.json-L13
py
from typing import List def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """ mean = sum(numbers) / len(numbers)
return sum(absolute_deviations) / len(absolute_deviations) print(mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]))
absolute_deviations = [abs(x - mean) for x in numbers]
def check(candidate): assert candidate([1.0, 2.0]) == 0.5 assert candidate([1.0, 2.0, 3.0, 4.0]) == 1.0 assert candidate([1.0, 2.0, 3.0, 4.0, 5.0]) == 1.2 def test_check(): check(mean_absolute_deviation) test_check()
humaneval-HumanEval_1_separate_paren_groups.json-L23
js
//Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separate_paren_groups("( ) (( )) (( )( ))") // ["()", "(())", "(()())"] function separate_paren_groups(paren_string){ var count = 0; var group = ''; var groups = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] === '('){ count++; group += paren_string[i]; } else if (paren_string[i] === ')'){ count--; group += paren_string[i]; } if (count === 0 && group){ groups.push(group); group = ''; }
return groups; }
}
const assert = require('node:assert'); function test() { let candidate = separate_paren_groups; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]); assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]); assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]); assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]); } test();
humaneval-HumanEval_17_parse_music.json-L15
js
//Input to this function is a string representing musical notes in a special ASCII format. // Your task is to parse this string and return array 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 // >>> parse_music("o o| .| o| o| .| .| .| .| o o") // [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] function parse_music(music_string){ let songs = music_string.split(' '); let song = []; songs.forEach(s => { if(s === 'o'){
}else if(s === 'o|'){ song.push(2); }else if(s === '.|'){ song.push(1); } }); return song; }
song.push(4);
const assert = require('node:assert'); function test() { let candidate = parse_music; assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("o o o o"),[4, 4, 4, 4]); assert.deepEqual(candidate(".| .| .| .|"),[1, 1, 1, 1]); assert.deepEqual(candidate("o| o| .| .| o o o o"),[2, 2, 1, 1, 4, 4, 4, 4]); assert.deepEqual(candidate("o| .| o| .| o o| o o|"),[2, 1, 2, 1, 4, 2, 4, 2]); } test();
humaneval-HumanEval_21_rescale_to_unit.json-L12
js
//Given array of numbers (of at least two elements), apply a linear transform to that array, // such that the smallest number will become 0 and the largest will become 1 // >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) // [0.0, 0.25, 0.5, 0.75, 1.0] function rescale_to_unit(numbers){ var min = Math.min.apply(Math, numbers); var max = Math.max.apply(Math, numbers); var sub = max - min; var unit = []; for (var i = 0; i < numbers.length; i++) { unit.push((numbers[i] - min) / sub);
return unit; }
}
const assert = require('node:assert'); function test() { let candidate = rescale_to_unit; assert.deepEqual(candidate([2.0, 49.9]),[0.0, 1.0]); assert.deepEqual(candidate([100.0, 49.9]),[1.0, 0.0]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0]),[0.0, 0.25, 0.5, 0.75, 1.0]); assert.deepEqual(candidate([2.0, 1.0, 5.0, 3.0, 4.0]),[0.25, 0.0, 1.0, 0.5, 0.75]); assert.deepEqual(candidate([12.0, 11.0, 15.0, 13.0, 14.0]),[0.25, 0.0, 1.0, 0.5, 0.75]); } test();
humaneval-HumanEval_161_solve.json-L25
js
//You are given a string s. // if s[i] is a letter, reverse its case from lower to upper or vise versa, // otherwise keep it as it is. // If the string contains no letters, reverse the string. // The function should return the resulted string. // Examples // >>> solve("1234") // "4321" // >>> solve("ab") // "AB" // >>> solve("#a@C") // "#A@c" function solve(s){ let letters = s.match(/[a-z]/ig); if(letters) { const swapped = s.split('').map(char => { if(/[a-z]/i.test(char)) { return char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase(); } return char; }); return swapped.join('');
return s.split('').reverse().join(''); }
}
const assert = require('node:assert'); function test() { let candidate = solve; assert.deepEqual(candidate("AsDf"),"aSdF"); assert.deepEqual(candidate("1234"),"4321"); assert.deepEqual(candidate("ab"),"AB"); assert.deepEqual(candidate("#a@C"),"#A@c"); assert.deepEqual(candidate("#AsdfW^45"),"#aSDFw^45"); assert.deepEqual(candidate("#6@2"),"2@6#"); assert.deepEqual(candidate("#$a^D"),"#$A^d"); assert.deepEqual(candidate("#ccc"),"#CCC"); } test();
humaneval-HumanEval_19_sort_numbers.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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") public static String sortNumbers(String numbers) { String [] nums = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; HashMap<String, Integer> indexMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { indexMap.put(nums[i], i); } String [] split = numbers.split(" "); Arrays.sort(split, new Comparator<String>() { @Override public int compare(String s1, String s2) { return indexMap.get(s1) - indexMap.get(s2);
}); return String.join(" ", split); } }
}
} public static void main(String[] args) { assert(sortNumbers(("")).equals((""))); assert(sortNumbers(("three")).equals(("three"))); assert(sortNumbers(("three five nine")).equals(("three five nine"))); assert(sortNumbers(("five zero four seven nine eight")).equals(("zero four five seven eight nine"))); assert(sortNumbers(("six five four three two one zero")).equals(("zero one two three four five six"))); } }
humaneval-HumanEval_120_maximum.json-L21
js
//Given an array arr of integers and a positive integer k, return a sorted array // of length k with the maximum k numbers in arr. // Example 1: // >>> maximum([-3, -4, 5], 3) // [-4, -3, 5] // Example 2: // >>> maximum([4, -4, 4], 2) // [4, 4] // Example 3: // >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1) // [2] // Note: // 1. The length of the array will be in the range of [1, 1000]. // 2. The elements in the array will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) function maximum(arr, k){ var len = arr.length; if(len === 0) return null; if(len === 1) return arr; return arr.sort((a, b) => a - b).slice(len - k);
}
const assert = require('node:assert'); function test() { let candidate = maximum; assert.deepEqual(candidate([-3, -4, 5], 3),[-4, -3, 5]); assert.deepEqual(candidate([4, -4, 4], 2),[4, 4]); assert.deepEqual(candidate([-3, 2, 1, 2, -1, -2, 1], 1),[2]); assert.deepEqual(candidate([123, -123, 20, 0, 1, 2, -3], 3),[2, 20, 123]); assert.deepEqual(candidate([-123, 20, 0, 1, 2, -3], 4),[0, 1, 2, 20]); assert.deepEqual(candidate([5, 15, 0, 3, -13, -8, 0], 7),[-13, -8, 0, 0, 3, 5, 15]); assert.deepEqual(candidate([-1, 0, 2, 5, 3, -10], 2),[3, 5]); assert.deepEqual(candidate([1, 0, 5, -7], 1),[5]); assert.deepEqual(candidate([4, -4], 2),[-4, 4]); assert.deepEqual(candidate([-10, 10], 2),[-10, 10]); assert.deepEqual(candidate([1, 2, 3, -23, 243, -400, 0], 0),[]); } test();
humaneval-HumanEval_65_circular_shift.json-L14
py
def circular_shift(x: int, shift: int) -> str: """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. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12' """ temp = list(str(x)) if shift > len(temp): return ''.join(reversed(temp)) else:
return ''.join(temp[-shift:] + temp[:-shift])
def check(candidate): assert candidate(100, 2) == '001' assert candidate(12, 2) == '12' assert candidate(97, 8) == '79' assert candidate(12, 1) == '21' assert candidate(11, 101) == '11' def test_check(): check(circular_shift) test_check()
humaneval-HumanEval_34_unique.json-L7
js
//Return sorted unique elements in an array // >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123]) // [0, 2, 3, 5, 9, 123] function unique(l){ return l.filter(function(e, i, a){ return a.indexOf(e) === i;
}
}).sort(function(a, b){return a-b});
const assert = require('node:assert'); function test() { let candidate = unique; assert.deepEqual(candidate([5, 3, 5, 2, 3, 3, 9, 0, 123]),[0, 2, 3, 5, 9, 123]); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L12
py
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ paren_string = paren_string.replace(' ', '')
group = '' open_count = 0 for c in paren_string: if c == '(': open_count += 1 elif c == ')': open_count -= 1 group += c if open_count == 0: groups.append(group) group = '' return groups
groups = []
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())'] assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))'] assert candidate('(()(())((())))') == ['(()(())((())))'] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())'] def test_check(): check(separate_paren_groups) test_check()
humaneval-HumanEval_152_compare.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two array array lists of scores and guesses of equal length, where each index shows a match. // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))) // >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l))) public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) {
for (int i = 0; i < game.size(); i++) { if (game.get(i) != guess.get(i)) { result.add(Math.abs(game.get(i) - guess.get(i))); } else { result.add((long)0); } } return result; } }
ArrayList<Long> result = new ArrayList<Long>();
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_57_monotonic.json-L9
js
//Return true is array elements are monotonically increasing or decreasing. // >>> monotonic([1, 2, 4, 20]) // true // >>> monotonic([1, 20, 4, 10]) // false // >>> monotonic([4, 1, 0, -10]) // true function monotonic(l){
return true; } if(l[0] < l[1]){ for(var i = 1; i < l.length - 1; i++){ if(l[i] > l[i + 1]){ return false; } } } else{ for(var i = 1; i < l.length - 1; i++){ if(l[i] < l[i + 1]){ return false; } } } return true; }
if(l.length <= 1){
const assert = require('node:assert'); function test() { let candidate = monotonic; assert.deepEqual(candidate([1, 2, 4, 10]),true); assert.deepEqual(candidate([1, 2, 4, 20]),true); assert.deepEqual(candidate([1, 20, 4, 10]),false); assert.deepEqual(candidate([4, 1, 0, -10]),true); assert.deepEqual(candidate([4, 1, 1, 0]),true); assert.deepEqual(candidate([1, 2, 3, 2, 5, 60]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 60]),true); assert.deepEqual(candidate([9, 9, 9, 9]),true); } test();
humaneval-HumanEval_129_minPath.json-L44
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; } } } let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){
x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
if(grid[i][j] === currCell){
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_99_closest_integer.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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")) // (10l) // >>> closestInteger(("15.3")) // (15l) // 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 closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. public static long closestInteger(String value) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP); return bd.longValue();
}
}
} public static void main(String[] args) { assert(closestInteger(("10")) == (10l)); assert(closestInteger(("14.5")) == (15l)); assert(closestInteger(("-15.5")) == (-16l)); assert(closestInteger(("15.3")) == (15l)); assert(closestInteger(("0")) == (0l)); } }
humaneval-HumanEval_113_odd_count.json-L18
py
from typing import List def odd_count(lst: List[str]) -> List[str]: """Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count(['1234567']) ['the number of odd elements 4n the str4ng 4 of the 4nput.'] >>> odd_count(['3', '11111111']) ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.'] """ output = [] for i in range(len(lst)): count = 0 for j in range(len(lst[i])):
count += 1 output.append(f"the number of odd elements {count}n the str{count}ng {count} of the {count}nput.") return output
if int(lst[i][j]) % 2 != 0:
def check(candidate): assert candidate(['1234567']) == ['the number of odd elements 4n the str4ng 4 of the 4nput.'] assert candidate(['3', '11111111']) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.'] assert candidate(['271', '137', '314']) == ['the number of odd elements 2n the str2ng 2 of the 2nput.', 'the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.'] def test_check(): check(odd_count) test_check()
humaneval-HumanEval_109_move_one_ball.json-L37
js
//We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array will be randomly ordered. Your task is to determine if // it is possible to get an array sorted in non-decreasing order by performing // the following operation on the given array: // You are allowed to perform right shift operation any number of times. // One right shift operation means shifting all elements of the array by one // position in the right direction. The last element of the array will be moved to // the starting position in the array i.e. 0th index. // If it is possible to obtain the sorted array by performing the above operation // then return true else return false. // If the given array is empty then return true. // Note: The given array is guaranteed to have unique elements. // For Example: // >>> move_one_ball([3, 4, 5, 1, 2]) // true // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array. // >>> move_one_ball([3, 5, 4, 1, 2]) // false // Explanation:It is not possible to get non-decreasing order for the given // array by performing any number of right shift operations. function move_one_ball(arr){ var diff_count = 0; var i = 0; var temp = 0; for(var i = 0; i < arr.length - 1; i++){ if(arr[i] > arr[i + 1]){ diff_count += 1; } } if(diff_count > 1){ return false; } else{ return true; }
}
const assert = require('node:assert'); function test() { let candidate = move_one_ball; assert.deepEqual(candidate([3, 4, 5, 1, 2]),true); assert.deepEqual(candidate([3, 5, 10, 1, 2]),true); assert.deepEqual(candidate([4, 3, 1, 2]),false); assert.deepEqual(candidate([3, 5, 4, 1, 2]),false); assert.deepEqual(candidate([]),true); } test();
humaneval-HumanEval_73_smallest_change.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list arr of integers, find the minimum number of elements that // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that // is read the same backwards and forwards. In one change, you can change one element to any other element. // For example: // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) // (4l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) // (1l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) // (0l) public static long smallestChange(ArrayList<Long> arr) { int first = 0; int last = arr.size() - 1; int count = 0; while (first < last) {
count++; } first++; last--; } return count; } }
if (arr.get(first) != arr.get(last)) {
} public static void main(String[] args) { assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) == (4l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)1l, (long)3l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); } }
humaneval-HumanEval_90_next_smallest.json-L27
js
//You are given an array of integers. // Write a function next_smallest() that returns the 2nd smallest element of the array. // Return undefined if there is no such element. // >>> next_smallest([1, 2, 3, 4, 5]) // 2 // >>> next_smallest([5, 1, 4, 3, 2]) // 2 // >>> next_smallest([]) // undefined // >>> next_smallest([1, 1]) // undefined function next_smallest(lst){ if(lst.length<=1){ return undefined; } var smallest=Math.min(...lst); var second_smallest=Number.MAX_VALUE; for(var i in lst){ if(lst[i]>smallest&&lst[i]<second_smallest){ second_smallest=lst[i]; } } if(second_smallest==Number.MAX_VALUE){ return undefined; } return second_smallest;
}
const assert = require('node:assert'); function test() { let candidate = next_smallest; assert.deepEqual(candidate([1, 2, 3, 4, 5]),2); assert.deepEqual(candidate([5, 1, 4, 3, 2]),2); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([1, 1, 1, 1, 0]),1); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([-35, 34, 12, -45]),-35); } test();
humaneval-HumanEval_139_special_factorial.json-L10
js
//The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // For example: // >>> special_factorial(4) // 288 // The function will receive an integer as input and should return the special // factorial of this integer. function special_factorial(n){
let fact = 1; for (let i = 1; i <= n; i++) { fact *= i; } return fact * special_factorial(n - 1); } else { return 1; } }
if (n > 0) {
const assert = require('node:assert'); function test() { let candidate = special_factorial; assert.deepEqual(candidate(4),288); assert.deepEqual(candidate(5),34560); assert.deepEqual(candidate(7),125411328000); assert.deepEqual(candidate(1),1); } test();
humaneval-HumanEval_143_words_in_sentence.json-L39
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> wordsInSentence(("This is a test")) // ("is") // Example 2: // >>> wordsInSentence(("lets go for swimming")) // ("go for") // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters public static String wordsInSentence(String sentence) { StringBuilder ans = new StringBuilder(); String[] words = sentence.split(" "); int[] 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}; boolean isPrime; for (String word : words) { isPrime = false; for (int prime : primes) { if (word.length() == prime) { isPrime = true; break; } } if (isPrime) { ans.append(word + " "); }
if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
}
} public static void main(String[] args) { assert(wordsInSentence(("This is a test")).equals(("is"))); assert(wordsInSentence(("lets go for swimming")).equals(("go for"))); assert(wordsInSentence(("there is no place available here")).equals(("there is no place"))); assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein"))); assert(wordsInSentence(("go for it")).equals(("go for it"))); assert(wordsInSentence(("here")).equals((""))); assert(wordsInSentence(("here is")).equals(("is"))); } }
humaneval-HumanEval_111_histogram.json-L22
js
//Given a string representing a space separated lowercase letters, return an object // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram("a b c") // {"a": 1, "b": 1, "c": 1} // >>> histogram("a b b a") // {"a": 2, "b": 2} // >>> histogram("a b c a b") // {"a": 2, "b": 2} // >>> histogram("b b b b a") // {"b": 4} // >>> histogram("") // {} function histogram(test){ if (test.length === 0){ return {}; } var lst = test.split(" "); var count = {}; for (var i = 0; i < lst.length; i++){
count[lst[i]] += 1; } else{ count[lst[i]] = 1; } } console.log(count); var max = 0; var result = {}; for (var key in count){ if (count[key] > max){ max = count[key]; result = {}; result[key] = max; } else if (count[key] === max){ result[key] = max; } } return result; }
if (count[lst[i]]){
const assert = require('node:assert'); function test() { let candidate = histogram; assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate("b b b b a"),{"b": 4}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate(""),{}); assert.deepEqual(candidate("a"),{"a": 1}); } test();
humaneval-HumanEval_56_correct_bracketing.json-L15
py
def correct_bracketing(brackets: str) -> bool: """ brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('<') False >>> correct_bracketing('<>') True >>> correct_bracketing('<<><>>') True >>> correct_bracketing('><<>') False """ num_left_brackets = 0
if bracket == '<': num_left_brackets += 1 elif bracket == '>': num_left_brackets -= 1 if num_left_brackets < 0: return False return num_left_brackets == 0
for bracket in brackets:
def check(candidate): assert candidate('<>') == True assert candidate('<<><>>') == True assert candidate('<><><<><>><>') == True assert candidate('<><><<<><><>><>><<><><<>>>') == True assert candidate('<<<><>>>>') == False assert candidate('><<>') == False assert candidate('<') == False assert candidate('<<<<') == False assert candidate('>') == False assert candidate('<<>') == False assert candidate('<><><<><>><>><<>') == False assert candidate('<><><<><>><>>><>') == False def test_check(): check(correct_bracketing) test_check()
humaneval-HumanEval_42_incr_list.json-L18
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return array list with elements incremented by 1. // >>> incrList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l))) // >>> incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))) // (new ArrayList<Long>(Arrays.asList((long)6l, (long)4l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))) public static ArrayList<Long> incrList(ArrayList<Long> l) { for (int i = 0; i < l.size(); i++) { l.set(i, l.get(i) + 1l); }
} }
return l;
} public static void main(String[] args) { assert(incrList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l))))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)2l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)3l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))))); } }
humaneval-HumanEval_47_median.json-L13
js
//Return median of elements in the array l. // >>> median([3, 1, 2, 4, 5]) // 3 // >>> median([-10, 4, 6, 1000, 10, 20]) // 15.0 function median(l){ let middle = Math.floor(l.length / 2); let sorted = l.sort((a, b) => a - b); if (l.length % 2 === 0) { return (sorted[middle - 1] + sorted[middle]) / 2; } else { return sorted[middle];
}
}
const assert = require('node:assert'); function test() { let candidate = median; assert.deepEqual(candidate([3, 1, 2, 4, 5]),3); assert.deepEqual(candidate([-10, 4, 6, 1000, 10, 20]),8.0); assert.deepEqual(candidate([5]),5); assert.deepEqual(candidate([6, 5]),5.5); assert.deepEqual(candidate([8, 1, 3, 9, 9, 2, 7]),7); } test();
humaneval-HumanEval_119_match_parens.json-L17
js
//You are given an array of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> match_parens(["()(", ")"]) // "Yes" // >>> match_parens([")", ")"]) // "No" function match_parens(lst){ const open = '('; const close = ')';
let stack = []; for (let p of s){ if (p === open){ stack.push(p); } else if (p === close){ if (stack.length === 0){ return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
const is_good = (s) => {
const assert = require('node:assert'); function test() { let candidate = match_parens; assert.deepEqual(candidate(["()(", ")"]),"Yes"); assert.deepEqual(candidate([")", ")"]),"No"); assert.deepEqual(candidate(["(()(())", "())())"]),"No"); assert.deepEqual(candidate([")())", "(()()("]),"Yes"); assert.deepEqual(candidate(["(())))", "(()())(("]),"Yes"); assert.deepEqual(candidate(["()", "())"]),"No"); assert.deepEqual(candidate(["(()(", "()))()"]),"Yes"); assert.deepEqual(candidate(["((((", "((())"]),"No"); assert.deepEqual(candidate([")(()", "(()("]),"No"); assert.deepEqual(candidate([")(", ")("]),"No"); assert.deepEqual(candidate(["(", ")"]),"Yes"); assert.deepEqual(candidate([")", "("]),"Yes"); } test();
humaneval-HumanEval_19_sort_numbers.json-L8
py
def sort_numbers(numbers: str) -> str: """ 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 >>> sort_numbers('three one five') 'one three five' """
res = '' mapper = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} for word in sorted(words, key=lambda x: mapper[x]): res += ' ' + word return res.strip()
words = numbers.split()
def check(candidate): assert candidate('') == '' assert candidate('three') == 'three' assert candidate('three five nine') == 'three five nine' assert candidate('five zero four seven nine eight') == 'zero four five seven eight nine' assert candidate('six five four three two one zero') == 'zero one two three four five six' def test_check(): check(sort_numbers) test_check()
humaneval-HumanEval_26_remove_duplicates.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // From an array array list of integers, remove all elements that occur more than once. // Keep order of elements left the same as in the input. // >>> removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)4l))) public static ArrayList<Long> removeDuplicates(ArrayList<Long> numbers) { HashMap<Long, Long> hashmap = new HashMap<Long, Long>(); for (int i = 0; i < numbers.size(); i++) {
if (hashmap.containsKey(key)) { hashmap.put(key, hashmap.get(key) + 1); } else { hashmap.put(key, 1L); } } ArrayList<Long> out = new ArrayList<Long>(); for (int i = 0; i < numbers.size(); i++) { Long key = numbers.get(i); if (hashmap.get(key) == 1) { out.add(key); } } return out; } }
Long key = numbers.get(i);
} public static void main(String[] args) { assert(removeDuplicates((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l, (long)3l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)5l))))); } }
humaneval-HumanEval_119_match_parens.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given an array array list of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))) // ("Yes") // >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))) // ("No") public static String matchParens(ArrayList<String> lst) { String s1 = lst.get(0); String s2 = lst.get(1); String s3 = s1+s2; String s4 = s2+s1; int c1 = 0; int c2 = 0; for (int i = 0; i < s3.length(); i++) { if (s3.charAt(i) == '(') c1 += 1;
if (c1 < 0) break; } for (int i = 0; i < s4.length(); i++) { if (s4.charAt(i) == '(') c2 += 1; else c2 -= 1; if (c2 < 0) break; } if (c1 == 0 || c2 == 0) return "Yes"; else return "No"; } }
else c1 -= 1;
} public static void main(String[] args) { assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes"))); } }
humaneval-HumanEval_96_count_up_to.json-L21
js
//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: // >>> count_up_to(5) // [2, 3] // >>> count_up_to(11) // [2, 3, 5, 7] // >>> count_up_to(0) // [] // >>> count_up_to(20) // [2, 3, 5, 7, 11, 13, 17, 19] // >>> count_up_to(1) // [] // >>> count_up_to(18) // [2, 3, 5, 7, 11, 13, 17] function count_up_to(n){ if (n < 2) return []; var output = [2]; for (var i = 3; i < n; i += 2){ var prime = true;
if (i % j === 0){ prime = false; break; } } if (prime) output.push(i); } return output; }
for (var j = 3; j < i; j += 2){
const assert = require('node:assert'); function test() { let candidate = count_up_to; assert.deepEqual(candidate(5),[2, 3]); assert.deepEqual(candidate(6),[2, 3, 5]); assert.deepEqual(candidate(7),[2, 3, 5]); assert.deepEqual(candidate(10),[2, 3, 5, 7]); assert.deepEqual(candidate(0),[]); assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]); assert.deepEqual(candidate(1),[]); assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]); assert.deepEqual(candidate(101),[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]); } test();
humaneval-HumanEval_128_prod_signs.json-L28
py
from typing import List, Optional def prod_signs(arr: List[int]) -> Optional[int]: """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -4]) 9 >>> prod_signs([0, 1]) 0 >>> prod_signs([]) None """ def product(lst: List[int]) -> int: out = 1 for item in lst: out *= item return out if len(arr) == 0: return None else: sign_arr = []
if num > 0: sign_arr.append(1) elif num < 0: sign_arr.append(-1) else: sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
for num in arr:
def check(candidate): assert candidate([1, 2, 2, -4]) == -9 assert candidate([0, 1]) == 0 assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10 assert candidate([]) == None assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20 assert candidate([-1, 1, -1, 1]) == 4 assert candidate([-1, 1, 1, 1]) == -4 assert candidate([-1, 1, 1, 0]) == 0 def test_check(): check(prod_signs) test_check()
humaneval-HumanEval_124_valid_date.json-L37
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 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. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){ return false; } }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; }
}
return false;
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_147_get_max_triples.json-L23
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0 j = 1 k = 2 count = 0 while (i < n - 2): while (j < n - 1): while (k < n):
count += 1 k += 1 j += 1 k = j + 1 i += 1 j = i + 1 k = j + 1 return count
if (a[i] + a[j] + a[k]) % 3 == 0:
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_65_circular_shift.json-L13
js
//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. // >>> circular_shift(12, 1) // "21" // >>> circular_shift(12, 2) // "12" function circular_shift(x, shift){ var str = x.toString(); var len = str.length; var res = ''; if(len < shift){
res += str[i]; } }else{ res = str.substring(len-shift) + str.substring(0, len-shift); } return res; }
for(var i = len-1; i >= 0; i--){
const assert = require('node:assert'); function test() { let candidate = circular_shift; assert.deepEqual(candidate(100, 2),"001"); assert.deepEqual(candidate(12, 2),"12"); assert.deepEqual(candidate(97, 8),"79"); assert.deepEqual(candidate(12, 1),"21"); assert.deepEqual(candidate(11, 101),"11"); } test();
humaneval-HumanEval_47_median.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return median of elements in the array list l. // >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) // (float)3l // >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) // (15.0f) public static float median(ArrayList<Long> l) { float ret = 0; Collections.sort(l); int size = l.size(); if (size % 2 == 0) { ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f;
ret = l.get(size / 2); } return ret; } }
} else {
} public static void main(String[] args) { assert(median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) == (float)3l); assert(median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) == (8.0f)); assert(median((new ArrayList<Long>(Arrays.asList((long)5l)))) == (float)5l); assert(median((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l)))) == (5.5f)); assert(median((new ArrayList<Long>(Arrays.asList((long)8l, (long)1l, (long)3l, (long)9l, (long)9l, (long)2l, (long)7l)))) == (float)7l); } }
humaneval-HumanEval_123_get_odd_collatz.json-L35
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // 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. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) } if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){
return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
odd_numbers.sort(function(a, b){return a-b})
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_121_solution.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a non-empty array list of integers, return the sum of all of the odd elements that are in even positions. // Examples // >>> solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) // (12l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) // (9l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) // (0l) public static long solution(ArrayList<Long> lst) { long sum = 0; for (int i = 0; i < lst.size(); i++) { if (i % 2 == 0 && lst.get(i) % 2 == 1) { sum += lst.get(i); } } return sum;
}
}
} public static void main(String[] args) { assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) == (12l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) == (9l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l)))) == (5l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)23l, (long)32l)))) == (23l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)13l, (long)2l, (long)9l)))) == (3l)); } }
humaneval-HumanEval_67_fruit_distribution.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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"), (19l)) // (8l) // >>> fruitDistribution(("0 apples and 1 oranges"), (3l)) // (2l) // >>> fruitDistribution(("2 apples and 3 oranges"), (100l)) // (95l) // >>> fruitDistribution(("100 apples and 1 oranges"), (120l)) // (19l) public static long fruitDistribution(String s, long n) { String[] splitted = s.split(" ");
long oranges = Long.parseLong(splitted[3]); return n - apples - oranges; } }
long apples = Long.parseLong(splitted[0]);
} public static void main(String[] args) { assert(fruitDistribution(("5 apples and 6 oranges"), (19l)) == (8l)); assert(fruitDistribution(("5 apples and 6 oranges"), (21l)) == (10l)); assert(fruitDistribution(("0 apples and 1 oranges"), (3l)) == (2l)); assert(fruitDistribution(("1 apples and 0 oranges"), (3l)) == (2l)); assert(fruitDistribution(("2 apples and 3 oranges"), (100l)) == (95l)); assert(fruitDistribution(("2 apples and 3 oranges"), (5l)) == (0l)); assert(fruitDistribution(("1 apples and 100 oranges"), (120l)) == (19l)); } }
humaneval-HumanEval_68_pluck.json-L30
js
//"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 an array, [ smalest_value, its index ], // If there are no even values or the given array is empty, return []. // Example 1: // >>> pluck([4, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck([1, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck([]) // [] // Example 4: // >>> pluck([5, 0, 3, 0, 4, 2]) // [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 function pluck(arr){ let result = [], index = -1; for(let i = 0; i < arr.length; i++){
if(result.length === 0 || result[0] > arr[i]){ result = [arr[i], i]; } } } return result; }
if(arr[i] % 2 === 0){
const assert = require('node:assert'); function test() { let candidate = pluck; assert.deepEqual(candidate([4, 2, 3]),[2, 1]); assert.deepEqual(candidate([1, 2, 3]),[2, 1]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5, 0, 3, 0, 4, 2]),[0, 1]); assert.deepEqual(candidate([1, 2, 3, 0, 5, 3]),[0, 3]); assert.deepEqual(candidate([5, 4, 8, 4, 8]),[4, 1]); assert.deepEqual(candidate([7, 6, 7, 1]),[6, 1]); assert.deepEqual(candidate([7, 9, 7, 1]),[]); } test();
humaneval-HumanEval_12_longest.json-L17
py
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) None >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """ if not strings: return None else: long = strings[0]
if len(s) > len(long): long = s return long
for s in strings:
def check(candidate): assert candidate([]) == None assert candidate(['x', 'y', 'z']) == 'x' assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz' def test_check(): check(longest) test_check()
humaneval-HumanEval_146_specialFilter.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes an array array list of numbers as input and returns // the number of elements in the array array list that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) // (1l) // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) // (2l) public static long specialFilter(ArrayList<Long> nums) { class helper { public long getFirstDigit(long n) { long[] digits = getDigits(n); return digits[0]; } public long getLastDigit(long n) { long[] digits = getDigits(n); return digits[digits.length - 1];
public long[] getDigits(long n) { ArrayList<Long> digits = new ArrayList<Long>(); while (n != 0) { digits.add(n % 10); n /= 10; } Collections.reverse(digits); return digits.stream().mapToLong(i -> i).toArray(); } } helper h = new helper(); return nums.stream().filter(x -> x > 10).filter(x -> { long firstDigit = h.getFirstDigit(x); long lastDigit = h.getLastDigit(x); return firstDigit % 2 != 0 && lastDigit % 2 != 0; }).count(); } }
}
} public static void main(String[] args) { assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)5l, (long)-2l, (long)1l, (long)-5l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) == (1l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) == (2l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)43l, (long)-12l, (long)93l, (long)125l, (long)121l, (long)109l)))) == (4l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)71l, (long)-2l, (long)-33l, (long)75l, (long)21l, (long)19l)))) == (3l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList()))) == (0l)); } }
humaneval-HumanEval_137_compare_one.json-L74
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.')
return a elif float(a_tmp) < b: return b
if float(a_tmp) > b:
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_111_histogram.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string representing a space separated lowercase letters, return a hash map // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram(("a b c")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) {
if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" "); for (String sss : ss) { if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; } }
HashMap<String,Long> s = new HashMap<String,Long>();
} public static void main(String[] args) { assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("")).equals((new HashMap<String,Long>()))); assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l))))); } }
humaneval-HumanEval_66_digitSum.json-L24
js
//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 function digitSum(s){ var sum = 0; for(var i = 0; i < s.length; i++){ if(s[i] >= 'A' && s[i] <= 'Z'){ sum += s.charCodeAt(i); } }
}
return sum;
const assert = require('node:assert'); function test() { let candidate = digitSum; assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("abAB"),131); assert.deepEqual(candidate("abcCd"),67); assert.deepEqual(candidate("helloE"),69); assert.deepEqual(candidate("woArBld"),131); assert.deepEqual(candidate("aAaaaXa"),153); assert.deepEqual(candidate(" How are yOu?"),151); assert.deepEqual(candidate("You arE Very Smart"),327); } test();
humaneval-HumanEval_127_intersection.json-L24
js
//You are given two intervals, // where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). // The given intervals are closed which means that the interval (start, end) // includes both start and end. // For each given interval, it is assumed that its start is less or equal its end. // Your task is to determine whether the length of intersection of these two // intervals is a prime number. // Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) // which its length is 1, which not a prime number. // If the length of the intersection is a prime number, return "YES", // otherwise, return "NO". // If the two intervals don't intersect, return "NO". // [input/output] samples: // >>> intersection([1, 2], [2, 3]) // "NO" // >>> intersection([-1, 1], [0, 4]) // "NO" // >>> intersection([-3, -1], [-5, 5]) // "YES" function intersection(interval1, interval2){ let start = Math.max(interval1[0], interval2[0]); let end = Math.min(interval1[1], interval2[1]); if (start >= end) {
} let length = end - start; 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]; return primes.includes(length) ? "YES" : "NO"; }
return "NO";
const assert = require('node:assert'); function test() { let candidate = intersection; assert.deepEqual(candidate([1, 2], [2, 3]),"NO"); assert.deepEqual(candidate([-1, 1], [0, 4]),"NO"); assert.deepEqual(candidate([-3, -1], [-5, 5]),"YES"); assert.deepEqual(candidate([-2, 2], [-4, 0]),"YES"); assert.deepEqual(candidate([-11, 2], [-1, -1]),"NO"); assert.deepEqual(candidate([1, 2], [3, 5]),"NO"); assert.deepEqual(candidate([1, 2], [1, 2]),"NO"); assert.deepEqual(candidate([-2, -2], [-3, -2]),"NO"); } test();
humaneval-HumanEval_128_prod_signs.json-L25
py
from typing import List, Optional def prod_signs(arr: List[int]) -> Optional[int]: """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -4]) 9 >>> prod_signs([0, 1]) 0 >>> prod_signs([]) None """ def product(lst: List[int]) -> int: out = 1 for item in lst: out *= item return out if len(arr) == 0:
else: sign_arr = [] for num in arr: if num > 0: sign_arr.append(1) elif num < 0: sign_arr.append(-1) else: sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
return None
def check(candidate): assert candidate([1, 2, 2, -4]) == -9 assert candidate([0, 1]) == 0 assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10 assert candidate([]) == None assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20 assert candidate([-1, 1, -1, 1]) == 4 assert candidate([-1, 1, 1, 1]) == -4 assert candidate([-1, 1, 1, 0]) == 0 def test_check(): check(prod_signs) test_check()
humaneval-HumanEval_10_make_palindrome.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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") public static String makePalindrome(String string) { StringBuilder newString = new StringBuilder(string); String reverse = new StringBuilder(string).reverse().toString(); for (int index = 0; index < string.length(); index++) {
newString.append(reverse.substring(string.length() - index)); break; } } return newString.toString(); } }
if (string.substring(index).equals(reverse.substring(0, string.length() - index))) {
} public static void main(String[] args) { assert(makePalindrome(("")).equals((""))); assert(makePalindrome(("x")).equals(("x"))); assert(makePalindrome(("xyz")).equals(("xyzyx"))); assert(makePalindrome(("xyx")).equals(("xyx"))); assert(makePalindrome(("jerry")).equals(("jerryrrej"))); } }
humaneval-HumanEval_61_correct_bracketing.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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) public static boolean correctBracketing(String brackets) { int balance = 0; for (int i = 0; i < brackets.length(); i++) { if (brackets.charAt(i) == '(') { balance++; } else {
} if (balance < 0) { return false; } } return balance == 0; } }
balance--;
} public static void main(String[] args) { assert(correctBracketing(("()")) == (true)); assert(correctBracketing(("(()())")) == (true)); assert(correctBracketing(("()()(()())()")) == (true)); assert(correctBracketing(("()()((()()())())(()()(()))")) == (true)); assert(correctBracketing(("((()())))")) == (false)); assert(correctBracketing((")(()")) == (false)); assert(correctBracketing(("(")) == (false)); assert(correctBracketing(("((((")) == (false)); assert(correctBracketing((")")) == (false)); assert(correctBracketing(("(()")) == (false)); assert(correctBracketing(("()()(()())())(()")) == (false)); assert(correctBracketing(("()()(()())()))()")) == (false)); } }
humaneval-HumanEval_129_minPath.json-L34
py
from typing import List def minPath(grid: List[List[int]], k: int) -> List[int]: """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) [1, 2, 1] >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) [1] """ min_val = float('inf') for i in range(len(grid)):
if grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path = [min_val] while len(path) < k: min_val = float('inf') for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path.append(min_val) return path
for j in range(len(grid[0])):
def check(candidate): assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3] def test_check(): check(minPath) test_check()
humaneval-HumanEval_148_bf.json-L27
py
from typing import Tuple def bf(planet1: str, planet2: str) -> Tuple[str, ...]: """ There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty tuple if planet1 or planet2 are not correct planet names. Examples >>> bf('Jupiter', 'Neptune') ('Saturn', 'Uranus') >>> bf('Earth', 'Mercury') 'Venus' >>> bf('Mercury', 'Uranus') ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') """ planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune') if planet1 not in planets or planet2 not in planets: return () start = planets.index(planet1) end = planets.index(planet2)
planets = planets[start+1:end] else: planets = planets[end+1:start] return tuple(planets)
if start < end:
def check(candidate): assert candidate('Jupiter', 'Neptune') == ('Saturn', 'Uranus') assert candidate('Earth', 'Mercury') == ('Venus',) assert candidate('Mercury', 'Uranus') == ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') assert candidate('Neptune', 'Venus') == ('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus') assert candidate('Earth', 'Earth') == () assert candidate('Mars', 'Earth') == () assert candidate('Jupiter', 'Makemake') == () def test_check(): check(bf) test_check()
humaneval-HumanEval_141_file_name_check.json-L31
py
def file_name_check(file_name: str) -> str: """Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and returns 'No' otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] Examples: >>> file_name_check('example.txt') 'Yes' >>> file_name_check('1example.dll') 'No' """ if not file_name: return 'No' s_count = 0 e_count = 0 for i in file_name: if i.isdigit(): s_count += 1 if i == '.': e_count += 1 if s_count > 3 or e_count != 1: return 'No' s_name = file_name.split('.')[0] e_name = file_name.split('.')[1] if not s_name or not e_name or not s_name[0].isalpha():
if e_name not in ['txt', 'exe', 'dll']: return 'No' return 'Yes'
return 'No'
def check(candidate): assert candidate('example.txt') == 'Yes' assert candidate('1example.dll') == 'No' assert candidate('s1sdf3.asd') == 'No' assert candidate('K.dll') == 'Yes' assert candidate('MY16FILE3.exe') == 'Yes' assert candidate('His12FILE94.exe') == 'No' assert candidate('_Y.txt') == 'No' assert candidate('?aREYA.exe') == 'No' assert candidate('/this_is_valid.dll') == 'No' assert candidate('this_is_valid.wow') == 'No' assert candidate('this_is_valid.txt') == 'Yes' assert candidate('this_is_valid.txtexe') == 'No' assert candidate('#this2_i4s_5valid.ten') == 'No' assert candidate('@this1_is6_valid.exe') == 'No' assert candidate('this_is_12valid.6exe4.txt') == 'No' assert candidate('all.exe.txt') == 'No' assert candidate('I563_No.exe') == 'Yes' assert candidate('Is3youfault.txt') == 'Yes' assert candidate('no_one#knows.dll') == 'Yes' assert candidate('1I563_Yes3.exe') == 'No' assert candidate('I563_Yes3.txtt') == 'No' assert candidate('final..txt') == 'No' assert candidate('final132') == 'No' assert candidate('_f4indsartal132.') == 'No' assert candidate('.txt') == 'No' assert candidate('s.') == 'No' def test_check(): check(file_name_check) test_check()
humaneval-HumanEval_123_get_odd_collatz.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array list sorted in increasing order. // For example: // 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. // >>> getOddCollatz((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l))) public static ArrayList<Long> getOddCollatz(long n) { if (n <= 0) return new ArrayList<Long>(); HashSet<Long> odds = new HashSet<Long>(); long n1 = n; while (n1 > 1) { if (n1 % 2 == 1) odds.add(n1); n1 = n1 % 2 == 0 ? n1 / 2 : 3 * n1 + 1; } odds.add(1l); Long[] odds_arr = odds.toArray(new Long[odds.size()]); ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr)); Collections.sort(ans); return ans;
}
}
} public static void main(String[] args) { assert(getOddCollatz((14l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))))); assert(getOddCollatz((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l))))); assert(getOddCollatz((12l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l))))); assert(getOddCollatz((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); } }
humaneval-HumanEval_147_get_max_triples.json-L29
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a positive integer n. You have to create an integer array array list a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { arrayList.add(i * i - i + 1); } for (int i = 0; i < arrayList.size(); i++) { for (int j = i + 1; j < arrayList.size(); j++) { for (int k = j + 1; k < arrayList.size(); k++) { if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) {
} } } } return count; } }
count++;
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_72_will_it_fly.json-L45
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) { return false; } for (int i = 0; i < q.size() / 2; i++) { if (q.get(i) != q.get(q.size() - 1 - i)) { return false; } } return true; }
}
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_115_max_fill.json-L34
py
from typing import List def max_fill(grid: List[List[int]], capacity: int) -> int: """ You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) 6 Example 2: >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) 5 Example 3: >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid[:,1].length <= 10^2 * grid[i][j] -> 0 | 1 * 1 <= capacity <= 10 """ times = 0 for row in grid: for i in range(0, len(row), capacity):
times += 1 return times
if 1 in row[i:i+capacity]:
def check(candidate): assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) == 6 assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) == 5 assert candidate([[0, 0, 0], [0, 0, 0]], 5) == 0 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2) == 4 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9) == 2 def test_check(): check(max_fill) test_check()
humaneval-HumanEval_147_get_max_triples.json-L21
js
//You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> get_max_triples(5) // 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). function get_max_triples(n){ let result = 0; let arr = []; for(let i = 1; i<=n; i++){ arr.push(i*i-i+1); } for(let i = 0; i<arr.length; i++){ for(let j = i+1; j<arr.length; j++){ for(let k = j+1; k<arr.length; k++){ if((arr[i]+arr[j]+arr[k])%3 === 0){
} } } } return result; }
result++;
const assert = require('node:assert'); function test() { let candidate = get_max_triples; assert.deepEqual(candidate(5),1); assert.deepEqual(candidate(6),4); assert.deepEqual(candidate(10),36); assert.deepEqual(candidate(100),53361); } test();