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_33_sort_third.json-L15
py
from typing import List def sort_third(l: List[int]) -> List[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """ for i in range(2, len(l), 3): j = i - 2 while j >= 0 and l[j] > l[j + 3]:
j -= 3 return l
l[j], l[j + 3] = l[j + 3], l[j]
def check(candidate): assert candidate([5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5] assert candidate([5, 8, 3, 4, 6, 9, 2]) == [2, 8, 3, 4, 6, 9, 5] assert candidate([5, 6, 9, 4, 8, 3, 2]) == [2, 6, 9, 4, 8, 3, 5] assert candidate([5, 6, 3, 4, 8, 9, 2, 1]) == [2, 6, 3, 4, 8, 9, 5, 1] def test_check(): check(sort_third) test_check()
humaneval-HumanEval_9_rolling_max.json-L9
py
from typing import List def rolling_max(numbers: List[int]) -> List[int]: """ From a given list of integers, generate a list 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] """
return [] else: return [max(numbers[:i + 1]) for i in range(len(numbers))]
if len(numbers) == 0:
def check(candidate): assert candidate([]) == [] assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4] assert candidate([4, 3, 2, 1]) == [4, 4, 4, 4] assert candidate([3, 2, 3, 100, 3]) == [3, 3, 3, 100, 100] def test_check(): check(rolling_max) test_check()
humaneval-HumanEval_19_sort_numbers.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 { // 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_84_solve.json-L15
js
//Given a positive integer N, return the total sum of its digits in binary. // Example // >>> solve(1000) // "1" // >>> solve(150) // "110" // >>> solve(147) // "1100" // Variables: // @N integer // Constraints: 0 ≤ N ≤ 10000. // Output: // a string of binary number function solve(N){
let total = 0; for(let i = 0; i < newN.length; i++){ let digit = newN[i]; total += parseInt(digit); } return total.toString(2); }
let newN = N.toString();
const assert = require('node:assert'); function test() { let candidate = solve; assert.deepEqual(candidate(1000),"1"); assert.deepEqual(candidate(150),"110"); assert.deepEqual(candidate(147),"1100"); assert.deepEqual(candidate(333),"1001"); assert.deepEqual(candidate(963),"10010"); } test();
humaneval-HumanEval_129_minPath.json-L53
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++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); }
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(x < n - 1){
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_120_maximum.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 { // Given an array array list arr of integers and a positive integer k, return a sorted array list // of length k with the maximum k numbers in arr. // Example 1: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)-4l, (long)5l))), (3l)) // (new ArrayList<Long>(Arrays.asList((long)-4l, (long)-3l, (long)5l))) // Example 2: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l, (long)4l))), (2l)) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l))) // Example 3: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)2l, (long)1l, (long)2l, (long)-1l, (long)-2l, (long)1l))), (1l)) // (new ArrayList<Long>(Arrays.asList((long)2l))) // Note: // 1. The length of the array array list will be in the range of [1, 1000]. // 2. The elements in the array array list will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) public static ArrayList<Long> maximum(ArrayList<Long> arr, long k) { Collections.sort(arr);
} }
return new ArrayList<Long>(arr.subList((int)(arr.size() - k), (int)(arr.size())));
} public static void main(String[] args) { assert(maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)-4l, (long)5l))), (3l)).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-3l, (long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l, (long)4l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)2l, (long)1l, (long)2l, (long)-1l, (long)-2l, (long)1l))), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)123l, (long)-123l, (long)20l, (long)0l, (long)1l, (long)2l, (long)-3l))), (3l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)20l, (long)123l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-123l, (long)20l, (long)0l, (long)1l, (long)2l, (long)-3l))), (4l)).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)20l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)5l, (long)15l, (long)0l, (long)3l, (long)-13l, (long)-8l, (long)0l))), (7l)).equals((new ArrayList<Long>(Arrays.asList((long)-13l, (long)-8l, (long)0l, (long)0l, (long)3l, (long)5l, (long)15l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)0l, (long)2l, (long)5l, (long)3l, (long)-10l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)5l, (long)-7l))), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)4l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-10l, (long)10l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)10l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)-23l, (long)243l, (long)-400l, (long)0l))), (0l)).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_157_right_angle_triangle.json-L16
js
//Given the lengths of the three sides of a triangle. Return true if the three // sides form a right-angled triangle, false otherwise. // A right-angled triangle is a triangle in which one angle is right angle or // 90 degree. // Example: // >>> right_angle_triangle(3, 4, 5) // true // >>> right_angle_triangle(1, 2, 3) // false function right_angle_triangle(a, b, c){ if(a**2 + b**2 == c**2 || b**2 + c**2 == a**2 || a**2 + c**2 == b**2) { return true; } else { return false; }
}
const assert = require('node:assert'); function test() { let candidate = right_angle_triangle; assert.deepEqual(candidate(3, 4, 5),true); assert.deepEqual(candidate(1, 2, 3),false); assert.deepEqual(candidate(10, 6, 8),true); assert.deepEqual(candidate(2, 2, 2),false); assert.deepEqual(candidate(7, 24, 25),true); assert.deepEqual(candidate(10, 5, 7),false); assert.deepEqual(candidate(5, 12, 13),true); assert.deepEqual(candidate(15, 8, 17),true); assert.deepEqual(candidate(48, 55, 73),true); assert.deepEqual(candidate(1, 1, 1),false); assert.deepEqual(candidate(2, 2, 10),false); } test();
humaneval-HumanEval_14_all_prefixes.json-L8
py
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """
for i in range(len(string)): prefixes.append(string[:i+1]) return prefixes
prefixes = []
def check(candidate): assert candidate('') == [] assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh'] assert candidate('WWW') == ['W', 'WW', 'WWW'] def test_check(): check(all_prefixes) test_check()
humaneval-HumanEval_126_is_sorted.json-L34
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 of numbers, return whether or not they are sorted // in ascending order. If array list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) // (false) public static boolean isSorted(ArrayList<Long> lst) { if (lst.size() == 0) { return true; } else {
int previous_number = 0; boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue(); } else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
int running_max = 0;
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_40_triples_sum_to_zero.json-L21
py
from typing import List def triples_sum_to_zero(l: List[int]) -> bool: """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """ assert len(l) > 0, "The input list cannot be empty"
for i in range(len(l)): for j in range(i + 1, len(l)): for k in range(j + 1, len(l)): if l[i] + l[j] + l[k] == 0: return True return False
l.sort()
def check(candidate): assert candidate([1, 3, 5, 0]) == False assert candidate([1, 3, 5, -1]) == False assert candidate([1, 3, -2, 1]) == True assert candidate([1, 2, 3, 7]) == False assert candidate([1, 2, 5, 7]) == False assert candidate([2, 4, -5, 3, 9, 7]) == True assert candidate([1]) == False assert candidate([1, 3, 5, -100]) == False assert candidate([100, 3, 5, -100]) == False def test_check(): check(triples_sum_to_zero) test_check()
humaneval-HumanEval_88_sort_array.json-L22
py
from typing import List def sort_array(array: List[int]) -> List[int]: """ Given an array of non-negative integers, return a copy of the given array after sorting, you will sort the given array in ascending order if the sum( first index value, last index value) is odd, or sort it in descending order if the sum( first index value, last index value) is even. Note: * don't change the given array. Examples: >>> sort_array([]) [] >>> sort_array([5]) [5] >>> sort_array([2, 4, 3, 0, 1, 5]) [0, 1, 2, 3, 4, 5] >>> sort_array([2, 4, 3, 0, 1, 5, 6]) [6, 5, 4, 3, 2, 1, 0] """
return sorted(array, reverse=True) if (array[0] + array[-1]) % 2 == 0 else sorted(array) return array
if array:
def check(candidate): assert candidate([]) == [] assert candidate([5]) == [5] assert candidate([2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5] assert candidate([2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0] assert candidate([2, 1]) == [1, 2] assert candidate([15, 42, 87, 32, 11, 0]) == [0, 11, 15, 32, 42, 87] assert candidate([21, 14, 23, 11]) == [23, 21, 14, 11] def test_check(): check(sort_array) test_check()
humaneval-HumanEval_160_do_algebra.json-L28
js
//Given two arrays operator, and operand. The first array has basic algebra operations, and // the second array is an array of integers. Use the two given arrays to build the algebric // expression and return the evaluation of this expression. // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // Example: // operator['+', '*', '-'] // array = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array is equal to the length of operand array minus one. // Operand is an array of of non-negative integers. // Operator array has at least one operator, and operand array has at least two operands. function do_algebra(operator, operand){ let do_again; let count = 0; let temp; let answer; while(count < operator.length){ switch(operator[count]){ case '*': operand[count] = operand[count] * operand[count + 1];
operator.splice(count, 1); count = 0; do_again = true; break; case '//': operand[count] = Math.floor(operand[count] / operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '**': operand[count] = Math.pow(operand[count], operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break; case '-': answer -= operand[0]; break; } operand.splice(0, 1); operator.splice(0, 1); } return answer; }
operand.splice(count + 1, 1);
const assert = require('node:assert'); function test() { let candidate = do_algebra; assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37); assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9); assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8); } test();
humaneval-HumanEval_10_make_palindrome.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 { // 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);
for (int index = 0; index < string.length(); index++) { if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { newString.append(reverse.substring(string.length() - index)); break; } } return newString.toString(); } }
String reverse = new StringBuilder(string).reverse().toString();
} 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_158_find_max.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 { // Write a function that accepts an array array list of strings. // The array list contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))) // ("string") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))) // ("enam") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))) // ("aaaaaaa") public static String findMax(ArrayList<String> words) { Map<String, Integer> wordsToUniqueCharacters = new HashMap<String, Integer>(); for (String word : words) {
for (char c : word.toCharArray()) { uniqueCharacters.add(c); } wordsToUniqueCharacters.put(word, uniqueCharacters.size()); } words.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { int compareResult = wordsToUniqueCharacters.get(o2).compareTo(wordsToUniqueCharacters.get(o1)); if (compareResult == 0) { return o1.compareTo(o2); } return compareResult; } }); return words.get(0); } }
Set<Character> uniqueCharacters = new HashSet<Character>();
} public static void main(String[] args) { assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))).equals(("string"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))).equals(("enam"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))).equals(("aaaaaaa"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"abc", (String)"cba")))).equals(("abc"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"this", (String)"game", (String)"of", (String)"footbott")))).equals(("footbott"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"gonna", (String)"rock")))).equals(("gonna"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"a", (String)"mad", (String)"nation")))).equals(("nation"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"this", (String)"is", (String)"a", (String)"prrk")))).equals(("this"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"b")))).equals(("b"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"play", (String)"play")))).equals(("play"))); } }
humaneval-HumanEval_146_specialFilter.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 { // 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_126_is_sorted.json-L61
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 of numbers, return whether or not they are sorted // in ascending order. If array list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) // (false) public static boolean isSorted(ArrayList<Long> lst) { if (lst.size() == 0) { return true; } else { int running_max = 0; int previous_number = 0; boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue(); } else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue();
} } } return true; } } }
running_max = number.intValue();
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_116_sort_array.json-L17
py
from typing import List def sort_array(arr: List[int]) -> List[int]: """ In this Kata, you have to sort an array of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. It must be implemented like this: >>> sort_array([1, 5, 2, 3, 4]) [1, 2, 3, 4, 5] >>> sort_array([-2, -3, -4, -5, -6]) [-6, -5, -4, -3, -2] >>> sort_array([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4] """
return sorted(arr, key=lambda x: (bin(x).count('1'), x))
def check(candidate): assert candidate([1, 5, 2, 3, 4]) == [1, 2, 4, 3, 5] assert candidate([-2, -3, -4, -5, -6]) == [-4, -2, -6, -5, -3] assert candidate([1, 0, 2, 3, 4]) == [0, 1, 2, 4, 3] assert candidate([]) == [] assert candidate([2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]) == [2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77] assert candidate([3, 6, 44, 12, 32, 5]) == [32, 3, 5, 6, 12, 44] assert candidate([2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32] assert candidate([2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32] def test_check(): check(sort_array) test_check()
humaneval-HumanEval_148_bf.json-L36
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 { // 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 pair 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 pair if planet1 or planet2 // are not correct planet names. // Examples // >>> bf(("Jupiter"), ("Neptune")) // (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))) // >>> bf(("Earth"), ("Mercury")) // (ArrayList<String>("Venus")) // >>> bf(("Mercury"), ("Uranus")) // (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))) public static ArrayList<String> bf(String planet1, String planet2) { ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune")); int indexPlanet1 = planets.indexOf(planet1); int indexPlanet2 = planets.indexOf(planet2); int indexMin = 0; int indexMax = 0; if (indexPlanet1 >= 0 && indexPlanet2 >= 0) { if (indexPlanet1 < indexPlanet2) { indexMin = indexPlanet1; indexMax = indexPlanet2; } else {
indexMax = indexPlanet1; } ArrayList<String> planetsInBetween = new ArrayList<String>(); for (int i = indexMin + 1; i < indexMax; i++) { planetsInBetween.add(planets.get(i)); } return planetsInBetween; } else { return new ArrayList<String>(); } } }
indexMin = indexPlanet2;
} public static void main(String[] args) { assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus"))))); assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))))); assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList())))); } }
humaneval-HumanEval_114_minSubArraySum.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 of integers nums, find the minimum sum of any non-empty sub-array array list // of nums. // Example // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) // (1l) // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) // (-6l) public static long minSubArraySum(ArrayList<Long> nums) { long minSum = Long.MAX_VALUE; long prevMinSum = Long.MAX_VALUE; for (int i = 0; i < nums.size(); i++) { long currSum = nums.get(i); if (currSum < prevMinSum) { prevMinSum = currSum; }
minSum = currSum; } for (int j = i + 1; j < nums.size(); j++) { currSum += nums.get(j); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum; } } } return minSum; } }
if (currSum < minSum) {
} public static void main(String[] args) { assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) == (1l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)2l, (long)-10l)))) == (-14l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-9999999999999999l)))) == (-9999999999999999l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)0l, (long)10l, (long)20l, (long)1000000l)))) == (0l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)10l, (long)11l, (long)13l, (long)8l, (long)3l, (long)4l)))) == (3l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-33l, (long)32l, (long)-1l, (long)0l, (long)-2l)))) == (-33l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-10l)))) == (-10l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)7l)))) == (7l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l)))) == (-1l)); } }
humaneval-HumanEval_115_max_fill.json-L44
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 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: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) // (6l) // Example 2: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) // (5l) // Example 3: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) // (0l) // 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 public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) { long count = 0l; for (ArrayList<Long> well : grid) { long level = 0l; for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity; if (level % capacity != 0l) { units += 1l; } count += units;
return count; } }
}
} public static void main(String[] args) { assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l)); } }
humaneval-HumanEval_1_separate_paren_groups.json-L32
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 containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array 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. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString());
} } return output; } }
}
} public static void main(String[] args) { assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())"))))); assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))"))))); assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))"))))); assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))))); } }
humaneval-HumanEval_13_greatest_common_divisor.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 { // Return a greatest common divisor of two integers a and b // >>> greatestCommonDivisor((3l), (5l)) // (1l) // >>> greatestCommonDivisor((25l), (15l)) // (5l) public static long greatestCommonDivisor(long a, long b) { if (a == 0) { return b; } if (b == 0) { return a; } return greatestCommonDivisor(b, a % b); }
}
} public static void main(String[] args) { assert(greatestCommonDivisor((3l), (7l)) == (1l)); assert(greatestCommonDivisor((10l), (15l)) == (5l)); assert(greatestCommonDivisor((49l), (14l)) == (7l)); assert(greatestCommonDivisor((144l), (60l)) == (12l)); } }
humaneval-HumanEval_148_bf.json-L40
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 { // 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 pair 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 pair if planet1 or planet2 // are not correct planet names. // Examples // >>> bf(("Jupiter"), ("Neptune")) // (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))) // >>> bf(("Earth"), ("Mercury")) // (ArrayList<String>("Venus")) // >>> bf(("Mercury"), ("Uranus")) // (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))) public static ArrayList<String> bf(String planet1, String planet2) { ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune")); int indexPlanet1 = planets.indexOf(planet1); int indexPlanet2 = planets.indexOf(planet2); int indexMin = 0; int indexMax = 0; if (indexPlanet1 >= 0 && indexPlanet2 >= 0) { if (indexPlanet1 < indexPlanet2) { indexMin = indexPlanet1; indexMax = indexPlanet2; } else { indexMin = indexPlanet2; indexMax = indexPlanet1; } ArrayList<String> planetsInBetween = new ArrayList<String>();
planetsInBetween.add(planets.get(i)); } return planetsInBetween; } else { return new ArrayList<String>(); } } }
for (int i = indexMin + 1; i < indexMax; i++) {
} public static void main(String[] args) { assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus"))))); assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))))); assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList())))); } }
humaneval-HumanEval_156_int_to_mini_roman.json-L30
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";
} 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; } }
num -= 900;
} 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_59_largest_prime_factor.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 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++) { if (x % i == 0) { primes.add(i);
i--; } } if (x > 1) { primes.add(x); } return primes.get(primes.size() - 1); } }
x /= i;
} 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_117_select_words.json-L23
js
//Given a string s and a natural number n, you have been tasked to implement // a function that returns an array 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. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> select_words("Mary had a little lamb", 4) // ["little"] // >>> select_words("Mary had a little lamb", 3) // ["Mary", "lamb"] // >>> select_words("simple white space", 2) // [] // >>> select_words("Hello world", 4) // ["world"] // >>> select_words("Uncle sam", 3) // ["Uncle"] function select_words(s, n){ let words = s.split(' ').filter(e => e != ''); let selected = words.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi) != null); if(n > 0){ return selected.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi).length == n); }else{
} }
return [];
const assert = require('node:assert'); function test() { let candidate = select_words; assert.deepEqual(candidate("Mary had a little lamb", 4),["little"]); assert.deepEqual(candidate("Mary had a little lamb", 3),["Mary", "lamb"]); assert.deepEqual(candidate("simple white space", 2),[]); assert.deepEqual(candidate("Hello world", 4),["world"]); assert.deepEqual(candidate("Uncle sam", 3),["Uncle"]); assert.deepEqual(candidate("", 4),[]); assert.deepEqual(candidate("a b c d e f", 1),["b", "c", "d", "f"]); } test();
humaneval-HumanEval_96_count_up_to.json-L40
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 { // Implement a function that takes an non-negative integer and returns an array array list of the first n // integers that are prime numbers and less than n. // for example: // >>> countUpTo((5l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))) // >>> countUpTo((11l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l))) // >>> countUpTo((0l)) // (new ArrayList<Long>(Arrays.asList())) // >>> countUpTo((20l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l))) // >>> countUpTo((1l)) // (new ArrayList<Long>(Arrays.asList())) // >>> countUpTo((18l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))) public static ArrayList<Long> countUpTo(long n) { ArrayList<Long> arrayList = new ArrayList<Long>(); for (long i = 2l; i < n; i++) { boolean isPrime = true; for (long j = 2l; j < i; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) { arrayList.add(i); } } return arrayList; }
}
} public static void main(String[] args) { assert(countUpTo((5l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))))); assert(countUpTo((6l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l))))); assert(countUpTo((7l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l))))); assert(countUpTo((10l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l))))); assert(countUpTo((0l)).equals((new ArrayList<Long>(Arrays.asList())))); assert(countUpTo((22l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l))))); assert(countUpTo((1l)).equals((new ArrayList<Long>(Arrays.asList())))); assert(countUpTo((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))))); assert(countUpTo((47l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l, (long)23l, (long)29l, (long)31l, (long)37l, (long)41l, (long)43l))))); assert(countUpTo((101l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l, (long)23l, (long)29l, (long)31l, (long)37l, (long)41l, (long)43l, (long)47l, (long)53l, (long)59l, (long)61l, (long)67l, (long)71l, (long)73l, (long)79l, (long)83l, (long)89l, (long)97l))))); } }
humaneval-HumanEval_0_has_close_elements.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 { // Check if in given array list of numbers, are any two numbers closer to each other than // given threshold. // >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f))), (0.5f)) // (false) // >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.8f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.3f)) // (true) public static boolean hasCloseElements(ArrayList<Float> numbers, float threshold) { Collections.sort(numbers); for (int i = 0; i < numbers.size() - 1; i++) {
return true; } } return false; } }
if (numbers.get(i+1) - numbers.get(i) < threshold) {
} public static void main(String[] args) { assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.3f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.05f)) == (false)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.95f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.8f)) == (false)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.1f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (1.0f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (0.5f)) == (false)); } }
humaneval-HumanEval_125_split_words.json-L27
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); } else if(txt.includes(',')){ return txt.split(','); } else{ let count = 0; for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){ if(txt[i] == txt[i].toLowerCase()){ count++; } } }
} }
return count;
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_17_parse_music.json-L19
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'){ song.push(4); }else if(s === 'o|'){ song.push(2); }else if(s === '.|'){
} }); return song; }
song.push(1);
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_59_largest_prime_factor.json-L16
py
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ largest = 1 factor = 2 while factor < n: if n % factor == 0: largest = factor while n % factor == 0: n = n // factor factor += 1
return max(largest, n)
def check(candidate): assert candidate(15) == 5 assert candidate(27) == 3 assert candidate(63) == 7 assert candidate(330) == 11 assert candidate(13195) == 29 def test_check(): check(largest_prime_factor) test_check()
humaneval-HumanEval_8_sum_product.json-L9
js
//For a given array of integers, return an array consisting of a sum and a product of all the integers in an array. // Empty sum should be equal to 0 and empty product should be equal to 1. // >>> sum_product([]) // [0, 1] // >>> sum_product([1, 2, 3, 4]) // [10, 24] function sum_product(numbers){ if(numbers.length == 0){
} let sum = 0; let product = 1; for(let i = 0; i < numbers.length; i++){ sum += numbers[i]; product *= numbers[i]; } return [sum, product]; }
return [0, 1];
const assert = require('node:assert'); function test() { let candidate = sum_product; assert.deepEqual(candidate([]),[0, 1]); assert.deepEqual(candidate([1, 1, 1]),[3, 1]); assert.deepEqual(candidate([100, 0]),[100, 0]); assert.deepEqual(candidate([3, 5, 7]),[15, 105]); assert.deepEqual(candidate([10]),[10, 10]); } test();
humaneval-HumanEval_110_exchange.json-L26
js
//In this problem, you will implement a function that takes two arrays of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array of only even numbers. // There is no limit on the number of exchanged elements between lst1 and lst2. // If it is possible to exchange elements between the lst1 and lst2 to make // all the elements of lst1 to be even, return "YES". // Otherwise, return "NO". // For example: // >>> exchange([1, 2, 3, 4], [1, 2, 3, 4]) // "YES" // >>> exchange([1, 2, 3, 4], [1, 5, 3, 4]) // "NO" // It is assumed that the input arrays will be non-empty. function exchange(lst1, lst2){ var num1 = 0; var num2 = 0; var exchange = true; while(num1 < lst1.length && exchange){ if(lst1[num1] % 2 !== 0){ exchange = false; if(num2 < lst2.length){ while(num2 < lst2.length && exchange == false){ if(lst2[num2] % 2 == 0){ lst1[num1] = lst2[num2]; exchange = true;
num2++; } } } num1++; } if(exchange){ return "YES"; }else{ return "NO"; } }
}
const assert = require('node:assert'); function test() { let candidate = exchange; assert.deepEqual(candidate([1, 2, 3, 4], [1, 2, 3, 4]),"YES"); assert.deepEqual(candidate([1, 2, 3, 4], [1, 5, 3, 4]),"NO"); assert.deepEqual(candidate([1, 2, 3, 4], [2, 1, 4, 3]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 4]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 3]),"NO"); assert.deepEqual(candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]),"NO"); assert.deepEqual(candidate([100, 200], [200, 200]),"YES"); } test();
humaneval-HumanEval_137_compare_one.json-L37
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; } } else if (typeof a === "string" && typeof b === "number"){ 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;
return undefined; } } }
} else {
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_126_is_sorted.json-L43
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 of numbers, return whether or not they are sorted // in ascending order. If array list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) // (false) public static boolean isSorted(ArrayList<Long> lst) { if (lst.size() == 0) { return true; } else { int running_max = 0; int previous_number = 0; boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue();
else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
}
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_114_minSubArraySum.json-L17
js
//Given an array of integers nums, find the minimum sum of any non-empty sub-array // of nums. // Example // >>> minSubArraySum([2, 3, 4, 1, 2, 4]) // 1 // >>> minSubArraySum([-1, -2, -3]) // -6 function minSubArraySum(nums){ let sum = 0; let minSum = nums[0]; for(let i = 0; i < nums.length; i++){ sum += nums[i]; if(sum < minSum){ minSum = sum; } if(sum > 0){
} } return minSum; }
sum = 0;
const assert = require('node:assert'); function test() { let candidate = minSubArraySum; assert.deepEqual(candidate([2, 3, 4, 1, 2, 4]),1); assert.deepEqual(candidate([-1, -2, -3]),-6); assert.deepEqual(candidate([-1, -2, -3, 2, -10]),-14); assert.deepEqual(candidate([-9999999999999999]),-9999999999999999); assert.deepEqual(candidate([0, 10, 20, 1000000]),0); assert.deepEqual(candidate([-1, -2, -3, 10, -5]),-6); assert.deepEqual(candidate([100, -1, -2, -3, 10, -5]),-6); assert.deepEqual(candidate([10, 11, 13, 8, 3, 4]),3); assert.deepEqual(candidate([100, -33, 32, -1, 0, -2]),-33); assert.deepEqual(candidate([-10]),-10); assert.deepEqual(candidate([7]),7); assert.deepEqual(candidate([1, -1]),-1); } test();
humaneval-HumanEval_40_triples_sum_to_zero.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 { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) { return false; } ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList); for (int i = 0; i < sortedList.size() - 2; i++) { int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) { j++; } else { k--;
} } return false; } }
}
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_68_pluck.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 an array array list 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 array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // 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 public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i; minValue = arr.get(i); } } } ArrayList<Long> newArr = new ArrayList<Long>();
return newArr; } newArr.add(minValue); newArr.add((long)minIndex); return newArr; } }
if (minIndex == -1) {
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_159_eat.json-L28
js
//You're a hungry rabbit, and you already have eaten a certain number of carrots, // but now you need to eat more carrots to complete the day's meals. // you should return an array of [ total number of eaten carrots after your meals, // the number of carrots left after your meals ] // if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. // Example: // >>> eat(5, 6, 10) // [11, 4] // >>> eat(4, 8, 9) // [12, 1] // >>> eat(1, 10, 10) // [11, 0] // >>> eat(2, 11, 5) // [7, 0] // Variables: // @number : integer // the number of carrots that you have eaten. // @need : integer // the number of carrots that you need to eat. // @remaining : integer // the number of remaining carrots thet exist in stock // Constrain: // * 0 <= number <= 1000 // * 0 <= need <= 1000 // * 0 <= remaining <= 1000 // Have fun :) function eat(number, need, remaining){
else return [number + need, remaining - need]; }
if (need > remaining) return [number + remaining, 0];
const assert = require('node:assert'); function test() { let candidate = eat; assert.deepEqual(candidate(5, 6, 10),[11, 4]); assert.deepEqual(candidate(4, 8, 9),[12, 1]); assert.deepEqual(candidate(1, 10, 10),[11, 0]); assert.deepEqual(candidate(2, 11, 5),[7, 0]); assert.deepEqual(candidate(4, 5, 7),[9, 2]); assert.deepEqual(candidate(4, 5, 1),[5, 0]); } test();
humaneval-HumanEval_141_file_name_check.json-L34
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(): return 'No' if e_name not in ['txt', 'exe', 'dll']: return 'No'
return 'Yes'
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_106_f.json-L21
js
//Implement the function f that takes n as a parameter, // and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f(5) // [1, 2, 6, 24, 15] function f(n){ var result = []; var sum = 0; var factorial = 1; for(var i = 1; i <= n; i++){ if(i % 2 == 0){ for(var j = 1; j <= i; j++){ factorial *= j; } result.push(factorial); factorial = 1; }else{
sum += k; } result.push(sum); sum = 0; } } return result; }
for(var k = 1; k <= i; k++){
const assert = require('node:assert'); function test() { let candidate = f; assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]); assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]); assert.deepEqual(candidate(1),[1]); assert.deepEqual(candidate(3),[1, 2, 6]); } test();
humaneval-HumanEval_146_specialFilter.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 { // 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) {
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(); } }
class helper {
} 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_6_parse_nested_parens.json-L17
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 represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parseNestedParens(("(()()) ((())) () ((())()())")) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))) public static ArrayList<Long> parseNestedParens(String paren_string) { ArrayList<Long> result = new ArrayList<Long>(); String[] paren_strings = paren_string.split(" ");
long max_depth = 0; long current_depth = 0; for (char c : paren.toCharArray()) { if (c == '(') { current_depth += 1; max_depth = Math.max(max_depth, current_depth); } else if (c == ')') { current_depth -= 1; } } result.add(max_depth); } return result; } }
for (String paren : paren_strings) {
} public static void main(String[] args) { assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))))); assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l))))); } }
humaneval-HumanEval_39_prime_fib.json-L28
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 { // prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> primeFib((1l)) // (2l) // >>> primeFib((2l)) // (3l) // >>> primeFib((3l)) // (5l) // >>> primeFib((4l)) // (13l) // >>> primeFib((5l)) // (89l) public static long primeFib(long n) { long fib = 1; long prev = 0; long count = 0; while (count != n) { long tmp = fib; fib += prev; prev = tmp;
count++; } } return fib; } }
if (BigInteger.valueOf(fib).isProbablePrime(1)) {
} public static void main(String[] args) { assert(primeFib((1l)) == (2l)); assert(primeFib((2l)) == (3l)); assert(primeFib((3l)) == (5l)); assert(primeFib((4l)) == (13l)); assert(primeFib((5l)) == (89l)); assert(primeFib((6l)) == (233l)); assert(primeFib((7l)) == (1597l)); assert(primeFib((8l)) == (28657l)); assert(primeFib((9l)) == (514229l)); assert(primeFib((10l)) == (433494437l)); } }
humaneval-HumanEval_105_by_length.json-L34
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three");
else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
}
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_10_make_palindrome.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 { // 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++) { if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { newString.append(reverse.substring(string.length() - index)); break; } } return newString.toString();
}
}
} 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_123_get_odd_collatz.json-L30
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 }
break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
if(collatz_sequence[i] == 1){
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_158_find_max.json-L31
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; }
if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
else if(Object.keys(unique_word).length === Object.keys(max_unique).length){
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_20_find_closest_elements.json-L25
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j])
temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
temp_index = i
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_3_below_zero.json-L17
py
from typing import List def below_zero(operations: List[int]) -> bool: """ You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ balance = 0 for operation in operations: balance += operation if balance < 0: return True
print(below_zero([1, 2, 3])) print(below_zero([1, 2, -4, 5]))
return False
def check(candidate): assert candidate([]) == False assert candidate([1, 2, -3, 1, 2, -3]) == False assert candidate([1, 2, -4, 5, 6]) == True assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True def test_check(): check(below_zero) test_check()
humaneval-HumanEval_2_truncate_number.json-L8
js
//Given a positive floating point number, it can be decomposed into // and integer part (largest integer smaller than given number) and decimals // (leftover part always smaller than 1). // Return the decimal part of the number. // >>> truncate_number(3.5) // 0.5 function truncate_number(number){
}
return number - Math.floor(number);
const assert = require('node:assert'); function test() { let candidate = truncate_number; assert.deepEqual(candidate(3.5),0.5); assert.deepEqual(candidate(1.25),0.25); assert.deepEqual(candidate(123.0),0.0); } test();
humaneval-HumanEval_115_max_fill.json-L43
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 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: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) // (6l) // Example 2: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) // (5l) // Example 3: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) // (0l) // 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 public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) { long count = 0l; for (ArrayList<Long> well : grid) { long level = 0l; for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity; if (level % capacity != 0l) { units += 1l; }
} return count; } }
count += units;
} public static void main(String[] args) { assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l)); } }
humaneval-HumanEval_33_sort_third.json-L11
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=[];
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; }
let k=0;
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_63_fibfib.json-L19
js
//The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib(1) // 0 // >>> fibfib(5) // 4 // >>> fibfib(8) // 24 function fibfib(n){ if(n <= 0){ return 0; } if(n == 1){ return 0;
if(n == 2){ return 1; } return fibfib(n-1) + fibfib(n-2) + fibfib(n-3); }
}
const assert = require('node:assert'); function test() { let candidate = fibfib; assert.deepEqual(candidate(2),1); assert.deepEqual(candidate(1),0); assert.deepEqual(candidate(5),4); assert.deepEqual(candidate(8),24); assert.deepEqual(candidate(10),81); assert.deepEqual(candidate(12),274); assert.deepEqual(candidate(14),927); } test();
humaneval-HumanEval_126_is_sorted.json-L39
js
//Given an array of numbers, return whether or not they are sorted // in ascending order. If array has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> is_sorted([5]) // true // >>> is_sorted([1, 2, 3, 4, 5]) // true // >>> is_sorted([1, 3, 2, 4, 5]) // false // >>> is_sorted([1, 2, 3, 4, 5, 6]) // true // >>> is_sorted([1, 2, 3, 4, 5, 6, 7]) // true // >>> is_sorted([1, 3, 2, 4, 5, 6, 7]) // false // >>> is_sorted([1, 2, 2, 3, 3, 4]) // true // >>> is_sorted([1, 2, 2, 2, 3, 4]) // false function is_sorted(lst){ var last = null; var dupe_found = false; for (var x of lst){ if (last == null){ last = x; } else if (x < last){ return false; } else if (x == last){ if (dupe_found){ return false; } else { dupe_found = true; } } else { last = x; dupe_found = false; }
return true; }
}
const assert = require('node:assert'); function test() { let candidate = is_sorted; assert.deepEqual(candidate([5]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, 7]),false); assert.deepEqual(candidate([]),true); assert.deepEqual(candidate([1]),true); assert.deepEqual(candidate([3, 2, 1]),false); assert.deepEqual(candidate([1, 2, 2, 2, 3, 4]),false); assert.deepEqual(candidate([1, 2, 3, 3, 3, 4]),false); assert.deepEqual(candidate([1, 2, 2, 3, 3, 4]),true); assert.deepEqual(candidate([1, 2, 3, 4]),true); } test();
humaneval-HumanEval_40_triples_sum_to_zero.json-L18
js
//triples_sum_to_zero takes an array of integers as an input. // it returns true if there are three distinct elements in the array that // sum to zero, and false otherwise. // >>> triples_sum_to_zero([1, 3, 5, 0]) // false // >>> triples_sum_to_zero([1, 3, -2, 1]) // true // >>> triples_sum_to_zero([1, 2, 3, 7]) // false // >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) // true // >>> triples_sum_to_zero([1]) // false function triples_sum_to_zero(l){ for (var i = 0; i < l.length; i++) { for (var j = 0; j < l.length; j++) { for (var k = 0; k < l.length; k++) {
if (l[i] + l[j] + l[k] === 0) { return true; } } } } } return false; }
if (i !== j && i !== k && j !== k) {
const assert = require('node:assert'); function test() { let candidate = triples_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, 5, -1]),false); assert.deepEqual(candidate([1, 3, -2, 1]),true); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([1, 2, 5, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 9, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([1, 3, 5, -100]),false); assert.deepEqual(candidate([100, 3, 5, -100]),false); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L42
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){
} else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); } else if (grades[i] > 1.3){ 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; }
grades_array.push("B-");
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_25_factorize.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 { // 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>(); for (long d = 2; d*d <= n; d++) { while (n % d == 0) { factors.add(d); n /= d;
} if (n > 1) factors.add(n); return factors; } }
}
} 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_148_bf.json-L30
js
//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 an array 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 array 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"] function bf(planet1, planet2){ var planets = { 'Mercury':1, 'Venus':2, 'Earth':3, 'Mars':4, 'Jupiter':5, 'Saturn':6, 'Uranus':7, 'Neptune':8 } if(!planets[planet1] || !planets[planet2]){ return [];
var keys = Object.keys(planets); var position1 = keys.indexOf(planet1); var position2 = keys.indexOf(planet2); if(position1 > position2){ var temp = position1; position1 = position2; position2 = temp; } var res = []; for(var i = position1 + 1; i < position2; i++){ res.push(keys[i]); } return res; }
}
const assert = require('node:assert'); function test() { let candidate = bf; assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]); assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]); assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Earth"),[]); assert.deepEqual(candidate("Mars", "Earth"),[]); assert.deepEqual(candidate("Jupiter", "Makemake"),[]); } test();
humaneval-HumanEval_19_sort_numbers.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 { // 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>() {
public int compare(String s1, String s2) { return indexMap.get(s1) - indexMap.get(s2); } }); return String.join(" ", split); } }
@Override
} 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_47_median.json-L14
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_39_prime_fib.json-L25
js
//prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> prime_fib(1) // 2 // >>> prime_fib(2) // 3 // >>> prime_fib(3) // 5 // >>> prime_fib(4) // 13 // >>> prime_fib(5) // 89 function prime_fib(n){ function isPrime(number){ if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false; }
return true; } } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b; b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
}
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_111_histogram.json-L31
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++){ if (count[lst[i]]){ count[lst[i]] += 1; } else{ count[lst[i]] = 1; } } console.log(count); var max = 0;
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; }
var result = {};
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_64_vowels_count.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 { // Write a function vowels_count which takes a string representing // a word as input and returns the number of vowels in the string. // Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a // vowel, but only when it is at the end of the given word. // Example: // >>> vowelsCount(("abcde")) // (2l) // >>> vowelsCount(("ACEDY")) // (3l) public static long vowelsCount(String s) { long sum = 0; String sUpper = s.toUpperCase(); int lastIndex = sUpper.length() - 1; for (int i = 0; i < sUpper.length(); i++) { if (sUpper.charAt(i) == 'A' || sUpper.charAt(i) == 'E' || sUpper.charAt(i) == 'I' || sUpper.charAt(i) == 'O' || sUpper.charAt(i) == 'U') { sum++;
if (sUpper.charAt(i) == 'Y' && i == lastIndex) { sum++; } } return sum; } }
}
} public static void main(String[] args) { assert(vowelsCount(("abcde")) == (2l)); assert(vowelsCount(("Alone")) == (3l)); assert(vowelsCount(("key")) == (2l)); assert(vowelsCount(("bye")) == (1l)); assert(vowelsCount(("keY")) == (2l)); assert(vowelsCount(("bYe")) == (1l)); assert(vowelsCount(("ACEDY")) == (3l)); } }
humaneval-HumanEval_85_add.json-L17
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 lst. add the even elements that are at odd indices.. // Examples: // >>> add((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)6l, (long)7l)))) // (2l) public static long add(ArrayList<Long> lst) { long sum = 0; for (int i = 0; i < lst.size(); i++) { if (i % 2 == 1 && lst.get(i) % 2 == 0) {
} } return sum; } }
sum += lst.get(i);
} public static void main(String[] args) { assert(add((new ArrayList<Long>(Arrays.asList((long)4l, (long)88l)))) == (88l)); assert(add((new ArrayList<Long>(Arrays.asList((long)4l, (long)5l, (long)6l, (long)7l, (long)2l, (long)122l)))) == (122l)); assert(add((new ArrayList<Long>(Arrays.asList((long)4l, (long)0l, (long)6l, (long)7l)))) == (0l)); assert(add((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)6l, (long)8l)))) == (12l)); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L41
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') elif x > 2.7: final.append('B')
final.append('B-') elif x > 2.0: final.append('C+') elif x > 1.7: final.append('C') elif x > 1.3: final.append('C-') elif x > 1.0: final.append('D+') elif x > 0.7: final.append('D') elif x > 0.0: final.append('D-') else: final.append('E') return final
elif x > 2.3:
def check(candidate): assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-'] assert candidate([1.2]) == ['D+'] assert candidate([0.5]) == ['D-'] assert candidate([0.0]) == ['E'] assert candidate([1.0, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+'] assert candidate([0.0, 0.7]) == ['E', 'D-'] def test_check(): check(numerical_letter_grade) test_check()
humaneval-HumanEval_149_sorted_list_sum.json-L39
js
//Write a function that accepts an array of strings as a parameter, // deletes the strings that have odd lengths from it, // and returns the resulted array with a sorted order, // The array is always an array of strings and never an array of numbers, // and it may contain duplicates. // The order of the array should be ascending by length of each word, and you // should return the array sorted by that rule. // If two words have the same length, sort the array alphabetically. // The function should return an array of strings in sorted order. // You may assume that all words will have the same length. // For example: // >>> list_sort(["aa", "a", "aaa"]) // ["aa"] // >>> list_sort(["ab", "a", "aaa", "cd"]) // ["ab", "cd"] function sorted_list_sum(lst){ var result = []; for(var i = 0; i < lst.length; i++){ if(lst[i].length % 2 == 0){ result.push(lst[i]); } } return result.sort(function(a, b){ if(a.length < b.length){ return -1; } else if(a.length > b.length){ return 1; } else{ if(a < b){ return -1; } else if(a > b){ return 1; } else{ return 0;
} }); } var a = ["aa", "a", "aaa"]; var b = ["ab", "a", "aaa", "cd"];
}
const assert = require('node:assert'); function test() { let candidate = sorted_list_sum; assert.deepEqual(candidate(["aa", "a", "aaa"]),["aa"]); assert.deepEqual(candidate(["school", "AI", "asdf", "b"]),["AI", "asdf", "school"]); assert.deepEqual(candidate(["d", "b", "c", "a"]),[]); assert.deepEqual(candidate(["d", "dcba", "abcd", "a"]),["abcd", "dcba"]); assert.deepEqual(candidate(["AI", "ai", "au"]),["AI", "ai", "au"]); assert.deepEqual(candidate(["a", "b", "b", "c", "c", "a"]),[]); assert.deepEqual(candidate(["aaaa", "bbbb", "dd", "cc"]),["cc", "dd", "aaaa", "bbbb"]); } test();
humaneval-HumanEval_129_minPath.json-L70
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++){ if(grid[i][j] === currCell){ 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; }
}
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_20_find_closest_elements.json-L26
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i
if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
temp2_index = j
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_161_solve.json-L27
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_82_prime_length.json-L23
py
def prime_length(string: str) -> bool: """Write a function that takes a string and returns True if the string length is a prime number or False otherwise Examples >>> prime_length('Hello') True >>> prime_length('abcdcba') True >>> prime_length('kittens') True >>> prime_length('orange') False """ num = len(string) if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False
pass
def check(candidate): assert candidate('Hello') == True assert candidate('abcdcba') == True assert candidate('kittens') == True assert candidate('orange') == False assert candidate('wow') == True assert candidate('world') == True assert candidate('MadaM') == True assert candidate('Wow') == True assert candidate('') == False assert candidate('HI') == True assert candidate('go') == True assert candidate('gogo') == False assert candidate('aaaaaaaaaaaaaaa') == False assert candidate('Madam') == True assert candidate('M') == False assert candidate('0') == False def test_check(): check(prime_length) test_check()
humaneval-HumanEval_11_string_xor.json-L17
js
//Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> string_xor("010", "110") // "100" function string_xor(a, b){ var arrayA = []; var arrayB = []; var arrayXOR = []; var result = ''; for (var i = 0; i < a.length; i++) { arrayA.push(parseInt(a[i])); } for (var j = 0; j < b.length; j++) { arrayB.push(parseInt(b[j])); } for (var k = 0; k < arrayA.length; k++) {
arrayXOR.push(1); } else { arrayXOR.push(0); } } result = arrayXOR.join(''); return result; }
if (arrayA[k] !== arrayB[k]) {
const assert = require('node:assert'); function test() { let candidate = string_xor; assert.deepEqual(candidate("111000", "101010"),"010010"); assert.deepEqual(candidate("1", "1"),"0"); assert.deepEqual(candidate("0101", "0000"),"0101"); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L33
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));
return ans; } }
Collections.sort(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_71_triangle_area.json-L14
js
//Given the lengths of the three sides of a triangle. Return the area of // the triangle rounded to 2 decimal points if the three sides form a valid triangle. // Otherwise return -1 // Three sides make a valid triangle when the sum of any two sides is greater // than the third side. // Example: // >>> triangle_area(3, 4, 5) // 6.0 // >>> triangle_area(1, 2, 10) // -1 function triangle_area(a, b, c){ if(a+b>c && a+c>b && b+c>a){ var s = (a+b+c)/2;
}else{ return -1; } }
return Math.sqrt(s*(s-a)*(s-b)*(s-c)).toFixed(2);
const assert = require('node:assert'); function test() { let candidate = triangle_area; assert.deepEqual(candidate(3, 4, 5),6.0); assert.deepEqual(candidate(1, 2, 10),-1); assert.deepEqual(candidate(4, 8, 5),8.18); assert.deepEqual(candidate(2, 2, 2),1.73); assert.deepEqual(candidate(1, 2, 3),-1); assert.deepEqual(candidate(10, 5, 7),16.25); assert.deepEqual(candidate(2, 6, 3),-1); assert.deepEqual(candidate(1, 1, 1),0.43); assert.deepEqual(candidate(2, 2, 10),-1); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L35
js
//Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> int_to_mini_roman(19) // "xix" // >>> int_to_mini_roman(152) // "clii" // >>> int_to_mini_roman(426) // "cdxxvi" function int_to_mini_roman(number){ var roman_conversion = { 1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number); key_list.sort(function(a, b){return b-a}); for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i];
} } } return output; }
break;
const assert = require('node:assert'); function test() { let candidate = int_to_mini_roman; assert.deepEqual(candidate(19),"xix"); assert.deepEqual(candidate(152),"clii"); assert.deepEqual(candidate(251),"ccli"); assert.deepEqual(candidate(426),"cdxxvi"); assert.deepEqual(candidate(500),"d"); assert.deepEqual(candidate(1),"i"); assert.deepEqual(candidate(4),"iv"); assert.deepEqual(candidate(43),"xliii"); assert.deepEqual(candidate(90),"xc"); assert.deepEqual(candidate(94),"xciv"); assert.deepEqual(candidate(532),"dxxxii"); assert.deepEqual(candidate(900),"cm"); assert.deepEqual(candidate(994),"cmxciv"); assert.deepEqual(candidate(1000),"m"); } test();
humaneval-HumanEval_56_correct_bracketing.json-L22
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 for bracket in brackets: if bracket == '<': num_left_brackets += 1 elif bracket == '>': num_left_brackets -= 1 if num_left_brackets < 0: return False
return num_left_brackets == 0
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_141_file_name_check.json-L21
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
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(): return 'No' if e_name not in ['txt', 'exe', 'dll']: return 'No' return 'Yes'
for i in file_name:
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_70_strange_sort_list.json-L24
js
//Given array of integers, return array in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strange_sort_list([1, 2, 3, 4]) // [1, 4, 2, 3] // >>> strange_sort_list([5, 5, 5, 5]) // [5, 5, 5, 5] // >>> strange_sort_list([]) // [] function strange_sort_list(lst){ if(lst.length === 0){ return []; } var output = []; var tmp = lst.slice(); for(var i = 0; i < lst.length; i++){ if(i % 2 === 0){ output.push(Math.min.apply(null, tmp)); } else{ output.push(Math.max.apply(null, tmp)); }
} return output; }
tmp.splice(tmp.indexOf(output[i]), 1);
const assert = require('node:assert'); function test() { let candidate = strange_sort_list; assert.deepEqual(candidate([1, 2, 3, 4]),[1, 4, 2, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9]),[5, 9, 6, 8, 7]); assert.deepEqual(candidate([1, 2, 3, 4, 5]),[1, 5, 2, 4, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9, 1]),[1, 9, 5, 8, 6, 7]); assert.deepEqual(candidate([5, 5, 5, 5]),[5, 5, 5, 5]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7, 8]),[1, 8, 2, 7, 3, 6, 4, 5]); assert.deepEqual(candidate([0, 2, 2, 2, 5, 5, -5, -5]),[-5, 5, -5, 5, 0, 2, 2, 2]); assert.deepEqual(candidate([111111]),[111111]); } test();
humaneval-HumanEval_95_check_dict_case.json-L28
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 hash map, 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 hash map is empty. // Examples: // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "b", "banana")))) // (true) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "A", "banana", "B", "banana")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", 8l, "banana", "a", "apple")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) // (true) public static boolean checkDictCase(HashMap<String,String> dict) { if (dict.isEmpty()) { return false; } boolean allLowerCase = dict.keySet().stream().allMatch(k -> k.matches("^[a-z]+$"));
return allLowerCase || allUpperCase; } }
boolean allUpperCase = dict.keySet().stream().allMatch(k -> k.matches("^[A-Z]+$"));
} public static void main(String[] args) { assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "b", "banana")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "A", "banana", "B", "banana")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "5", "banana", "a", "apple")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("fruit", "Orange", "taste", "Sweet")))) == (true)); assert(checkDictCase((new HashMap<String,String>())) == (false)); } }
humaneval-HumanEval_69_search.json-L14
js
//You are given a non-empty array of positive integers. Return the greatest integer that is greater than // zero, and has a frequency greater than or equal to the value of the integer itself. // The frequency of an integer is the number of times it appears in the array. // If no such a value exist, return -1. // Examples: // >>> search([4, 1, 2, 2, 3, 1]) // 2 // >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) // 3 // >>> search([5, 5, 4, 4, 4]) // -1 function search(lst){ var h = {};
var x = lst[i]; if (x in h){ h[x] += 1; } else{ h[x] = 1; } } var keys = Object.keys(h); var max = 0; for (var i=0; i<keys.length; i++){ if (keys[i] > max && h[keys[i]] >= keys[i]){ max = keys[i]; } } if (max == 0){ return -1; } return max; }
for (var i=0; i<lst.length; i++){
const assert = require('node:assert'); function test() { let candidate = search; assert.deepEqual(candidate([5, 5, 5, 5, 1]),1); assert.deepEqual(candidate([4, 1, 4, 1, 4, 4]),4); assert.deepEqual(candidate([3, 3]),-1); assert.deepEqual(candidate([8, 8, 8, 8, 8, 8, 8, 8]),8); assert.deepEqual(candidate([2, 3, 3, 2, 2]),2); assert.deepEqual(candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]),1); assert.deepEqual(candidate([3, 2, 8, 2]),2); assert.deepEqual(candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]),1); assert.deepEqual(candidate([8, 8, 3, 6, 5, 6, 4]),-1); assert.deepEqual(candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]),1); assert.deepEqual(candidate([1, 9, 10, 1, 3]),1); assert.deepEqual(candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]),5); assert.deepEqual(candidate([1]),1); assert.deepEqual(candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]),4); assert.deepEqual(candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]),2); assert.deepEqual(candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]),1); assert.deepEqual(candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]),4); assert.deepEqual(candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]),4); assert.deepEqual(candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]),2); assert.deepEqual(candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]),-1); assert.deepEqual(candidate([10]),-1); assert.deepEqual(candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]),2); assert.deepEqual(candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]),1); assert.deepEqual(candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]),1); assert.deepEqual(candidate([3, 10, 10, 9, 2]),-1); } test();
humaneval-HumanEval_87_get_row.json-L24
py
from typing import List, Tuple def get_row(lst: List[List[int]], x: int) -> List[Tuple[int, int]]: """ You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: >>> get_row([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] >>> get_row([], 1) [] >>> get_row([[], [1], [1, 2, 3]], 3) [(2, 2)] """ res = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x] res.sort(key=lambda t: (t[0], -t[1]))
return res
def check(candidate): assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 2) == [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)] assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 1, 3, 4, 5, 6], [1, 2, 1, 4, 5, 6], [1, 2, 3, 1, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) == [(0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0)] assert candidate([], 1) == [] assert candidate([[1]], 2) == [] assert candidate([[], [1], [1, 2, 3]], 3) == [(2, 2)] def test_check(): check(get_row) test_check()
humaneval-HumanEval_10_make_palindrome.json-L13
py
def make_palindrome(string: str) -> str: """ 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. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """
return string prefix = string[::-1] for i in range(len(string)): if string[i:] == prefix[:len(string) - i]: return string + prefix[len(string) - i:] return string
if not string:
def check(candidate): assert candidate('') == '' assert candidate('x') == 'x' assert candidate('xyz') == 'xyzyx' assert candidate('xyx') == 'xyx' assert candidate('jerry') == 'jerryrrej' def test_check(): check(make_palindrome) test_check()
humaneval-HumanEval_107_even_odd_palindrome.json-L31
js
//Given a positive integer n, return an array that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // Example 1: // >>> even_odd_palindrome(3) // [1, 2] // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // Example 2: // >>> even_odd_palindrome(12) // [4, 6] // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // Note: // 1. 1 <= n <= 10^3 // 2. returned array has the number of even and odd integer palindromes respectively. function even_odd_palindrome(n){ var pal = []; var isPalindrome = function(x){ var y = x.toString().split('').reverse().join(''); return y == x; } for(var i = 1; i <= n; i++){ if(isPalindrome(i)){ pal.push(i); } } var odd = 0; var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){
} else{ odd++; } } return [even, odd]; }
even++;
const assert = require('node:assert'); function test() { let candidate = even_odd_palindrome; assert.deepEqual(candidate(123),[8, 13]); assert.deepEqual(candidate(12),[4, 6]); assert.deepEqual(candidate(3),[1, 2]); assert.deepEqual(candidate(63),[6, 8]); assert.deepEqual(candidate(25),[5, 6]); assert.deepEqual(candidate(19),[4, 6]); assert.deepEqual(candidate(9),[4, 5]); assert.deepEqual(candidate(1),[0, 1]); } test();
humaneval-HumanEval_7_filter_by_substring.json-L12
js
//Filter an input array of strings only for ones that contain given substring // >>> filter_by_substring([], "a") // [] // >>> filter_by_substring(["abc", "bacd", "cde", "array"], "a") // ["abc", "bacd", "array"] function filter_by_substring(strings, substring){ var filtered = []; for(var i = 0; i < strings.length; i++){ if(strings[i].includes(substring)){ filtered.push(strings[i]); }
return filtered; }
}
const assert = require('node:assert'); function test() { let candidate = filter_by_substring; assert.deepEqual(candidate([], "john"),[]); assert.deepEqual(candidate(["xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx"], "xxx"),["xxx", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["xxx", "asd", "aaaxxy", "john doe", "xxxAAA", "xxx"], "xx"),["xxx", "aaaxxy", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["grunt", "trumpet", "prune", "gruesome"], "run"),["grunt", "prune"]); } test();
humaneval-HumanEval_10_make_palindrome.json-L19
js
//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. // >>> make_palindrome("") // "" // >>> make_palindrome("cat") // "catac" // >>> make_palindrome("cata") // "catac" function make_palindrome(string){ var string_length = string.length; var is_palindrome = function(s){ return s == s.split("").reverse().join(""); }; var i = string_length; while(i > 0){ if(is_palindrome(string.substring(0, i))){
} i--; } return string; }
return string + string.substring(0, string_length - i).split("").reverse().join("");
const assert = require('node:assert'); function test() { let candidate = make_palindrome; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("x"),"x"); assert.deepEqual(candidate("xyz"),"xyzyx"); assert.deepEqual(candidate("xyx"),"xyx"); assert.deepEqual(candidate("jerry"),"jerryrrej"); } test();
humaneval-HumanEval_90_next_smallest.json-L21
py
from typing import List, Optional def next_smallest(lst: List[int]) -> Optional[int]: """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. >>> next_smallest([1, 2, 3, 4, 5]) 2 >>> next_smallest([5, 1, 4, 3, 2]) 2 >>> next_smallest([]) None >>> next_smallest([1, 1]) None """ if len(lst) < 2: return None min1 = min(lst[0], lst[1]) min2 = max(lst[0], lst[1])
if lst[i] < min1: min2 = min1 min1 = lst[i] elif lst[i] < min2: min2 = lst[i] return min2 if min1 != min2 else None
for i in range(2, len(lst)):
def check(candidate): assert candidate([1, 2, 3, 4, 5]) == 2 assert candidate([5, 1, 4, 3, 2]) == 2 assert candidate([]) == None assert candidate([1, 1]) == None assert candidate([1, 1, 1, 1, 0]) == 1 assert candidate([1, 1]) == None assert candidate([-35, 34, 12, -45]) == -35 def test_check(): check(next_smallest) test_check()
humaneval-HumanEval_35_max_element.json-L11
py
from typing import List def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ max_elem = l[0]
if l[i] > max_elem: max_elem = l[i] return max_elem
for i in range(1, len(l)):
def check(candidate): assert candidate([1, 2, 3]) == 3 assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124 def test_check(): check(max_element) test_check()
humaneval-HumanEval_106_f.json-L22
js
//Implement the function f that takes n as a parameter, // and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f(5) // [1, 2, 6, 24, 15] function f(n){ var result = []; var sum = 0; var factorial = 1; for(var i = 1; i <= n; i++){ if(i % 2 == 0){ for(var j = 1; j <= i; j++){ factorial *= j; } result.push(factorial); factorial = 1; }else{ for(var k = 1; k <= i; k++){
} result.push(sum); sum = 0; } } return result; }
sum += k;
const assert = require('node:assert'); function test() { let candidate = f; assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]); assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]); assert.deepEqual(candidate(1),[1]); assert.deepEqual(candidate(3),[1, 2, 6]); } test();
humaneval-HumanEval_90_next_smallest.json-L25
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_6_parse_nested_parens.json-L12
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0; var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){
if (level > maxlevel){ maxlevel = level; } } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
level += 1;
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_137_compare_one.json-L20
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 {
} } else if (typeof a === "string" && typeof b === "number"){ 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; } } }
return undefined;
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_56_correct_bracketing.json-L16
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 for bracket in brackets:
num_left_brackets += 1 elif bracket == '>': num_left_brackets -= 1 if num_left_brackets < 0: return False return num_left_brackets == 0
if bracket == '<':
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_85_add.json-L12
js
//Given a non-empty array of integers lst. add the even elements that are at odd indices.. // Examples: // >>> add([4, 2, 6, 7]) // 2 function add(lst){ var add = 0; for(var i = 0; i < lst.length; i++) { if(lst[i] % 2 == 0 && i % 2 != 0) { add += lst[i]; } }
}
return add;
const assert = require('node:assert'); function test() { let candidate = add; assert.deepEqual(candidate([4, 88]),88); assert.deepEqual(candidate([4, 5, 6, 7, 2, 122]),122); assert.deepEqual(candidate([4, 0, 6, 7]),0); assert.deepEqual(candidate([4, 4, 6, 8]),12); } test();
humaneval-HumanEval_19_sort_numbers.json-L27
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_143_words_in_sentence.json-L37
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) {
} } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
ans.append(word + " ");
} 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_74_total_match.json-L23
js
//Write a function that accepts two arrays of strings and returns the array that has // total number of chars in the all strings of the array less than the other array. // if the two arrays have the same number of chars, return the first array. // Examples // >>> total_match([], []) // [] // >>> total_match(["hi", "admin"], ["hI", "Hi"]) // ["hI", "Hi"] // >>> total_match(["hi", "admin"], ["hi", "hi", "admin", "project"]) // ["hi", "admin"] // >>> total_match(["hi", "admin"], ["hI", "hi", "hi"]) // ["hI", "hi", "hi"] // >>> total_match(["4"], ["1", "2", "3", "4", "5"]) // ["4"] function total_match(lst1, lst2){ let sum_lst1 = 0; let sum_lst2 = 0; for(let item of lst1){ sum_lst1 += item.length; } for(let item of lst2){ sum_lst2 += item.length;
if(sum_lst1 > sum_lst2){ return lst2; } else{ return lst1; } }
}
const assert = require('node:assert'); function test() { let candidate = total_match; assert.deepEqual(candidate([], []),[]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi"]),["hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi", "admin", "project"]),["hi", "admin"]); assert.deepEqual(candidate(["4"], ["1", "2", "3", "4", "5"]),["4"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "Hi"]),["hI", "Hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hi"]),["hI", "hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hii"]),["hi", "admin"]); assert.deepEqual(candidate([], ["this"]),[]); assert.deepEqual(candidate(["this"], []),[]); } test();
humaneval-HumanEval_93_encode.json-L13
js
//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" function encode(message){ const vowels = "aeiou";
for(let i = 0; i < message.length; i++){ let letter = message[i]; if(vowels.includes(letter.toLowerCase())){ let newIndex = (letter.charCodeAt(0) + 2 - (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))) % 26; letter = String.fromCharCode(newIndex + (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))); } result += letter.toUpperCase() === letter ? letter.toLowerCase() : letter.toUpperCase(); } return result; }
let result = "";
const assert = require('node:assert'); function test() { let candidate = encode; assert.deepEqual(candidate("TEST"),"tgst"); assert.deepEqual(candidate("Mudasir"),"mWDCSKR"); assert.deepEqual(candidate("YES"),"ygs"); assert.deepEqual(candidate("This is a message"),"tHKS KS C MGSSCGG"); assert.deepEqual(candidate("I DoNt KnOw WhAt tO WrItE"),"k dQnT kNqW wHcT Tq wRkTg"); } test();
humaneval-HumanEval_31_is_prime.json-L33
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 true if a given number is prime, and false otherwise. // >>> isPrime((6l)) // (false) // >>> isPrime((101l)) // (true) // >>> isPrime((11l)) // (true) // >>> isPrime((13441l)) // (true) // >>> isPrime((61l)) // (true) // >>> isPrime((4l)) // (false) // >>> isPrime((1l)) // (false) public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long i = 5; while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; }
} }
return true;
} public static void main(String[] args) { assert(isPrime((6l)) == (false)); assert(isPrime((101l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((13441l)) == (true)); assert(isPrime((61l)) == (true)); assert(isPrime((4l)) == (false)); assert(isPrime((1l)) == (false)); assert(isPrime((5l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((17l)) == (true)); assert(isPrime((85l)) == (false)); assert(isPrime((77l)) == (false)); assert(isPrime((255379l)) == (false)); } }
humaneval-HumanEval_155_even_odd_count.json-L21
py
from typing import Tuple def even_odd_count(num: int) -> Tuple[int, int]: """Given an integer. return a tuple that has the number of even and odd digits respectively. Example: >>> even_odd_count(-12) (1, 1) >>> even_odd_count(123) (1, 2) """ num_str = str(abs(num)) even_count = 0 odd_count = 0 for ch in num_str: digit = int(ch) if digit % 2 == 0: even_count += 1 else: odd_count += 1
return even_count, odd_count
def check(candidate): assert candidate(7) == (0, 1) assert candidate(-78) == (1, 1) assert candidate(3452) == (2, 2) assert candidate(346211) == (3, 3) assert candidate(-345821) == (3, 3) assert candidate(-2) == (1, 0) assert candidate(-45347) == (2, 3) assert candidate(0) == (1, 0) def test_check(): check(even_odd_count) test_check()
humaneval-HumanEval_124_valid_date.json-L33
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 true; } return false; }
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();