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_129_minPath.json-L38
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++){
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; }
path.push(currCell);
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_160_do_algebra.json-L31
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]; operand.splice(count + 1, 1); operator.splice(count, 1); count = 0;
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; }
do_again = true;
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_149_sorted_list_sum.json-L44
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_23_strlen.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return length of given string // >>> stringLength(("")) // (0l) // >>> stringLength(("abc")) // (3l) public static long strlen(String string) { return string.length();
}
}
} public static void main(String[] args) { assert(strlen(("")) == (0l)); assert(strlen(("x")) == (1l)); assert(strlen(("asdasnakj")) == (9l)); } }
humaneval-HumanEval_31_is_prime.json-L34
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){ if (n==1) { return false; } if (n==2) { return true; } if (n%2==0) { return false; } var limit = Math.sqrt(n); for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false; }
return true; }
}
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_119_match_parens.json-L23
js
//You are given an array of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> match_parens(["()(", ")"]) // "Yes" // >>> match_parens([")", ")"]) // "No" function match_parens(lst){ const open = '('; const close = ')'; const is_good = (s) => { let stack = []; for (let p of s){ if (p === open){ stack.push(p); } else if (p === close){
return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
if (stack.length === 0){
const assert = require('node:assert'); function test() { let candidate = match_parens; assert.deepEqual(candidate(["()(", ")"]),"Yes"); assert.deepEqual(candidate([")", ")"]),"No"); assert.deepEqual(candidate(["(()(())", "())())"]),"No"); assert.deepEqual(candidate([")())", "(()()("]),"Yes"); assert.deepEqual(candidate(["(())))", "(()())(("]),"Yes"); assert.deepEqual(candidate(["()", "())"]),"No"); assert.deepEqual(candidate(["(()(", "()))()"]),"Yes"); assert.deepEqual(candidate(["((((", "((())"]),"No"); assert.deepEqual(candidate([")(()", "(()("]),"No"); assert.deepEqual(candidate([")(", ")("]),"No"); assert.deepEqual(candidate(["(", ")"]),"Yes"); assert.deepEqual(candidate([")", "("]),"Yes"); } test();
humaneval-HumanEval_140_fix_spaces.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string text, replace all spaces in it with underscores, // and if a string has more than 2 consecutive spaces, // then replace all consecutive spaces with - // >>> fixSpaces((" Example")) // ("Example") // >>> fixSpaces((" Example 1")) // ("Example_1") // >>> fixSpaces((" Example 2")) // ("_Example_2") // >>> fixSpaces((" Example 3")) // ("_Example-3") public static String fixSpaces(String text) { String result = text.replace(" ", "_"); int i = 0; while (i < result.length() - 2) {
result = result.substring(0, i) + "-" + result.substring(i + 3); } i++; } return result; } }
if (result.charAt(i) == '_' && result.charAt(i + 1) == '_' && result.charAt(i + 2) == '_') {
} public static void main(String[] args) { assert(fixSpaces(("Example")).equals(("Example"))); assert(fixSpaces(("Mudasir Hanif ")).equals(("Mudasir_Hanif_"))); assert(fixSpaces(("Yellow Yellow Dirty Fellow")).equals(("Yellow_Yellow__Dirty__Fellow"))); assert(fixSpaces(("Exa mple")).equals(("Exa-mple"))); assert(fixSpaces((" Exa 1 2 2 mple")).equals(("-Exa_1_2_2_mple"))); } }
humaneval-HumanEval_33_sort_third.json-L41
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) { min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j));
} else { l_s.add(l_r.get(i - j)); } } return l_s; } }
j++;
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_46_fib4.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 { // The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fib4(0) -> 0 // fib4(1) -> 0 // fib4(2) -> 2 // fib4(3) -> 0 // fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). // Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. // >>> fib4((5l)) // (4l) // >>> fib4((6l)) // (8l) // >>> fib4((7l)) // (14l) public static long fib4(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 2; if (n == 3) return 0;
} }
return fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4);
} public static void main(String[] args) { assert(fib4((5l)) == (4l)); assert(fib4((8l)) == (28l)); assert(fib4((10l)) == (104l)); assert(fib4((12l)) == (386l)); } }
humaneval-HumanEval_104_unique_digits.json-L14
js
//Given an array of positive integers x. return a sorted array of all // elements that hasn't any even digit. // Note: Returned array should be sorted in increasing order. // For example: // >>> unique_digits([15, 33, 1422, 1]) // [1, 15, 33] // >>> unique_digits([152, 323, 1422, 10]) // [] function unique_digits(x){ let result = [] for(let i = 0; i < x.length; i++){ let num = x[i].toString() if(num.indexOf('2') === -1 && num.indexOf('4') === -1 && num.indexOf('6') === -1 && num.indexOf('8') === -1 && num.indexOf('0') === -1){
} } return result.sort(function(a, b){return a-b}) }
result.push(x[i])
const assert = require('node:assert'); function test() { let candidate = unique_digits; assert.deepEqual(candidate([15, 33, 1422, 1]),[1, 15, 33]); assert.deepEqual(candidate([152, 323, 1422, 10]),[]); assert.deepEqual(candidate([12345, 2033, 111, 151]),[111, 151]); assert.deepEqual(candidate([135, 103, 31]),[31, 135]); } test();
humaneval-HumanEval_146_specialFilter.json-L10
js
//Write a function that takes an array of numbers as input and returns // the number of elements in the array that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter([15, -73, 14, -15]) // 1 // >>> specialFilter([33, -2, -3, 45, 21, 109]) // 2 function specialFilter(nums){
for(let i = 0; i < nums.length; i++){ let num = nums[i]; let firstDigit = nums[i].toString()[0]; let lastDigit = nums[i].toString()[nums[i].toString().length - 1]; if(num > 10 && firstDigit % 2 !== 0 && lastDigit % 2 !== 0){ count++; } } return count; }
let count = 0;
const assert = require('node:assert'); function test() { let candidate = specialFilter; assert.deepEqual(candidate([5, -2, 1, -5]),0); assert.deepEqual(candidate([15, -73, 14, -15]),1); assert.deepEqual(candidate([33, -2, -3, 45, 21, 109]),2); assert.deepEqual(candidate([43, -12, 93, 125, 121, 109]),4); assert.deepEqual(candidate([71, -2, -33, 75, 21, 19]),3); assert.deepEqual(candidate([1]),0); assert.deepEqual(candidate([]),0); } test();
humaneval-HumanEval_142_sum_squares.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 { // " // This function will take an array array list of integers. For all entries in the array list, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the array list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // Examples: // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)) // >>> lst // (long)new ArrayList<Long>(Arrays.asList()) // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)) public static long sumSquares(ArrayList<Long> lst) { int sz = lst.size(); for (int i = 0; i < sz; i++) { if (i % 3 == 0) { lst.set(i, lst.get(i) * lst.get(i)); } else if (i % 4 == 0) { lst.set(i, lst.get(i) * lst.get(i) * lst.get(i)); } }
for (int i = 0; i < sz; i++) { ans += lst.get(i); } return ans; } }
long ans = 0;
} public static void main(String[] args) { assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (6l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)9l)))) == (14l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l)))) == (9l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l)))) == (-3l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)0l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)))) == (-126l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-56l, (long)-99l, (long)1l, (long)0l, (long)-2l)))) == (3030l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)-1l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-16l, (long)-9l, (long)-2l, (long)36l, (long)36l, (long)26l, (long)-20l, (long)25l, (long)-40l, (long)20l, (long)-4l, (long)12l, (long)-26l, (long)35l, (long)37l)))) == (-14196l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-3l, (long)17l, (long)-1l, (long)-15l, (long)13l, (long)-1l, (long)14l, (long)-14l, (long)-12l, (long)-5l, (long)14l, (long)-14l, (long)6l, (long)13l, (long)11l, (long)16l, (long)16l, (long)4l, (long)10l)))) == (-1448l)); } }
humaneval-HumanEval_15_string_sequence.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 { // Return a string containing space-delimited numbers starting from 0 upto n inclusive. // >>> stringSequence((0l)) // ("0") // >>> stringSequence((5l)) // ("0 1 2 3 4 5") public static String stringSequence(long n) { String result = ""; for (long i = 0; i <= n; i++) {
} return result.trim(); } }
result += i + " ";
} public static void main(String[] args) { assert(stringSequence((0l)).equals(("0"))); assert(stringSequence((3l)).equals(("0 1 2 3"))); assert(stringSequence((10l)).equals(("0 1 2 3 4 5 6 7 8 9 10"))); } }
humaneval-HumanEval_18_how_many_times.json-L9
js
//Find how many times a given substring can be found in the original string. Count overlaping cases. // >>> how_many_times("", "a") // 0 // >>> how_many_times("aaa", "a") // 3 // >>> how_many_times("aaaa", "aa") // 3 function how_many_times(string, substring){
var count = 0; while(string.indexOf(substring, i) !== -1){ count++; i = string.indexOf(substring, i) + 1; } return count; }
var i = 0;
const assert = require('node:assert'); function test() { let candidate = how_many_times; assert.deepEqual(candidate("", "x"),0); assert.deepEqual(candidate("xyxyxyx", "x"),4); assert.deepEqual(candidate("cacacacac", "cac"),4); assert.deepEqual(candidate("john doe", "john"),1); } test();
humaneval-HumanEval_53_add.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Add two numbers x and y // >>> add((2l), (3l)) // (5l) // >>> add((5l), (7l)) // (12l) public static long add(long x, long y) { return x + y;
}
}
} public static void main(String[] args) { assert(add((0l), (1l)) == (1l)); assert(add((1l), (0l)) == (1l)); assert(add((2l), (3l)) == (5l)); assert(add((5l), (7l)) == (12l)); assert(add((7l), (5l)) == (12l)); } }
humaneval-HumanEval_95_check_dict_case.json-L46
js
//Given an object, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; } } else if (case_type == 1){ if (key != key.toUpperCase()){ return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } } else{ return false;
} return true; }
}
const assert = require('node:assert'); function test() { let candidate = check_dict_case; assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true); assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false); assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false); assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false); assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true); assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true); assert.deepEqual(candidate({}),false); } test();
humaneval-HumanEval_126_is_sorted.json-L57
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; } }
seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
else {
} 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_160_do_algebra.json-L37
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]; operand.splice(count + 1, 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);
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; }
count = 0;
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_69_search.json-L28
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 = {}; for (var i=0; i<lst.length; i++){ 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; }
}
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_142_sum_squares.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 { // " // This function will take an array array list of integers. For all entries in the array list, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the array list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // Examples: // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)) // >>> lst // (long)new ArrayList<Long>(Arrays.asList()) // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)) public static long sumSquares(ArrayList<Long> lst) { int sz = lst.size(); for (int i = 0; i < sz; i++) { if (i % 3 == 0) { lst.set(i, lst.get(i) * lst.get(i)); } else if (i % 4 == 0) { lst.set(i, lst.get(i) * lst.get(i) * lst.get(i)); }
long ans = 0; for (int i = 0; i < sz; i++) { ans += lst.get(i); } return ans; } }
}
} public static void main(String[] args) { assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (6l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)9l)))) == (14l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l)))) == (9l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l)))) == (-3l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)0l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)))) == (-126l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-56l, (long)-99l, (long)1l, (long)0l, (long)-2l)))) == (3030l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)-1l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-16l, (long)-9l, (long)-2l, (long)36l, (long)36l, (long)26l, (long)-20l, (long)25l, (long)-40l, (long)20l, (long)-4l, (long)12l, (long)-26l, (long)35l, (long)37l)))) == (-14196l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-3l, (long)17l, (long)-1l, (long)-15l, (long)13l, (long)-1l, (long)14l, (long)-14l, (long)-12l, (long)-5l, (long)14l, (long)-14l, (long)6l, (long)13l, (long)11l, (long)16l, (long)16l, (long)4l, (long)10l)))) == (-1448l)); } }
humaneval-HumanEval_62_derivative.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 { // xs represent coefficients of a polynomial. // xs[0] + xs[1] * x + xs[2] * x^2 + .... // Return derivative of this polynomial in the same form. // >>> derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)12l, (long)20l))) // >>> derivative((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l))) public static ArrayList<Long> derivative(ArrayList<Long> xs) { ArrayList<Long> ans = new ArrayList<Long>(); for (int i = 1; i < xs.size(); i++) { ans.add(xs.get(i) * i); } return ans; }
}
} public static void main(String[] args) { assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)12l, (long)20l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l, (long)0l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)0l, (long)16l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_37_sort_even.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the odd indicies, while its values at the even indicies are equal // to the values of the even indicies of l, but sorted. // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>(); ArrayList<Long> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } index++; }
index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else { res.add(num); } index++; } return res; } }
Collections.sort(evenIndexed);
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_156_int_to_mini_roman.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 a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d";
} 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 -= 500;
} 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_99_closest_integer.json-L23
js
//Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closest_integer("10") // 10 // >>> closest_integer("15.3") // 15 // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){ return Math.floor(value); }else{ return Math.ceil(value); } }else{
return Math.floor(value); }else{ return Math.ceil(value); } } }
if(value - Math.floor(value) > -0.5){
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_134_check_if_last_char_is_a_letter.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 { // Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // Examples: // >>> checkIfLastCharIsALetter(("apple pie")) // (false) // >>> checkIfLastCharIsALetter(("apple pi e")) // (true) // >>> checkIfLastCharIsALetter(("apple pi e ")) // (false) // >>> checkIfLastCharIsALetter(("")) // (false) public static boolean checkIfLastCharIsALetter(String txt) { if (txt.length() == 0) { return false;
int len = txt.length(); if (txt.substring(len - 1, len).matches("[A-Z]") || txt.substring(len - 1, len).matches("[a-z]")) { if (len == 1) { return true; } if (txt.substring(len - 2, len - 1).matches(" ")) { return true; } } return false; } }
}
} public static void main(String[] args) { assert(checkIfLastCharIsALetter(("apple")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e")) == (true)); assert(checkIfLastCharIsALetter(("eeeee")) == (false)); assert(checkIfLastCharIsALetter(("A")) == (true)); assert(checkIfLastCharIsALetter(("Pumpkin pie ")) == (false)); assert(checkIfLastCharIsALetter(("Pumpkin pie 1")) == (false)); assert(checkIfLastCharIsALetter(("")) == (false)); assert(checkIfLastCharIsALetter(("eeeee e ")) == (false)); assert(checkIfLastCharIsALetter(("apple pie")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e ")) == (false)); } }
humaneval-HumanEval_158_find_max.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 { // 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) { Set<Character> uniqueCharacters = new HashSet<Character>(); for (char c : word.toCharArray()) { uniqueCharacters.add(c); } wordsToUniqueCharacters.put(word, uniqueCharacters.size()); } words.sort(new Comparator<String>() {
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); } }
@Override
} 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_25_factorize.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 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);
} } if (n > 1) factors.add(n); return factors; } }
n /= d;
} public static void main(String[] args) { assert(factorize((2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(factorize((4l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(factorize((8l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))))); assert(factorize((57l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l))))); assert(factorize((3249l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)19l, (long)19l))))); assert(factorize((185193l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((20577l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)3l))))); } }
humaneval-HumanEval_115_max_fill.json-L28
js
//You are given a rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // Example 1: // >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) // 6 // Example 2: // >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) // 5 // Example 3: // >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) // 0 // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 function max_fill(grid, capacity){ var maxFill = 0; var sum = 0; var c = 1; var r = grid.length; var c = grid[0].length;
sum = 0; for(var j = 0; j < c; j++){ sum += grid[i][j]; } maxFill += Math.ceil(sum/capacity); } return maxFill; }
for(var i = 0; i < r; i++){
const assert = require('node:assert'); function test() { let candidate = max_fill; assert.deepEqual(candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1),6); assert.deepEqual(candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2),5); assert.deepEqual(candidate([[0, 0, 0], [0, 0, 0]], 5),0); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2),4); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9),2); } test();
humaneval-HumanEval_123_get_odd_collatz.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 { // 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()]);
Collections.sort(ans); return ans; } }
ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr));
} 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_78_hex_key.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You have been tasked to write a function that receives // a hexadecimal number as a string and counts the number of hexadecimal // digits that are primes (prime number, or a prime, is a natural number // greater than 1 that is not a product of two smaller natural numbers). // Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. // Prime numbers are 2, 3, 5, 7, 11, 13, 17,... // So you have to determine a number of the following digits: 2, 3, 5, 7, // B (=decimal 11), D (=decimal 13). // Note: you may assume the input is always correct or empty string, // and symbols A,B,C,D,E,F are always uppercase. // Examples: // >>> hexKey(("AB")) // (1l) // >>> hexKey(("1077E")) // (2l) // >>> hexKey(("ABED1A33")) // (4l) // >>> hexKey(("123456789ABCDEF0")) // (6l) // >>> hexKey(("2020")) // (2l) public static long hexKey(String num) {
for (int i = 0; i < num.length(); i++) { if (num.charAt(i) == '2' || num.charAt(i) == '3' || num.charAt(i) == '5' || num.charAt(i) == '7' || num.charAt(i) == 'B' || num.charAt(i) == 'D') { result++; } } return result; } }
long result = 0;
} public static void main(String[] args) { assert(hexKey(("AB")) == (1l)); assert(hexKey(("1077E")) == (2l)); assert(hexKey(("ABED1A33")) == (4l)); assert(hexKey(("2020")) == (2l)); assert(hexKey(("123456789ABCDEF0")) == (6l)); assert(hexKey(("112233445566778899AABBCCDDEEFF00")) == (12l)); } }
humaneval-HumanEval_93_encode.json-L25
py
def encode(message: str) -> str: """ 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' """ def swap_case(ch: str) -> str: if ch.isupper(): return ch.lower() else: return ch.upper() def encode_vowel(ch: str) -> str: if ch.lower() in 'aeiou': if ch.lower() in 'wxyz': return ch.lower() return chr(ord(ch) + 2)
return ''.join(map(lambda ch: encode_vowel(swap_case(ch)), message))
return ch
def check(candidate): assert candidate('TEST') == 'tgst' assert candidate('Mudasir') == 'mWDCSKR' assert candidate('YES') == 'ygs' assert candidate('This is a message') == 'tHKS KS C MGSSCGG' assert candidate('I DoNt KnOw WhAt tO WrItE') == 'k dQnT kNqW wHcT Tq wRkTg' def test_check(): check(encode) test_check()
humaneval-HumanEval_82_prime_length.json-L20
js
//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 function prime_length(string){ let length = string.length; let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]; if (primes.includes(length)){ return true; } else { return false; }
}
const assert = require('node:assert'); function test() { let candidate = prime_length; assert.deepEqual(candidate("Hello"),true); assert.deepEqual(candidate("abcdcba"),true); assert.deepEqual(candidate("kittens"),true); assert.deepEqual(candidate("orange"),false); assert.deepEqual(candidate("wow"),true); assert.deepEqual(candidate("world"),true); assert.deepEqual(candidate("MadaM"),true); assert.deepEqual(candidate("Wow"),true); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("HI"),true); assert.deepEqual(candidate("go"),true); assert.deepEqual(candidate("gogo"),false); assert.deepEqual(candidate("aaaaaaaaaaaaaaa"),false); assert.deepEqual(candidate("Madam"),true); assert.deepEqual(candidate("M"),false); assert.deepEqual(candidate("0"),false); } test();
humaneval-HumanEval_56_correct_bracketing.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 { // brackets is a string of "<" and ">". // return true if every opening bracket has a corresponding closing bracket. // >>> correctBracketing(("<")) // (false) // >>> correctBracketing(("<>")) // (true) // >>> correctBracketing(("<<><>>")) // (true) // >>> correctBracketing(("><<>")) // (false) public static boolean correctBracketing(String brackets) { int open = 0; for (int i = 0; i < brackets.length(); i++) { char c = brackets.charAt(i); if (c == '<') { open++; } else { open--; } if (open < 0) { return false;
} return open == 0; } }
}
} public static void main(String[] args) { assert(correctBracketing(("<>")) == (true)); assert(correctBracketing(("<<><>>")) == (true)); assert(correctBracketing(("<><><<><>><>")) == (true)); assert(correctBracketing(("<><><<<><><>><>><<><><<>>>")) == (true)); assert(correctBracketing(("<<<><>>>>")) == (false)); assert(correctBracketing(("><<>")) == (false)); assert(correctBracketing(("<")) == (false)); assert(correctBracketing(("<<<<")) == (false)); assert(correctBracketing((">")) == (false)); assert(correctBracketing(("<<>")) == (false)); assert(correctBracketing(("<><><<><>><>><<>")) == (false)); assert(correctBracketing(("<><><<><>><>>><>")) == (false)); } }
humaneval-HumanEval_41_car_race_collision.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 { // Imagine a road that's a perfectly straight infinitely long line. // n cars are driving left to right; simultaneously, a different set of n cars // are driving right to left. The two sets of cars start out being very far from // each other. All cars move in the same speed. Two cars are said to collide // when a car that's moving left to right hits a car that's moving right to left. // However, the cars are infinitely sturdy and strong; as a result, they continue moving // in their trajectory as if they did not collide. // This function outputs the number of such collisions. public static long carRaceCollision(long n) { BigInteger nBigInteger = BigInteger.valueOf(n);
return nSquared.longValue(); } }
BigInteger nSquared = nBigInteger.multiply(nBigInteger);
} public static void main(String[] args) { assert(carRaceCollision((2l)) == (4l)); assert(carRaceCollision((3l)) == (9l)); assert(carRaceCollision((4l)) == (16l)); assert(carRaceCollision((8l)) == (64l)); assert(carRaceCollision((10l)) == (100l)); } }
humaneval-HumanEval_118_get_closest_vowel.json-L21
py
def get_closest_vowel(word: str) -> str: """You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: >>> get_closest_vowel('yogurt') 'u' >>> get_closest_vowel('FULL') 'U' >>> get_closest_vowel('quick') '' >>> get_closest_vowel('ab') '' """ if len(word) < 3:
for i in range(len(word) - 2, 0, -1): if word[i] in 'aeiouAEIOU' and word[i-1] not in 'aeiouAEIOU' and word[i+1] not in 'aeiouAEIOU': return word[i] return ''
return ''
def check(candidate): assert candidate('yogurt') == 'u' assert candidate('full') == 'u' assert candidate('easy') == '' assert candidate('eAsy') == '' assert candidate('ali') == '' assert candidate('bad') == 'a' assert candidate('most') == 'o' assert candidate('ab') == '' assert candidate('ba') == '' assert candidate('quick') == '' assert candidate('anime') == 'i' assert candidate('Asia') == '' assert candidate('Above') == 'o' def test_check(): check(get_closest_vowel) test_check()
humaneval-HumanEval_146_specialFilter.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 { // 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 lastDigit = h.getLastDigit(x); return firstDigit % 2 != 0 && lastDigit % 2 != 0; }).count(); } }
long firstDigit = h.getFirstDigit(x);
} 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_119_match_parens.json-L35
py
from typing import List def match_parens(lst: List[str]) -> str: """ You are given a list of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string '(())()' is good, while the string '())' is not. Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. Examples: >>> match_parens(['()(', ')']) 'Yes' >>> match_parens([')', ')']) 'No' """ s1, s2 = lst strings = [s1 + s2, s2 + s1] for s in strings: open_parens = 0 close_parens = 0 for c in s: if c == '(': open_parens += 1 elif c == ')': if open_parens: open_parens -= 1 else: close_parens += 1 if open_parens == 0 and close_parens == 0: return 'Yes'
return 'No'
def check(candidate): assert candidate(['()(', ')']) == 'Yes' assert candidate([')', ')']) == 'No' assert candidate(['(()(())', '())())']) == 'No' assert candidate([')())', '(()()(']) == 'Yes' assert candidate(['(())))', '(()())((']) == 'Yes' assert candidate(['()', '())']) == 'No' assert candidate(['(()(', '()))()']) == 'Yes' assert candidate(['((((', '((())']) == 'No' assert candidate([')(()', '(()(']) == 'No' assert candidate([')(', ')(']) == 'No' assert candidate(['(', ')']) == 'Yes' assert candidate([')', '(']) == 'Yes' def test_check(): check(match_parens) test_check()
humaneval-HumanEval_111_histogram.json-L29
py
from typing import Dict def histogram(test: str) -> Dict[str, int]: """Given a string representing a space separated lowercase letters, return a dictionary 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('') { } """ letters = {} most_count = 0 result = {} for letter in test.split(): letters[letter] = letters.get(letter, 0) + 1 if letters[letter] >= most_count: most_count = letters[letter] for letter in letters:
result[letter] = most_count return result
if letters[letter] == most_count:
def check(candidate): assert candidate('a b b a') == { 'a': 2, 'b': 2 } assert candidate('a b c a b') == { 'a': 2, 'b': 2 } assert candidate('a b c d g') == { 'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('b b b b a') == { 'b': 4 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('') == { } assert candidate('a') == { 'a': 1 } def test_check(): check(histogram) test_check()
humaneval-HumanEval_158_find_max.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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) { Set<Character> uniqueCharacters = new HashSet<Character>(); 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 words.get(0); } }
return compareResult;
} 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_43_pairs_sum_to_zero.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 { // pairs_sum_to_zero takes an array array list of integers as an input. // it returns true if there are two distinct elements in the array list that // sum to zero, and false otherwise. // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l)))) // (true) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean pairsSumToZero(ArrayList<Long> l) { for (int i = 0; i < l.size(); i++) { for (int j = i + 1; j < l.size(); j++) { if (l.get(i) + l.get(j) == 0) { return true; } } } return false; }
}
} public static void main(String[] args) { assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)30l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)31l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)30l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)31l)))) == (false)); } }
humaneval-HumanEval_0_has_close_elements.json-L16
js
//Check if in given array of numbers, are any two numbers closer to each other than // given threshold. // >>> has_close_elements([1.0, 2.0, 3.0], 0.5) // false // >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) // true function has_close_elements(numbers, threshold){ for(var i = 0; i < numbers.length; i++){ for(var j = i + 1; j < numbers.length; j++){ if(Math.abs(numbers[i] - numbers[j]) < threshold){ return true; } } } return false;
}
const assert = require('node:assert'); function test() { let candidate = has_close_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3),true); assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05),false); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95),true); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8),false); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1),true); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0),true); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5),false); } test();
humaneval-HumanEval_16_count_distinct_characters.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 { // Given a string, find out how many distinct characters (regardless of case) does it consist of // >>> countDistinctCharacters(("xyzXYZ")) // (3l) // >>> countDistinctCharacters(("Jerry")) // (4l) public static long countDistinctCharacters(String string) { long result = 0; string = string.toLowerCase(); Set<Character> set = new HashSet<Character>(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); set.add(c); } result = set.size();
} }
return result;
} public static void main(String[] args) { assert(countDistinctCharacters(("")) == (0l)); assert(countDistinctCharacters(("abcde")) == (5l)); assert(countDistinctCharacters(("abcdecadeCADE")) == (5l)); assert(countDistinctCharacters(("aaaaAAAAaaaa")) == (1l)); assert(countDistinctCharacters(("Jerry jERRY JeRRRY")) == (5l)); } }
humaneval-HumanEval_141_file_name_check.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 { // 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: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result; } String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; }
if (count > 3) { return result; } if (name.length() == 0) { return result; } if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes"; } }
}
} public static void main(String[] args) { assert(fileNameCheck(("example.txt")).equals(("Yes"))); assert(fileNameCheck(("1example.dll")).equals(("No"))); assert(fileNameCheck(("s1sdf3.asd")).equals(("No"))); assert(fileNameCheck(("K.dll")).equals(("Yes"))); assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes"))); assert(fileNameCheck(("His12FILE94.exe")).equals(("No"))); assert(fileNameCheck(("_Y.txt")).equals(("No"))); assert(fileNameCheck(("?aREYA.exe")).equals(("No"))); assert(fileNameCheck(("/this_is_valid.dll")).equals(("No"))); assert(fileNameCheck(("this_is_valid.wow")).equals(("No"))); assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes"))); assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No"))); assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No"))); assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No"))); assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No"))); assert(fileNameCheck(("all.exe.txt")).equals(("No"))); assert(fileNameCheck(("I563_No.exe")).equals(("Yes"))); assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes"))); assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes"))); assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No"))); assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No"))); assert(fileNameCheck(("final..txt")).equals(("No"))); assert(fileNameCheck(("final132")).equals(("No"))); assert(fileNameCheck(("_f4indsartal132.")).equals(("No"))); assert(fileNameCheck((".txt")).equals(("No"))); assert(fileNameCheck(("s.")).equals(("No"))); } }
humaneval-HumanEval_71_triangle_area.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 { // Given the lengths of the three sides of a triangle. Return the area of // the triangle rounded to 2 decimal points if the three sides form a valid triangle. // Otherwise return -1 // Three sides make a valid triangle when the sum of any two sides is greater // than the third side. // Example: // >>> triangleArea((3l), (4l), (5l)) // (6.0f) // >>> triangleArea((1l), (2l), (10l)) // (float)-1l public static float triangleArea(long a, long b, long c) {
float s = (a + b + c) / 2.0f; float area = (float)Math.sqrt(s * (s - a) * (s - b) * (s - c)); return (float)Math.round(area * 100) / 100; } return -1; } }
if(a + b > c && a + c > b && b + c > a) {
} public static void main(String[] args) { assert(triangleArea((3l), (4l), (5l)) == (6.0f)); assert(triangleArea((1l), (2l), (10l)) == (float)-1l); assert(triangleArea((4l), (8l), (5l)) == (8.18f)); assert(triangleArea((2l), (2l), (2l)) == (1.73f)); assert(triangleArea((1l), (2l), (3l)) == (float)-1l); assert(triangleArea((10l), (5l), (7l)) == (16.25f)); assert(triangleArea((2l), (6l), (3l)) == (float)-1l); assert(triangleArea((1l), (1l), (1l)) == (0.43f)); assert(triangleArea((2l), (2l), (10l)) == (float)-1l); } }
humaneval-HumanEval_108_count_nums.json-L25
js
//Write a function count_nums which takes an array of integers and returns // the number of elements which has a sum of digits > 0. // If a number is negative, then its first signed digit will be negative: // e.g. -123 has signed digits -1, 2, and 3. // >>> count_nums([]) // 0 // >>> count_nums([-1, 11, -11]) // 1 // >>> count_nums([1, 1, 2]) // 3 function count_nums(arr){ if(!arr.length) { return 0; } var count = 0; for(var i = 0; i < arr.length; i++) { var sum = 0; var str = arr[i].toString(); if(str[0] === '-') { sum += Number(str[0] + str[1]); for(var j = 2; j < str.length; j++) { sum += Number(str[j]); } } else {
sum += Number(str[k]); } } if(sum > 0) { count++; } } return count; }
for(var k = 0; k < str.length; k++) {
const assert = require('node:assert'); function test() { let candidate = count_nums; assert.deepEqual(candidate([]),0); assert.deepEqual(candidate([-1, -2, 0]),0); assert.deepEqual(candidate([1, 1, 2, -2, 3, 4, 5]),6); assert.deepEqual(candidate([1, 6, 9, -6, 0, 1, 5]),5); assert.deepEqual(candidate([1, 100, 98, -7, 1, -1]),4); assert.deepEqual(candidate([12, 23, 34, -45, -56, 0]),5); assert.deepEqual(candidate([0, 1]),1); assert.deepEqual(candidate([1]),1); } test();
humaneval-HumanEval_141_file_name_check.json-L25
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 == '.':
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'
e_count += 1
def check(candidate): assert candidate('example.txt') == 'Yes' assert candidate('1example.dll') == 'No' assert candidate('s1sdf3.asd') == 'No' assert candidate('K.dll') == 'Yes' assert candidate('MY16FILE3.exe') == 'Yes' assert candidate('His12FILE94.exe') == 'No' assert candidate('_Y.txt') == 'No' assert candidate('?aREYA.exe') == 'No' assert candidate('/this_is_valid.dll') == 'No' assert candidate('this_is_valid.wow') == 'No' assert candidate('this_is_valid.txt') == 'Yes' assert candidate('this_is_valid.txtexe') == 'No' assert candidate('#this2_i4s_5valid.ten') == 'No' assert candidate('@this1_is6_valid.exe') == 'No' assert candidate('this_is_12valid.6exe4.txt') == 'No' assert candidate('all.exe.txt') == 'No' assert candidate('I563_No.exe') == 'Yes' assert candidate('Is3youfault.txt') == 'Yes' assert candidate('no_one#knows.dll') == 'Yes' assert candidate('1I563_Yes3.exe') == 'No' assert candidate('I563_Yes3.txtt') == 'No' assert candidate('final..txt') == 'No' assert candidate('final132') == 'No' assert candidate('_f4indsartal132.') == 'No' assert candidate('.txt') == 'No' assert candidate('s.') == 'No' def test_check(): check(file_name_check) test_check()
humaneval-HumanEval_96_count_up_to.json-L22
js
//Implement a function that takes an non-negative integer and returns an array of the first n // integers that are prime numbers and less than n. // for example: // >>> count_up_to(5) // [2, 3] // >>> count_up_to(11) // [2, 3, 5, 7] // >>> count_up_to(0) // [] // >>> count_up_to(20) // [2, 3, 5, 7, 11, 13, 17, 19] // >>> count_up_to(1) // [] // >>> count_up_to(18) // [2, 3, 5, 7, 11, 13, 17] function count_up_to(n){ if (n < 2) return []; var output = [2]; for (var i = 3; i < n; i += 2){ var prime = true; for (var j = 3; j < i; j += 2){
prime = false; break; } } if (prime) output.push(i); } return output; }
if (i % j === 0){
const assert = require('node:assert'); function test() { let candidate = count_up_to; assert.deepEqual(candidate(5),[2, 3]); assert.deepEqual(candidate(6),[2, 3, 5]); assert.deepEqual(candidate(7),[2, 3, 5]); assert.deepEqual(candidate(10),[2, 3, 5, 7]); assert.deepEqual(candidate(0),[]); assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]); assert.deepEqual(candidate(1),[]); assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]); assert.deepEqual(candidate(101),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]); } test();
humaneval-HumanEval_160_do_algebra.json-L38
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 two array lists operator, and operand. The first array list has basic algebra operations, and // the second array list is an array array list of integers. Use the two given array lists 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 array list = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array list is equal to the length of operand array list minus one. // Operand is an array array list of of non-negative integers. // Operator array list has at least one operator, and operand array list has at least two operands. public static long doAlgebra(ArrayList<String> op, ArrayList<Long> operand) { ArrayList<Long> list = new ArrayList<>(); list.add(operand.get(0)); for (int i = 0; i < op.size(); i++) { if (op.get(i).equals("+")) list.add(operand.get(i + 1)); else if (op.get(i).equals("-")) list.add(-operand.get(i + 1)); else if (op.get(i).equals("*")) list.set(list.size() - 1, list.get(list.size() - 1) * operand.get(i + 1)); else if (op.get(i).equals("//"))
else if (op.get(i).equals("**")) list.set(list.size() - 1, (long) Math.pow(list.get(list.size() - 1), operand.get(i + 1))); } return list.stream().mapToLong(x -> x).sum(); } }
list.set(list.size() - 1, list.get(list.size() - 1) / operand.get(i + 1));
} public static void main(String[] args) { assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"**", (String)"*", (String)"+"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (37l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"+", (String)"*", (String)"-"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (9l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"//", (String)"*"))), (new ArrayList<Long>(Arrays.asList((long)7l, (long)3l, (long)4l)))) == (8l)); } }
humaneval-HumanEval_37_sort_even.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the odd indicies, while its values at the even indicies are equal // to the values of the even indicies of l, but sorted. // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>();
int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } index++; } Collections.sort(evenIndexed); index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else { res.add(num); } index++; } return res; } }
ArrayList<Long> evenIndexed = new ArrayList<Long>();
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_153_Strongest_Extension.json-L22
py
from typing import List def Strongest_Extension(class_name: str, extensions: List[str]) -> str: """You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -1). Example: >>> Strongest_Extension('my_class', ['AA', 'Be', 'CC']) 'my_class.AA' """ best_strength, best_extension = -1, ''
n_uppercase = sum(1 for c in extension if c.isupper()) n_lowercase = sum(1 for c in extension if c.islower()) if n_uppercase - n_lowercase > best_strength: best_strength = n_uppercase - n_lowercase best_extension = extension return class_name + '.' + best_extension
for extension in extensions:
def check(candidate): assert candidate('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) == 'Watashi.eIGHt8OKe' assert candidate('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg']) == 'Boku123.YEs.WeCaNe' assert candidate('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321']) == '__YESIMHERE.NuLl__' assert candidate('K', ['Ta', 'TAR', 't234An', 'cosSo']) == 'K.TAR' assert candidate('__HAHA', ['Tab', '123', '781345', '-_-']) == '__HAHA.123' assert candidate('YameRore', ['HhAas', 'okIWILL123', 'WorkOut', 'Fails', '-_-']) == 'YameRore.okIWILL123' assert candidate('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) == 'finNNalLLly.WoW' assert candidate('_', ['Bb', '91245']) == '_.Bb' assert candidate('Sp', ['671235', 'Bb']) == 'Sp.671235' def test_check(): check(Strongest_Extension) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L38
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:
elif x > 2.7: final.append('B') elif x > 2.3: 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
final.append('B+')
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_54_same_chars.json-L24
js
//Check if two words have the same characters. // >>> same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") // true // >>> same_chars("abcd", "dddddddabc") // true // >>> same_chars("dddddddabc", "abcd") // true // >>> same_chars("eabcd", "dddddddabc") // false // >>> same_chars("abcd", "dddddddabce") // false // >>> same_chars("eabcdzzzz", "dddzzzzzzzddddabc") // false function same_chars(s0, s1){ let res = true; for(let i = 0; i < s0.length; i++){ if(s1.indexOf(s0[i]) === -1){ res = false; break; } } for(let i = 0; i < s1.length; i++){ if(s0.indexOf(s1[i]) === -1){
break; } } return res; }
res = false;
const assert = require('node:assert'); function test() { let candidate = same_chars; assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddeddabc"),true); assert.deepEqual(candidate("abcd", "dddddddabc"),true); assert.deepEqual(candidate("dddddddabc", "abcd"),true); assert.deepEqual(candidate("eabcd", "dddddddabc"),false); assert.deepEqual(candidate("abcd", "dddddddabcf"),false); assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddddabc"),false); assert.deepEqual(candidate("aabb", "aaccc"),false); } test();
humaneval-HumanEval_153_Strongest_Extension.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 will be given the name of a class (a string) and an array array list of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array list. // For example, if you are given "Slices" as the class and an array array list of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC")))) // ("my_class.AA") public static String StrongestExtension(String class_name, ArrayList<String> extensions) { if (extensions.size() == 0) { return class_name; } int strength = Integer.MIN_VALUE; String strongest = ""; for (String s : extensions) { int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count(); int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count(); int diff = cap - sm; if (diff > strength) { strength = diff;
} } return class_name + "." + strongest; } }
strongest = s;
} public static void main(String[] args) { assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe"))); assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe"))); assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__"))); assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR"))); assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123"))); assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123"))); assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW"))); assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb"))); assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235"))); } }
humaneval-HumanEval_39_prime_fib.json-L50
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_11_string_xor.json-L22
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++) { if (arrayA[k] !== arrayB[k]) { arrayXOR.push(1); } else { arrayXOR.push(0);
} result = arrayXOR.join(''); return result; }
}
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_131_digits.json-L18
js
//Given a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits(1) // 1 // >>> digits(4) // 0 // >>> digits(235) // 15 function digits(n){ if(!n){ return "error"; } if(n < 0){ return "error"; } var temp = 0;
var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp; odd = false; } } if(odd){ return 0; } return prod; }
var prod = 1;
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_144_simplify.json-L17
py
def simplify(x: str, n: str) -> bool: """Your task is to implement a function that will simplify the expression x * n. The function returns True if x * n evaluates to a whole number and False otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. >>> simplify('1/5', '5/1') True >>> simplify('1/6', '2/1') False >>> simplify('7/10', '10/2') False """ x_num, x_denom = [int(i) for i in x.split('/')]
return (x_num * n_num) % (x_denom * n_denom) == 0
n_num, n_denom = [int(i) for i in n.split('/')]
def check(candidate): assert candidate('1/5', '5/1') == True assert candidate('1/6', '2/1') == False assert candidate('5/1', '3/1') == True assert candidate('7/10', '10/2') == False assert candidate('2/10', '50/10') == True assert candidate('7/2', '4/2') == True assert candidate('11/6', '6/1') == True assert candidate('2/3', '5/2') == False assert candidate('5/2', '3/5') == False assert candidate('2/4', '8/4') == True assert candidate('2/4', '4/2') == True assert candidate('1/5', '5/1') == True assert candidate('1/5', '1/5') == False def test_check(): check(simplify) test_check()
humaneval-HumanEval_151_double_the_difference.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 { // Given an array array list of numbers, return the sum of squares of the numbers // in the array list that are odd. Ignore numbers that are negative or not integers. // >>> doubleTheDifference((new ArrayList<Float>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)0l)))) // (10l) // >>> doubleTheDifference((new ArrayList<Float>(Arrays.asList((long)-1l, (long)-2l, (long)0l)))) // (0l) // >>> doubleTheDifference((new ArrayList<Float>(Arrays.asList((long)9l, (long)-2l)))) // (81l) // >>> doubleTheDifference((new ArrayList<Float>(Arrays.asList((long)0l)))) // (0l) // If the input array list is empty, return 0. public static long doubleTheDifference(ArrayList<Float> lst) {
} }
return lst.stream().filter(x -> x%2 == 1).mapToLong(Math::round).map(x -> x*x).sum();
} public static void main(String[] args) { assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList()))) == (0l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)5.0f, (float)4.0f)))) == (25l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)0.1f, (float)0.2f, (float)0.3f)))) == (0l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)-10.0f, (float)-20.0f, (float)-30.0f)))) == (0l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)-1.0f, (float)-2.0f, (float)8.0f)))) == (0l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)0.2f, (float)3.0f, (float)5.0f)))) == (34l)); assert(doubleTheDifference((new ArrayList<Float>(Arrays.asList((float)-9.0f, (float)-7.0f, (float)-5.0f, (float)-3.0f, (float)-1.0f, (float)1.0f, (float)3.0f, (float)5.0f, (float)7.0f, (float)9.0f)))) == (165l)); } }
humaneval-HumanEval_153_Strongest_Extension.json-L20
js
//You will be given the name of a class (a string) and an array of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array. // For example, if you are given "Slices" as the class and an array of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> Strongest_Extension("my_class", ["AA", "Be", "CC"]) // "my_class.AA" function Strongest_Extension(class_name, extensions){ var output = class_name + "."; var min_strength = 1;
var strength = -1*(extensions[i].replace(/[^A-Z]/g, "").length - extensions[i].replace(/[^a-z]/g, "").length); if (strength < min_strength) { min_strength = strength; output = class_name + "." + extensions[i]; } } return output; }
for (var i = 0; i < extensions.length; i++) {
const assert = require('node:assert'); function test() { let candidate = Strongest_Extension; assert.deepEqual(candidate("Watashi", ["tEN", "niNE", "eIGHt8OKe"]),"Watashi.eIGHt8OKe"); assert.deepEqual(candidate("Boku123", ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]),"Boku123.YEs.WeCaNe"); assert.deepEqual(candidate("__YESIMHERE", ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]),"__YESIMHERE.NuLl__"); assert.deepEqual(candidate("K", ["Ta", "TAR", "t234An", "cosSo"]),"K.TAR"); assert.deepEqual(candidate("__HAHA", ["Tab", "123", "781345", "-_-"]),"__HAHA.123"); assert.deepEqual(candidate("YameRore", ["HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"]),"YameRore.okIWILL123"); assert.deepEqual(candidate("finNNalLLly", ["Die", "NowW", "Wow", "WoW"]),"finNNalLLly.WoW"); assert.deepEqual(candidate("_", ["Bb", "91245"]),"_.Bb"); assert.deepEqual(candidate("Sp", ["671235", "Bb"]),"Sp.671235"); } test();
humaneval-HumanEval_105_by_length.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 an array array list of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array array list, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))) // (new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))) // If the array array list is empty, return an empty array array list: // >>> byLength((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<String>(Arrays.asList())) // If the array array list has any strange number ignore it: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))) // (new ArrayList<String>(Arrays.asList((String)"One"))) public static ArrayList<String> byLength(ArrayList<Long> arr) { String[] a = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; ArrayList<String> res = new ArrayList<String>(); ArrayList<Long> good = new ArrayList<Long>(); for (Long i : arr) { if (i >= 1 && i <= 9) { good.add(i);
} good.sort(new Comparator<Long>() { public int compare(Long i1, Long i2) { return i1.compareTo(i2); } }); Collections.reverse(good); for (Long i : good) { res.add(a[i.intValue() - 1]); } return res; } }
}
} public static void main(String[] args) { assert(byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))).equals((new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList())))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))).equals((new ArrayList<String>(Arrays.asList((String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)3l, (long)2l)))).equals((new ArrayList<String>(Arrays.asList((String)"Three", (String)"Two", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)9l, (long)4l, (long)8l)))).equals((new ArrayList<String>(Arrays.asList((String)"Nine", (String)"Eight", (String)"Four"))))); } }
humaneval-HumanEval_138_is_equal_to_sum_even.json-L17
js
//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> is_equal_to_sum_even(4) // false // >>> is_equal_to_sum_even(6) // false // >>> is_equal_to_sum_even(8) // true function is_equal_to_sum_even(n){ let m =0; for(let i=2;i<n;i+=2){ for(let j=2;j<n;j+=2){ for(let k=2;k<n;k+=2){ for(let l=2;l<n;l+=2){ if((i+j+k+l)==n){ m=1;
} } } } } if(m==1){ return true; } else{ return false; } }
break;
const assert = require('node:assert'); function test() { let candidate = is_equal_to_sum_even; assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),true); assert.deepEqual(candidate(11),false); assert.deepEqual(candidate(12),true); assert.deepEqual(candidate(13),false); assert.deepEqual(candidate(16),true); } test();
humaneval-HumanEval_87_get_row.json-L22
js
//You are given a 2 dimensional data, as a nested arrays, // 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 array, // and return array of arrays, [(x1, y1), (x2, y2) ...] such that // each array 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]] function get_row(lst, x){ let coordinates = []; for (let i = 0; i < lst.length; i++){ let array = lst[i]; for (let j = 0; j < array.length; j++){ if (lst[i][j] === x){
} } } return coordinates.sort(function(a, b){ return a[0] - b[0] || b[1] - a[1]; }); }
coordinates.push([i, j]);
const assert = require('node:assert'); function test() { let candidate = get_row; assert.deepEqual(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.deepEqual(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.deepEqual(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.deepEqual(candidate([], 1),[]); assert.deepEqual(candidate([[1]], 2),[]); assert.deepEqual(candidate([[], [1], [1, 2, 3]], 3),[[2, 2]]); } test();
humaneval-HumanEval_152_compare.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 { // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two array array lists of scores and guesses of equal length, where each index shows a match. // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))) // >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l))) public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) { ArrayList<Long> result = new ArrayList<Long>(); for (int i = 0; i < game.size(); i++) { if (game.get(i) != guess.get(i)) { result.add(Math.abs(game.get(i) - guess.get(i))); } else { result.add((long)0); }
return result; } }
}
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_106_f.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Implement the function f that takes n as a parameter, // and returns an array array list of size n, such that the value of the element at index i is the factorial of i if i is even // 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((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))) public static ArrayList<Long> f(long n) { ArrayList<Long> ret = new ArrayList<Long>(); for (long i = 1l; i <= n; i++) { long v = 0l; if (i % 2 == 0) { v = 1l; for (long j = 2l; j <= i; j++) { v *= j; } } else { v = (i * (i + 1l)) / 2l; } ret.add(v); }
} }
return ret;
} public static void main(String[] args) { assert(f((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))))); assert(f((7l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l, (long)720l, (long)28l))))); assert(f((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); assert(f((3l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l))))); } }
humaneval-HumanEval_113_odd_count.json-L21
py
from typing import List def odd_count(lst: List[str]) -> List[str]: """Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count(['1234567']) ['the number of odd elements 4n the str4ng 4 of the 4nput.'] >>> odd_count(['3', '11111111']) ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.'] """ output = [] for i in range(len(lst)): count = 0 for j in range(len(lst[i])): if int(lst[i][j]) % 2 != 0: count += 1 output.append(f"the number of odd elements {count}n the str{count}ng {count} of the {count}nput.")
return output
def check(candidate): assert candidate(['1234567']) == ['the number of odd elements 4n the str4ng 4 of the 4nput.'] assert candidate(['3', '11111111']) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.'] assert candidate(['271', '137', '314']) == ['the number of odd elements 2n the str2ng 2 of the 2nput.', 'the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.'] def test_check(): check(odd_count) test_check()
humaneval-HumanEval_72_will_it_fly.json-L38
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) { return false; }
if (q.get(i) != q.get(q.size() - 1 - i)) { return false; } } return true; } }
for (int i = 0; i < q.size() / 2; i++) {
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_61_correct_bracketing.json-L15
js
//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 function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){
} else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false; } } } if (opens.length == 0){ return true; } else { return false; } }
opens.push(brackets[i]);
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_90_next_smallest.json-L13
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){
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; }
if(lst.length<=1){
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_137_compare_one.json-L19
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """
if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
if isinstance(a, int) and isinstance(b, int):
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_55_fib.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 { // Return n-th Fibonacci number. // >>> fib((10l)) // (55l) // >>> fib((1l)) // (1l) // >>> fib((8l)) // (21l) public static long fib(long n) { if (n == 0) { return 0l; } else if (n == 1) { return 1l; } else { return Problem.fib((n - 1)) + Problem.fib((n - 2)); } }
}
} public static void main(String[] args) { assert(fib((10l)) == (55l)); assert(fib((1l)) == (1l)); assert(fib((8l)) == (21l)); assert(fib((11l)) == (89l)); assert(fib((12l)) == (144l)); } }
humaneval-HumanEval_0_has_close_elements.json-L11
py
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool: """ Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """
for j in range(i + 1, len(numbers)): if abs(numbers[i] - numbers[j]) < threshold: return True return False
for i in range(len(numbers)):
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) == True assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False def test_check(): check(has_close_elements) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L52
js
//It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array of GPAs for some students and you have to write // a function that can output an array of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) // ["A+", "B", "C-", "C", "A-"] function numerical_letter_grade(grades){ var grades_array = []; for (var i = 0; i < grades.length; i++){ if (grades[i] >= 4.0){ grades_array.push("A+"); } else if (grades[i] > 3.7){ grades_array.push("A"); } else if (grades[i] > 3.3){ grades_array.push("A-"); } else if (grades[i] > 3.0){ grades_array.push("B+"); } else if (grades[i] > 2.7){ grades_array.push("B"); } else if (grades[i] > 2.3){ grades_array.push("B-"); } else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); } 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; }
}
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_75_is_multiply_prime.json-L20
py
def is_multiply_prime(a: int) -> bool: """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: >>> is_multiply_prime(30) True 30 = 2 * 3 * 5 """ n = a d = 2 prime_factors = [] while d * d <= n: if n % d == 0: prime_factors.append(d) n //= d else: d += 1 if n > 1:
if len(prime_factors) == 3: return True else: return False
prime_factors.append(n)
def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(105) == True assert candidate(126) == False assert candidate(729) == False assert candidate(891) == False assert candidate(1001) == True def test_check(): check(is_multiply_prime) test_check()
humaneval-HumanEval_107_even_odd_palindrome.json-L23
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++){
pal.push(i); } } var odd = 0; var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){ even++; } else{ odd++; } } return [even, odd]; }
if(isPalindrome(i)){
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_143_words_in_sentence.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> wordsInSentence(("This is a test")) // ("is") // Example 2: // >>> wordsInSentence(("lets go for swimming")) // ("go for") // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters public static String wordsInSentence(String sentence) { StringBuilder ans = new StringBuilder(); String[] words = sentence.split(" "); int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; boolean isPrime; for (String word : words) { isPrime = false; for (int prime : primes) { if (word.length() == prime) { isPrime = true; break; }
if (isPrime) { ans.append(word + " "); } } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
}
} public static void main(String[] args) { assert(wordsInSentence(("This is a test")).equals(("is"))); assert(wordsInSentence(("lets go for swimming")).equals(("go for"))); assert(wordsInSentence(("there is no place available here")).equals(("there is no place"))); assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein"))); assert(wordsInSentence(("go for it")).equals(("go for it"))); assert(wordsInSentence(("here")).equals((""))); assert(wordsInSentence(("here is")).equals(("is"))); } }
humaneval-HumanEval_30_get_positive.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 { // Return only positive numbers in the array list. // >>> getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)-4l, (long)5l, (long)6l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)6l))) // >>> getPositive((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)3l, (long)9l, (long)123l, (long)1l))) public static ArrayList<Long> getPositive(ArrayList<Long> l) { return (new ArrayList<Long>(l.stream().filter(x -> x > 0).collect(Collectors.toList()))); }
}
} public static void main(String[] args) { assert(getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)4l, (long)5l, (long)6l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)5l, (long)6l))))); assert(getPositive((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)3l, (long)3l, (long)9l, (long)123l, (long)1l))))); assert(getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(getPositive((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_3_below_zero.json-L20
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 return False print(below_zero([1, 2, 3]))
print(below_zero([1, 2, -4, 5]))
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_13_greatest_common_divisor.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 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_151_double_the_difference.json-L19
py
from typing import List def double_the_difference(lst: List[float]) -> int: """ Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. >>> double_the_difference([1, 3, 2, 0]) 10 >>> double_the_difference([-1, -2, 0]) 0 >>> double_the_difference([9, -2]) 81 >>> double_the_difference([0]) 0 If the input list is empty, return 0. """
for x in lst: if not x < 0 and x % 2 == 1: sum += x * x return sum
sum = 0
def check(candidate): assert candidate([]) == 0 assert candidate([5.0, 4.0]) == 25 assert candidate([0.1, 0.2, 0.3]) == 0 assert candidate([-10.0, -20.0, -30.0]) == 0 assert candidate([-1.0, -2.0, 8.0]) == 0 assert candidate([0.2, 3.0, 5.0]) == 34 assert candidate([-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0]) == 165 def test_check(): check(double_the_difference) test_check()
humaneval-HumanEval_55_fib.json-L12
js
//Return n-th Fibonacci number. // >>> fib(10) // 55 // >>> fib(1) // 1 // >>> fib(8) // 21 function fib(n){ if(n <= 2){ return 1; } else {
} }
return fib(n-1) + fib(n-2);
const assert = require('node:assert'); function test() { let candidate = fib; assert.deepEqual(candidate(10),55); assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(8),21); assert.deepEqual(candidate(11),89); assert.deepEqual(candidate(12),144); } test();
humaneval-HumanEval_148_bf.json-L31
py
from typing import Tuple def bf(planet1: str, planet2: str) -> Tuple[str, ...]: """ There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty tuple if planet1 or planet2 are not correct planet names. Examples >>> bf('Jupiter', 'Neptune') ('Saturn', 'Uranus') >>> bf('Earth', 'Mercury') 'Venus' >>> bf('Mercury', 'Uranus') ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') """ planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune') if planet1 not in planets or planet2 not in planets: return () start = planets.index(planet1) end = planets.index(planet2) if start < end: planets = planets[start+1:end] else: planets = planets[end+1:start]
return tuple(planets)
def check(candidate): assert candidate('Jupiter', 'Neptune') == ('Saturn', 'Uranus') assert candidate('Earth', 'Mercury') == ('Venus',) assert candidate('Mercury', 'Uranus') == ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') assert candidate('Neptune', 'Venus') == ('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus') assert candidate('Earth', 'Earth') == () assert candidate('Mars', 'Earth') == () assert candidate('Jupiter', 'Makemake') == () def test_check(): check(bf) test_check()
humaneval-HumanEval_156_int_to_mini_roman.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 { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000;
if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
}
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_124_valid_date.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 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 // >>> validDate(("03-11-2000")) // (true) // >>> validDate(("15-01-2012")) // (false) // >>> validDate(("04-0-2040")) // (false) // >>> validDate(("06-04-2020")) // (true) // >>> validDate(("06/04/2020")) // (false) public static boolean validDate(String date) { boolean valid_date = false; if (date.equals("")) return valid_date; String[] parts = date.split("-"); if (parts.length != 3) return valid_date; try { int month = Integer.parseInt(parts[0]); int day = Integer.parseInt(parts[1]); int year = Integer.parseInt(parts[2]); if (month < 1 || month > 12) return valid_date; if (month == 2) {
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { if (day < 1 || day > 31) return valid_date; } else { if (day < 1 || day > 30) return valid_date; } valid_date = true; } catch (Exception e) { valid_date = false; } return valid_date; } }
if (day < 1 || day > 29) return valid_date;
} public static void main(String[] args) { assert(validDate(("03-11-2000")) == (true)); assert(validDate(("15-01-2012")) == (false)); assert(validDate(("04-0-2040")) == (false)); assert(validDate(("06-04-2020")) == (true)); assert(validDate(("01-01-2007")) == (true)); assert(validDate(("03-32-2011")) == (false)); assert(validDate(("")) == (false)); assert(validDate(("04-31-3000")) == (false)); assert(validDate(("06-06-2005")) == (true)); assert(validDate(("21-31-2000")) == (false)); assert(validDate(("04-12-2003")) == (true)); assert(validDate(("04122003")) == (false)); assert(validDate(("20030412")) == (false)); assert(validDate(("2003-04")) == (false)); assert(validDate(("2003-04-12")) == (false)); assert(validDate(("04-2003")) == (false)); } }
humaneval-HumanEval_156_int_to_mini_roman.json-L39
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]; break; } } }
}
return output;
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_135_can_arrange.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 { // Create a function which returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array array list will not contain // duplicate values. // Examples: // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) // (3l) // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (-1l) public static long canArrange(ArrayList<Long> arr) { long p = -1l; for (int i = arr.size() - 1; i > 0; i--) { if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break; } } return p; }
}
} public static void main(String[] args) { assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) == (3l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)5l)))) == (-1l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)10l)))) == (2l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)4l, (long)8l, (long)5l, (long)7l, (long)3l)))) == (4l)); assert(canArrange((new ArrayList<Long>(Arrays.asList()))) == (-1l)); } }
humaneval-HumanEval_128_prod_signs.json-L17
js
//You are given an array arr of integers and you need to return // sum of magnitudes of integers multiplied by product of all signs // of each number in the array, represented by 1, -1 or 0. // Note: return undefined for empty arr. // Example: // >>> prod_signs([1, 2, 2, -4]) // 9 // >>> prod_signs([0, 1]) // 0 // >>> prod_signs([]) // undefined function prod_signs(arr){ var total = 0; var len = arr.length; var pro = 1; if(len == 0){
} else{ for(var i = 0; i < len; i++){ total += Math.abs(arr[i]); if(arr[i] < 0){ pro *= -1; } else if(arr[i] == 0){ pro *= 0; } } total *= pro; return total; } }
return undefined;
const assert = require('node:assert'); function test() { let candidate = prod_signs; assert.deepEqual(candidate([1, 2, 2, -4]),-9); assert.deepEqual(candidate([0, 1]),0); assert.deepEqual(candidate([1, 1, 1, 2, 3, -1, 1]),-10); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([2, 4, 1, 2, -1, -1, 9]),20); assert.deepEqual(candidate([-1, 1, -1, 1]),4); assert.deepEqual(candidate([-1, 1, 1, 1]),-4); assert.deepEqual(candidate([-1, 1, 1, 0]),0); } test();
humaneval-HumanEval_147_get_max_triples.json-L24
js
//You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> get_max_triples(5) // 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). function get_max_triples(n){ let result = 0; let arr = []; for(let i = 1; i<=n; i++){ arr.push(i*i-i+1); } for(let i = 0; i<arr.length; i++){ for(let j = i+1; j<arr.length; j++){ for(let k = j+1; k<arr.length; k++){ if((arr[i]+arr[j]+arr[k])%3 === 0){ result++; } }
} return result; }
}
const assert = require('node:assert'); function test() { let candidate = get_max_triples; assert.deepEqual(candidate(5),1); assert.deepEqual(candidate(6),4); assert.deepEqual(candidate(10),36); assert.deepEqual(candidate(100),53361); } test();
humaneval-HumanEval_31_is_prime.json-L33
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){ if (n==1) { return false; } if (n==2) { return true; } if (n%2==0) { return false; } var limit = Math.sqrt(n); for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false;
} return true; }
}
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_3_below_zero.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 { // You're given an array array 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. // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (false) // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l)))) // (true) public static boolean belowZero(ArrayList<Long> operations) { long balance = 0; for (long op : operations) { balance += op; if (balance < 0) { return true; } } return false;
}
}
} public static void main(String[] args) { assert(belowZero((new ArrayList<Long>(Arrays.asList()))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-3l, (long)1l, (long)2l, (long)-3l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l, (long)6l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-5l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-2l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (true)); } }
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L20
js
//Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // Examples: // >>> check_if_last_char_is_a_letter("apple pie") // false // >>> check_if_last_char_is_a_letter("apple pi e") // true // >>> check_if_last_char_is_a_letter("apple pi e ") // false // >>> check_if_last_char_is_a_letter("") // false function check_if_last_char_is_a_letter(txt){ var result=txt.split(" "); if(result[result.length-1].length==1 && result[result.length-1].match(/[a-z]/i)){ return true; } return false;
}
const assert = require('node:assert'); function test() { let candidate = check_if_last_char_is_a_letter; assert.deepEqual(candidate("apple"),false); assert.deepEqual(candidate("apple pi e"),true); assert.deepEqual(candidate("eeeee"),false); assert.deepEqual(candidate("A"),true); assert.deepEqual(candidate("Pumpkin pie "),false); assert.deepEqual(candidate("Pumpkin pie 1"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("eeeee e "),false); assert.deepEqual(candidate("apple pie"),false); assert.deepEqual(candidate("apple pi e "),false); } test();
humaneval-HumanEval_44_change_base.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Change numerical base of input number x to base. // return string representation after the conversion. // base numbers are less than 10. // >>> changeBase((8l), (3l)) // ("22") // >>> changeBase((8l), (2l)) // ("1000") // >>> changeBase((7l), (2l)) // ("111") public static String changeBase(long x, long base) { if (x<0 || base<2 || base>9) { throw new IllegalArgumentException("bad input"); } if (x==0) { return "0"; } StringBuilder sb = new StringBuilder(); while (x>0) { sb.append(x%base); x = x/base; } return sb.reverse().toString();
}
}
} public static void main(String[] args) { assert(changeBase((8l), (3l)).equals(("22"))); assert(changeBase((9l), (3l)).equals(("100"))); assert(changeBase((234l), (2l)).equals(("11101010"))); assert(changeBase((16l), (2l)).equals(("10000"))); assert(changeBase((8l), (2l)).equals(("1000"))); assert(changeBase((7l), (2l)).equals(("111"))); assert(changeBase((2l), (3l)).equals(("2"))); assert(changeBase((3l), (4l)).equals(("3"))); assert(changeBase((4l), (5l)).equals(("4"))); assert(changeBase((5l), (6l)).equals(("5"))); assert(changeBase((6l), (7l)).equals(("6"))); assert(changeBase((7l), (8l)).equals(("7"))); } }
humaneval-HumanEval_158_find_max.json-L38
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) { Set<Character> uniqueCharacters = new HashSet<Character>(); 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);
} 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_107_even_odd_palindrome.json-L34
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){ even++; } else{
} } return [even, odd]; }
odd++;
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_83_starts_one_ends.json-L7
js
//Given a positive integer n, return the count of the numbers of n-digit // positive integers that start or end with 1. function starts_one_ends(n){ let ones = []; for(let i = Math.pow(10, n-1); i < Math.pow(10, n); i++){ if(i.toString().startsWith('1') || i.toString().endsWith('1')){
} } return ones.length; }
ones.push(i);
const assert = require('node:assert'); function test() { let candidate = starts_one_ends; assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(2),18); assert.deepEqual(candidate(3),180); assert.deepEqual(candidate(4),1800); assert.deepEqual(candidate(5),18000); } test();
humaneval-HumanEval_20_find_closest_elements.json-L12
js
//From a supplied array 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] function find_closest_elements(numbers){ let closest = Math.abs(numbers[0] - numbers[1]); let a = numbers[0]; let b = numbers[1]; for (let i = 0; i < numbers.length; i++) {
if (Math.abs(numbers[i] - numbers[j]) < closest) { closest = Math.abs(numbers[i] - numbers[j]); a = numbers[i]; b = numbers[j]; } } } return a > b ? [b, a] : [a, b]; }
for (let j = i + 1; j < numbers.length; j++) {
const assert = require('node:assert'); function test() { let candidate = find_closest_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]); } test();
humaneval-HumanEval_129_minPath.json-L57
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){
} 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; }
neighbours.push(grid[x][y - 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_72_will_it_fly.json-L29
js
//Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> will_it_fly([1, 2], 5) // false // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> will_it_fly([3, 2, 3], 1) // false // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> will_it_fly([3, 2, 3], 9) // true // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> will_it_fly([3], 5) // true // # 3 is less than the maximum possible weight, and it's balanced. function will_it_fly(q, w){ let sum = 0; let balanced = true; for(let i = 0; i < q.length; i++){ sum += q[i]; } for(let i = 0; i < q.length; i++){ if(q[i] !== q[q.length - 1 - i]){ balanced = false; break; } } return balanced && sum <= w;
}
const assert = require('node:assert'); function test() { let candidate = will_it_fly; assert.deepEqual(candidate([3, 2, 3], 9),true); assert.deepEqual(candidate([1, 2], 5),false); assert.deepEqual(candidate([3], 5),true); assert.deepEqual(candidate([3, 2, 3], 1),false); assert.deepEqual(candidate([1, 2, 3], 6),false); assert.deepEqual(candidate([5], 5),true); } test();
humaneval-HumanEval_11_string_xor.json-L14
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++) {
} for (var k = 0; k < arrayA.length; k++) { if (arrayA[k] !== arrayB[k]) { arrayXOR.push(1); } else { arrayXOR.push(0); } } result = arrayXOR.join(''); return result; }
arrayB.push(parseInt(b[j]));
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_46_fib4.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 { // The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fib4(0) -> 0 // fib4(1) -> 0 // fib4(2) -> 2 // fib4(3) -> 0 // fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). // Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. // >>> fib4((5l)) // (4l) // >>> fib4((6l)) // (8l) // >>> fib4((7l)) // (14l) public static long fib4(long n) {
if (n == 1) return 0; if (n == 2) return 2; if (n == 3) return 0; return fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4); } }
if (n == 0) return 0;
} public static void main(String[] args) { assert(fib4((5l)) == (4l)); assert(fib4((8l)) == (28l)); assert(fib4((10l)) == (104l)); assert(fib4((12l)) == (386l)); } }
humaneval-HumanEval_147_get_max_triples.json-L26
js
//You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> get_max_triples(5) // 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). function get_max_triples(n){ let result = 0; let arr = []; for(let i = 1; i<=n; i++){ arr.push(i*i-i+1); } for(let i = 0; i<arr.length; i++){ for(let j = i+1; j<arr.length; j++){ for(let k = j+1; k<arr.length; k++){ if((arr[i]+arr[j]+arr[k])%3 === 0){ result++; } } } }
}
return result;
const assert = require('node:assert'); function test() { let candidate = get_max_triples; assert.deepEqual(candidate(5),1); assert.deepEqual(candidate(6),4); assert.deepEqual(candidate(10),36); assert.deepEqual(candidate(100),53361); } test();