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_44_change_base.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 { // 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_88_sort_array.json-L16
js
//Given an array of non-negative integers, return a cojs of the given array after sorting, // you will sort the given array in ascending order if the sum( first index value, last index value) is odd, // or sort it in descending order if the sum( first index value, last index value) is even. // Note: // * don't change the given array. // Examples: // >>> sort_array([]) // [] // >>> sort_array([5]) // [5] // >>> sort_array([2, 4, 3, 0, 1, 5]) // [0, 1, 2, 3, 4, 5] // >>> sort_array([2, 4, 3, 0, 1, 5, 6]) // [6, 5, 4, 3, 2, 1, 0] function sort_array(array){
let newArr = []; if(sum % 2 === 0){ newArr = array.sort(function(a, b){return b - a;}); }else{ newArr = array.sort(function(a, b){return a - b;}); } return newArr; }
let sum = array[0] + array[array.length - 1];
const assert = require('node:assert'); function test() { let candidate = sort_array; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5]),[5]); assert.deepEqual(candidate([2, 4, 3, 0, 1, 5]),[0, 1, 2, 3, 4, 5]); assert.deepEqual(candidate([2, 4, 3, 0, 1, 5, 6]),[6, 5, 4, 3, 2, 1, 0]); assert.deepEqual(candidate([2, 1]),[1, 2]); assert.deepEqual(candidate([15, 42, 87, 32, 11, 0]),[0, 11, 15, 32, 42, 87]); assert.deepEqual(candidate([21, 14, 23, 11]),[23, 21, 14, 11]); } test();
humaneval-HumanEval_105_by_length.json-L24
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = [];
var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
for(var i = 0; i < arr2.length; i++){
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_115_max_fill.json-L40
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // Example 1: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) // (6l) // Example 2: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) // (5l) // Example 3: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) // (0l) // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) { long count = 0l; for (ArrayList<Long> well : grid) { long level = 0l; for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity;
units += 1l; } count += units; } return count; } }
if (level % capacity != 0l) {
} public static void main(String[] args) { assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l)); } }
humaneval-HumanEval_129_minPath.json-L67
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; } } } let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr;
} currCell = nextCell; } return path; }
}
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_89_encrypt.json-L19
js
//Create a function encrypt that takes a string as an argument and // returns a string encrypted with the alphabet being rotated. // The alphabet should be rotated in a manner such that the letters // shift down by two multiplied to two places. // For example: // >>> encrypt("hi") // "lm" // >>> encrypt("asdfghjkl") // "ewhjklnop" // >>> encrypt("gf") // "kj" // >>> encrypt("et") // "ix" function encrypt(s){ var alphabet = "abcdefghijklmnopqrstuvwxyz"; var newString = ""; var shiftBy = 2 * 2; for(var i = 0; i < s.length; i++){
newString += alphabet[(index + shiftBy) % 26]; } return newString; }
var index = alphabet.indexOf(s[i]);
const assert = require('node:assert'); function test() { let candidate = encrypt; assert.deepEqual(candidate("hi"),"lm"); assert.deepEqual(candidate("asdfghjkl"),"ewhjklnop"); assert.deepEqual(candidate("gf"),"kj"); assert.deepEqual(candidate("et"),"ix"); assert.deepEqual(candidate("faewfawefaewg"),"jeiajeaijeiak"); assert.deepEqual(candidate("hellomyfriend"),"lippsqcjvmirh"); assert.deepEqual(candidate("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh"),"hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"); assert.deepEqual(candidate("a"),"e"); } test();
humaneval-HumanEval_104_unique_digits.json-L23
py
from typing import List def unique_digits(x: List[int]) -> List[int]: """Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing order. For example: >>> unique_digits([15, 33, 1422, 1]) [1, 15, 33] >>> unique_digits([152, 323, 1422, 10]) [] """ s=[] for i in x: temp=i while temp: if temp%2==0: s.append(i) break temp=temp//10
x.remove(i) return sorted(x)
for i in s:
def check(candidate): assert candidate([15, 33, 1422, 1]) == [1, 15, 33] assert candidate([152, 323, 1422, 10]) == [] assert candidate([12345, 2033, 111, 151]) == [111, 151] assert candidate([135, 103, 31]) == [31, 135] def test_check(): check(unique_digits) test_check()
humaneval-HumanEval_20_find_closest_elements.json-L27
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j
temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
if numbers[temp_index] > numbers[temp2_index]:
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_55_fib.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 { // 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_52_below_threshold.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 { // Return true if all numbers in the array list l are below threshold t. // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) // (true) // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) // (false) public static boolean belowThreshold(ArrayList<Long> l, long t) { Long[] a = l.toArray(new Long[l.size()]); for (int i = 0; i < a.length; i++) { if (a[i] >= t) { return false; } }
} }
return true;
} public static void main(String[] args) { assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) == (false)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (21l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (22l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (11l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (10l)) == (false)); } }
humaneval-HumanEval_39_prime_fib.json-L21
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{
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); }
for(var i = 5; i * i <= number; i += 6){
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_78_hex_key.json-L30
js
//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: // >>> hex_key("AB") // 1 // >>> hex_key("1077E") // 2 // >>> hex_key("ABED1A33") // 4 // >>> hex_key("123456789ABCDEF0") // 6 // >>> hex_key("2020") // 2 function hex_key(num){ let result = 0; let hexadecimals = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']; let primes = ['2', '3', '5', '7', 'B', 'D']; for(let x = 0; x < num.length; x++){ if(primes.includes(num[x])){ result += 1; }
return result; }
}
const assert = require('node:assert'); function test() { let candidate = hex_key; assert.deepEqual(candidate("AB"),1); assert.deepEqual(candidate("1077E"),2); assert.deepEqual(candidate("ABED1A33"),4); assert.deepEqual(candidate("2020"),2); assert.deepEqual(candidate("123456789ABCDEF0"),6); assert.deepEqual(candidate("112233445566778899AABBCCDDEEFF00"),12); } test();
humaneval-HumanEval_36_fizz_buzz.json-L14
js
//Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. // >>> fizz_buzz(50) // 0 // >>> fizz_buzz(78) // 2 // >>> fizz_buzz(79) // 3 function fizz_buzz(n){ let result = 0; for(let i = 0; i < n; i++){ if(i % 11 === 0 || i % 13 === 0){ let arr = i.toString().split(''); for(let j = 0; j < arr.length; j++){
result++; } } } } return result; }
if(arr[j] === '7'){
const assert = require('node:assert'); function test() { let candidate = fizz_buzz; assert.deepEqual(candidate(50),0); assert.deepEqual(candidate(78),2); assert.deepEqual(candidate(79),3); assert.deepEqual(candidate(100),3); assert.deepEqual(candidate(200),6); assert.deepEqual(candidate(4000),192); assert.deepEqual(candidate(10000),639); assert.deepEqual(candidate(100000),8026); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L18
js
//Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separate_paren_groups("( ) (( )) (( )( ))") // ["()", "(())", "(()())"] function separate_paren_groups(paren_string){ var count = 0; var group = ''; var groups = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] === '('){ count++; group += paren_string[i]; } else if (paren_string[i] === ')'){ count--; group += paren_string[i];
if (count === 0 && group){ groups.push(group); group = ''; } } return groups; }
}
const assert = require('node:assert'); function test() { let candidate = separate_paren_groups; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]); assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]); assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]); assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]); } test();
humaneval-HumanEval_118_get_closest_vowel.json-L24
js
//You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> get_closest_vowel("yogurt") // "u" // >>> get_closest_vowel("FULL") // "U" // >>> get_closest_vowel("quick") // "" // >>> get_closest_vowel("ab") // "" function get_closest_vowel(word){ let vowels = ["a", "e", "i", "o", "u"]; let i = word.length - 1; let result = []; if (word.length === 1) { return "" } else { while (i >= 0) { if (vowels.includes(word[i])) {
if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) { result.push(word[i]); } } } i--; } if (result.length === 0) { return "" } else { return result[0]; } } }
if (i > 0 && i < word.length - 1) {
const assert = require('node:assert'); function test() { let candidate = get_closest_vowel; assert.deepEqual(candidate("yogurt"),"u"); assert.deepEqual(candidate("full"),"u"); assert.deepEqual(candidate("easy"),""); assert.deepEqual(candidate("eAsy"),""); assert.deepEqual(candidate("ali"),""); assert.deepEqual(candidate("bad"),"a"); assert.deepEqual(candidate("most"),"o"); assert.deepEqual(candidate("ab"),""); assert.deepEqual(candidate("ba"),""); assert.deepEqual(candidate("quick"),""); assert.deepEqual(candidate("anime"),"i"); assert.deepEqual(candidate("Asia"),""); assert.deepEqual(candidate("Above"),"o"); } test();
humaneval-HumanEval_57_monotonic.json-L27
js
//Return true is array elements are monotonically increasing or decreasing. // >>> monotonic([1, 2, 4, 20]) // true // >>> monotonic([1, 20, 4, 10]) // false // >>> monotonic([4, 1, 0, -10]) // true function monotonic(l){ if(l.length <= 1){ return true; } if(l[0] < l[1]){ for(var i = 1; i < l.length - 1; i++){ if(l[i] > l[i + 1]){ return false; } } } else{ for(var i = 1; i < l.length - 1; i++){ if(l[i] < l[i + 1]){ return false; } } } return true;
}
const assert = require('node:assert'); function test() { let candidate = monotonic; assert.deepEqual(candidate([1, 2, 4, 10]),true); assert.deepEqual(candidate([1, 2, 4, 20]),true); assert.deepEqual(candidate([1, 20, 4, 10]),false); assert.deepEqual(candidate([4, 1, 0, -10]),true); assert.deepEqual(candidate([4, 1, 1, 0]),true); assert.deepEqual(candidate([1, 2, 3, 2, 5, 60]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 60]),true); assert.deepEqual(candidate([9, 9, 9, 9]),true); } test();
humaneval-HumanEval_101_words_string.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 { // You will be given a string of words separated by commas or spaces. Your task is // to split the string into words and return an array array list of the words. // For example: // >>> wordsString(("Hi, my name is John")) // (new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John"))) // >>> wordsString(("One, two, three, four, five, six")) // (new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))) public static ArrayList<String> wordsString(String s) { ArrayList<String> al = new ArrayList<String>();
while (st.hasMoreTokens()) { al.add(st.nextToken()); } return al; } }
StringTokenizer st = new StringTokenizer(s, " , ");
} public static void main(String[] args) { assert(wordsString(("Hi, my name is John")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John"))))); assert(wordsString(("One, two, three, four, five, six")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))))); assert(wordsString(("Hi, my name")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name"))))); assert(wordsString(("One,, two, three, four, five, six,")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))))); assert(wordsString(("")).equals((new ArrayList<String>(Arrays.asList())))); assert(wordsString(("ahmed , gamal")).equals((new ArrayList<String>(Arrays.asList((String)"ahmed", (String)"gamal"))))); } }
humaneval-HumanEval_111_histogram.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 { // Given a string representing a space separated lowercase letters, return a hash map // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram(("a b c")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) { HashMap<String,Long> s = new HashMap<String,Long>(); if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" "); for (String sss : ss) {
hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; } }
if (hm.containsKey(sss)) {
} public static void main(String[] args) { assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("")).equals((new HashMap<String,Long>()))); assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l))))); } }
humaneval-HumanEval_75_is_multiply_prime.json-L22
js
//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 function is_multiply_prime(a){ a = Math.abs(a); const prime = [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]; let i = 0; let check = []; while(a != 1){ if(a % prime[i] == 0){ a = a / prime[i]; check.push(prime[i]); }else{ i++; } } if(check.length == 3){
}else{ return false; } }
return true;
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_124_valid_date.json-L26
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false;
if(day < 1 || day > 29){ return false; } }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; } return false; }
}else if(month == 2){
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_6_parse_nested_parens.json-L11
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0; var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){
level += 1; if (level > maxlevel){ maxlevel = level; } } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
if (paren_string[i] == "("){
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_10_make_palindrome.json-L16
py
def make_palindrome(string: str) -> str: """ Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """ if not string: return string
for i in range(len(string)): if string[i:] == prefix[:len(string) - i]: return string + prefix[len(string) - i:] return string
prefix = string[::-1]
def check(candidate): assert candidate('') == '' assert candidate('x') == 'x' assert candidate('xyz') == 'xyzyx' assert candidate('xyx') == 'xyx' assert candidate('jerry') == 'jerryrrej' def test_check(): check(make_palindrome) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L62
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";
} if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
num -= 9;
} 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_117_select_words.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 { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l;
switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) { ret.add(word); } } return ret; } }
for (char c : wordInLowerCase.toCharArray()) {
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_60_sum_to_n.json-L14
py
def sum_to_n(n: int) -> int: """sum_to_n is a function that sums numbers from 1 to n. >>> sum_to_n(30) 465 >>> sum_to_n(100) 5050 >>> sum_to_n(5) 15 >>> sum_to_n(10) 55 >>> sum_to_n(1) 1 """
return n * (n + 1) // 2
def check(candidate): assert candidate(1) == 1 assert candidate(6) == 21 assert candidate(11) == 66 assert candidate(30) == 465 assert candidate(100) == 5050 def test_check(): check(sum_to_n) test_check()
humaneval-HumanEval_25_factorize.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 { // Return array list of prime factors of given integer in the order from smallest to largest. // Each of the factors should be array listed number of times corresponding to how many times it appeares in factorization. // Input number should be equal to the product of all factors // >>> factorize((8l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))) // >>> factorize((25l)) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l))) // >>> factorize((70l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)7l))) public static ArrayList<Long> factorize(long n) { ArrayList<Long> factors = new ArrayList<Long>(); for (long d = 2; d*d <= n; d++) { while (n % d == 0) { factors.add(d); n /= d; } } if (n > 1) factors.add(n); return factors; }
}
} public static void main(String[] args) { assert(factorize((2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(factorize((4l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(factorize((8l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))))); assert(factorize((57l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l))))); assert(factorize((3249l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)19l, (long)19l))))); assert(factorize((185193l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((20577l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)3l))))); } }
humaneval-HumanEval_73_smallest_change.json-L19
py
from typing import List def smallest_change(arr: List[int]) -> int: """ Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: >>> smallest_change([1, 2, 3, 5, 4, 7, 9, 6]) 4 >>> smallest_change([1, 2, 3, 4, 3, 2, 2]) 1 >>> smallest_change([1, 2, 3, 2, 1]) 0 """ start = 0 end = len(arr) - 1
while start < end: if arr[start] != arr[end]: count += 1 start += 1 end -= 1 return count
count = 0
def check(candidate): assert candidate([1, 2, 3, 5, 4, 7, 9, 6]) == 4 assert candidate([1, 2, 3, 4, 3, 2, 2]) == 1 assert candidate([1, 4, 2]) == 1 assert candidate([1, 4, 4, 2]) == 1 assert candidate([1, 2, 3, 2, 1]) == 0 assert candidate([3, 1, 1, 3]) == 0 assert candidate([1]) == 0 assert candidate([0, 1]) == 1 def test_check(): check(smallest_change) test_check()
humaneval-HumanEval_101_words_string.json-L9
js
//You will be given a string of words separated by commas or spaces. Your task is // to split the string into words and return an array of the words. // For example: // >>> words_string("Hi, my name is John") // ["Hi", "my", "name", "is", "John"] // >>> words_string("One, two, three, four, five, six") // ["One", "two", "three", "four", "five", "six"] function words_string(s){
return res; }
let res = s.split(/[\s,]+/).filter(Boolean);
const assert = require('node:assert'); function test() { let candidate = words_string; assert.deepEqual(candidate("Hi, my name is John"),["Hi", "my", "name", "is", "John"]); assert.deepEqual(candidate("One, two, three, four, five, six"),["One", "two", "three", "four", "five", "six"]); assert.deepEqual(candidate("Hi, my name"),["Hi", "my", "name"]); assert.deepEqual(candidate("One,, two, three, four, five, six,"),["One", "two", "three", "four", "five", "six"]); assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("ahmed , gamal"),["ahmed", "gamal"]); } test();
humaneval-HumanEval_68_pluck.json-L45
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given an array array list representing a branch of a tree that has non-negative integer nodes // your task is to pluck one of the nodes and return it. // The plucked node should be the node with the smallest even value. // If multiple nodes with the same smallest even value are found return the node that has smallest index. // The plucked node should be returned in an array array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // Explanation: 0 is the smallest value, but there are two zeros, // so we will choose the first zero, which has the smallest index. // Constraints: // * 1 <= nodes.length <= 10000 // * 0 <= node.value public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i; minValue = arr.get(i); } } }
if (minIndex == -1) { return newArr; } newArr.add(minValue); newArr.add((long)minIndex); return newArr; } }
ArrayList<Long> newArr = new ArrayList<Long>();
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_64_vowels_count.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function vowels_count which takes a string representing // a word as input and returns the number of vowels in the string. // Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a // vowel, but only when it is at the end of the given word. // Example: // >>> vowelsCount(("abcde")) // (2l) // >>> vowelsCount(("ACEDY")) // (3l) public static long vowelsCount(String s) { long sum = 0; String sUpper = s.toUpperCase();
for (int i = 0; i < sUpper.length(); i++) { if (sUpper.charAt(i) == 'A' || sUpper.charAt(i) == 'E' || sUpper.charAt(i) == 'I' || sUpper.charAt(i) == 'O' || sUpper.charAt(i) == 'U') { sum++; } if (sUpper.charAt(i) == 'Y' && i == lastIndex) { sum++; } } return sum; } }
int lastIndex = sUpper.length() - 1;
} public static void main(String[] args) { assert(vowelsCount(("abcde")) == (2l)); assert(vowelsCount(("Alone")) == (3l)); assert(vowelsCount(("key")) == (2l)); assert(vowelsCount(("bye")) == (1l)); assert(vowelsCount(("keY")) == (2l)); assert(vowelsCount(("bYe")) == (1l)); assert(vowelsCount(("ACEDY")) == (3l)); } }
humaneval-HumanEval_33_sort_third.json-L22
js
//This function takes an array l and returns an array l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sort_third([1, 2, 3]) // [1, 2, 3] // >>> sort_third([5, 6, 3, 4, 8, 9, 2]) // [2, 6, 3, 4, 8, 9, 5] function sort_third(l){ let x=[]; let y=[]; let k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ y[k]=l[i]; k=k+1; } else{ x[i]=l[i]; } } y.sort();
for(let i=0;i<l.length;i++){ if(i%3==0){ x[i]=y[k]; k=k+1; } } return x; }
k=0;
const assert = require('node:assert'); function test() { let candidate = sort_third; assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2]),[2, 6, 3, 4, 8, 9, 5]); assert.deepEqual(candidate([5, 8, 3, 4, 6, 9, 2]),[2, 8, 3, 4, 6, 9, 5]); assert.deepEqual(candidate([5, 6, 9, 4, 8, 3, 2]),[2, 6, 9, 4, 8, 3, 5]); assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2, 1]),[2, 6, 3, 4, 8, 9, 5, 1]); } test();
humaneval-HumanEval_134_check_if_last_char_is_a_letter.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 { // 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) {
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; } }
if (txt.length() == 0) {
} 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_118_get_closest_vowel.json-L36
js
//You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> get_closest_vowel("yogurt") // "u" // >>> get_closest_vowel("FULL") // "U" // >>> get_closest_vowel("quick") // "" // >>> get_closest_vowel("ab") // "" function get_closest_vowel(word){ let vowels = ["a", "e", "i", "o", "u"]; let i = word.length - 1; let result = []; if (word.length === 1) { return "" } else { while (i >= 0) { if (vowels.includes(word[i])) { if (i > 0 && i < word.length - 1) { if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) { result.push(word[i]); } } } i--; } if (result.length === 0) { return "" } else { return result[0];
} }
}
const assert = require('node:assert'); function test() { let candidate = get_closest_vowel; assert.deepEqual(candidate("yogurt"),"u"); assert.deepEqual(candidate("full"),"u"); assert.deepEqual(candidate("easy"),""); assert.deepEqual(candidate("eAsy"),""); assert.deepEqual(candidate("ali"),""); assert.deepEqual(candidate("bad"),"a"); assert.deepEqual(candidate("most"),"o"); assert.deepEqual(candidate("ab"),""); assert.deepEqual(candidate("ba"),""); assert.deepEqual(candidate("quick"),""); assert.deepEqual(candidate("anime"),"i"); assert.deepEqual(candidate("Asia"),""); assert.deepEqual(candidate("Above"),"o"); } test();
humaneval-HumanEval_129_minPath.json-L26
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 startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; } } } let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
let path = [];
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_112_reverse_delete.json-L22
py
from typing import Tuple def reverse_delete(s: str, c: str) -> Tuple[str, bool]: """Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and True/False for the check. Example >>> reverse_delete('abcde', 'ae') ('bcd', False) >>> reverse_delete('abcdef', 'b') ('acdef', False) >>> reverse_delete('abcdedcba', 'ab') ('cdedc', True) """ new_str = '' for i in s: if i not in c: new_str += i new_str_reverse = new_str[::-1]
return (new_str, new_str == new_str_reverse)
def check(candidate): assert candidate('abcde', 'ae') == ('bcd', False) assert candidate('abcdef', 'b') == ('acdef', False) assert candidate('abcdedcba', 'ab') == ('cdedc', True) assert candidate('dwik', 'w') == ('dik', False) assert candidate('a', 'a') == ('', True) assert candidate('abcdedcba', '') == ('abcdedcba', True) assert candidate('abcdedcba', 'v') == ('abcdedcba', True) assert candidate('vabba', 'v') == ('abba', True) assert candidate('mamma', 'mia') == ('', True) def test_check(): check(reverse_delete) test_check()
humaneval-HumanEval_59_largest_prime_factor.json-L7
js
//Return the largest prime factor of n. Assume n > 1 and is not a prime. // >>> largest_prime_factor(13195) // 29 // >>> largest_prime_factor(2048) // 2 function largest_prime_factor(n){
while(n > result){ if(n % result == 0){ n = n / result; } else{ result = result + 1; } } return result; }
var result = 2;
const assert = require('node:assert'); function test() { let candidate = largest_prime_factor; assert.deepEqual(candidate(15),5); assert.deepEqual(candidate(27),3); assert.deepEqual(candidate(63),7); assert.deepEqual(candidate(330),11); assert.deepEqual(candidate(13195),29); } test();
humaneval-HumanEval_74_total_match.json-L22
js
//Write a function that accepts two arrays of strings and returns the array that has // total number of chars in the all strings of the array less than the other array. // if the two arrays have the same number of chars, return the first array. // Examples // >>> total_match([], []) // [] // >>> total_match(["hi", "admin"], ["hI", "Hi"]) // ["hI", "Hi"] // >>> total_match(["hi", "admin"], ["hi", "hi", "admin", "project"]) // ["hi", "admin"] // >>> total_match(["hi", "admin"], ["hI", "hi", "hi"]) // ["hI", "hi", "hi"] // >>> total_match(["4"], ["1", "2", "3", "4", "5"]) // ["4"] function total_match(lst1, lst2){ let sum_lst1 = 0; let sum_lst2 = 0; for(let item of lst1){ sum_lst1 += item.length; } for(let item of lst2){
} if(sum_lst1 > sum_lst2){ return lst2; } else{ return lst1; } }
sum_lst2 += item.length;
const assert = require('node:assert'); function test() { let candidate = total_match; assert.deepEqual(candidate([], []),[]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi"]),["hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi", "admin", "project"]),["hi", "admin"]); assert.deepEqual(candidate(["4"], ["1", "2", "3", "4", "5"]),["4"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "Hi"]),["hI", "Hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hi"]),["hI", "hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hii"]),["hi", "admin"]); assert.deepEqual(candidate([], ["this"]),[]); assert.deepEqual(candidate(["this"], []),[]); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L23
js
//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 function is_multiply_prime(a){ a = Math.abs(a); const prime = [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]; let i = 0; let check = []; while(a != 1){ if(a % prime[i] == 0){ a = a / prime[i]; check.push(prime[i]); }else{ i++; } } if(check.length == 3){ return true;
return false; } }
}else{
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_113_odd_count.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of strings, where each string consists of only digits, return an array array 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. // >>> oddCount((new ArrayList<String>(Arrays.asList((String)"1234567")))) // (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput."))) // >>> oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111")))) // (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput."))) public static ArrayList<String> oddCount(ArrayList<String> lst) { ArrayList<String> res = new ArrayList<String>(); for (int i = 0; i < lst.size(); i++) { int count = 0; for (int j = 0; j < lst.get(i).length(); j++) { if (Integer.parseInt(lst.get(i).substring(j, j + 1)) % 2 == 1) { count++; }
res.add("the number of odd elements " + count + "n the str" + count + "ng " + count + " of the " + count + "nput."); } return res; } }
}
} public static void main(String[] args) { assert(oddCount((new ArrayList<String>(Arrays.asList((String)"1234567")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput."))))); assert(oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput."))))); assert(oddCount((new ArrayList<String>(Arrays.asList((String)"271", (String)"137", (String)"314")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 2n the str2ng 2 of the 2nput.", (String)"the number of odd elements 3n the str3ng 3 of the 3nput.", (String)"the number of odd elements 2n the str2ng 2 of the 2nput."))))); } }
humaneval-HumanEval_128_prod_signs.json-L33
py
from typing import List, Optional def prod_signs(arr: List[int]) -> Optional[int]: """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -4]) 9 >>> prod_signs([0, 1]) 0 >>> prod_signs([]) None """ def product(lst: List[int]) -> int: out = 1 for item in lst: out *= item return out if len(arr) == 0: return None else: sign_arr = [] for num in arr: if num > 0: sign_arr.append(1) elif num < 0: sign_arr.append(-1)
sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
else:
def check(candidate): assert candidate([1, 2, 2, -4]) == -9 assert candidate([0, 1]) == 0 assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10 assert candidate([]) == None assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20 assert candidate([-1, 1, -1, 1]) == 4 assert candidate([-1, 1, 1, 1]) == -4 assert candidate([-1, 1, 1, 0]) == 0 def test_check(): check(prod_signs) test_check()
humaneval-HumanEval_36_fizz_buzz.json-L11
js
//Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. // >>> fizz_buzz(50) // 0 // >>> fizz_buzz(78) // 2 // >>> fizz_buzz(79) // 3 function fizz_buzz(n){ let result = 0; for(let i = 0; i < n; i++){
let arr = i.toString().split(''); for(let j = 0; j < arr.length; j++){ if(arr[j] === '7'){ result++; } } } } return result; }
if(i % 11 === 0 || i % 13 === 0){
const assert = require('node:assert'); function test() { let candidate = fizz_buzz; assert.deepEqual(candidate(50),0); assert.deepEqual(candidate(78),2); assert.deepEqual(candidate(79),3); assert.deepEqual(candidate(100),3); assert.deepEqual(candidate(200),6); assert.deepEqual(candidate(4000),192); assert.deepEqual(candidate(10000),639); assert.deepEqual(candidate(100000),8026); } test();
humaneval-HumanEval_40_triples_sum_to_zero.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 { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) { return false; } ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList);
int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) { j++; } else { k--; } } } return false; } }
for (int i = 0; i < sortedList.size() - 2; i++) {
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_112_reverse_delete.json-L21
py
from typing import Tuple def reverse_delete(s: str, c: str) -> Tuple[str, bool]: """Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and True/False for the check. Example >>> reverse_delete('abcde', 'ae') ('bcd', False) >>> reverse_delete('abcdef', 'b') ('acdef', False) >>> reverse_delete('abcdedcba', 'ab') ('cdedc', True) """ new_str = '' for i in s: if i not in c: new_str += i
return (new_str, new_str == new_str_reverse)
new_str_reverse = new_str[::-1]
def check(candidate): assert candidate('abcde', 'ae') == ('bcd', False) assert candidate('abcdef', 'b') == ('acdef', False) assert candidate('abcdedcba', 'ab') == ('cdedc', True) assert candidate('dwik', 'w') == ('dik', False) assert candidate('a', 'a') == ('', True) assert candidate('abcdedcba', '') == ('abcdedcba', True) assert candidate('abcdedcba', 'v') == ('abcdedcba', True) assert candidate('vabba', 'v') == ('abba', True) assert candidate('mamma', 'mia') == ('', True) def test_check(): check(reverse_delete) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L39
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+')
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
elif x > 2.7:
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_94_skjkasdkd.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 { // You are given an array array list of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) // (10l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) // (25l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) // (13l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) // (11l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) // (3l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) // (7l) public static long skjkasdkd(ArrayList<Long> lst) { long largestPrime = 0l; for (Long item : lst) { long number = item; int counter = 0; if (item == 1) { continue; } if (item == 2) { counter = 1; } else { int l = 1; while (l <= (int) number) {
counter++; } l++; } } if (counter == 2) { if (number > largestPrime) { largestPrime = number; } } } if (largestPrime == 0) { return 0l; } else { long output = 0l; while (largestPrime > 0) { output += largestPrime % 10; largestPrime /= 10; } return output; } } }
if (number % l == 0) {
} public static void main(String[] args) { assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) == (10l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) == (25l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) == (13l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) == (11l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) == (3l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) == (7l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l, (long)123456l, (long)127l, (long)7l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)127l, (long)97l, (long)8192l)))) == (10l)); } }
humaneval-HumanEval_162_string_to_md5.json-L8
js
//Given a string 'text', return its md5 hash equivalent string. // If 'text' is an empty string, return undefined. // >>> string_to_md5("Hello world") // "3e25960a79dbc69b674cd4ec67a72c62" function string_to_md5(text){ if(text === ''){ return undefined;
return require('crypto').createHash('md5').update(text).digest('hex'); }
}
const assert = require('node:assert'); function test() { let candidate = string_to_md5; assert.deepEqual(candidate("Hello world"),"3e25960a79dbc69b674cd4ec67a72c62"); assert.deepEqual(candidate(""),undefined); assert.deepEqual(candidate("A B C"),"0ef78513b0cb8cef12743f5aeb35f888"); assert.deepEqual(candidate("password"),"5f4dcc3b5aa765d61d8327deb882cf99"); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L36
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){
} 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; }
grades_array.push("B+");
const assert = require('node:assert'); function test() { let candidate = numerical_letter_grade; assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]); assert.deepEqual(candidate([1.2]),["D+"]); assert.deepEqual(candidate([0.5]),["D-"]); assert.deepEqual(candidate([0.0]),["E"]); assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]); assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]); } test();
humaneval-HumanEval_116_sort_array.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 { // In this Kata, you have to sort an array array list of non-negative integers according to // number of ones in their binary representation in ascending order. // For similar number of ones, sort based on decimal value. // It must be implemented like this: // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))) // (new ArrayList<Long>(Arrays.asList((long)-6l, (long)-5l, (long)-4l, (long)-3l, (long)-2l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l))) public static ArrayList<Long> sortArray(ArrayList<Long> arr) { Collections.sort(arr, (a, b) -> { long a1 = a, b1 = b; if (a1 < 0) { a1 = -a1; } if (b1 < 0) {
} return Long.bitCount(a1) == Long.bitCount(b1) ? Long.compare(a, b) : Integer.compare(Long.bitCount(a1), Long.bitCount(b1)); }); return arr; } }
b1 = -b1;
} public static void main(String[] args) { assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-2l, (long)-6l, (long)-5l, (long)-3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)4l, (long)3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)77l, (long)4l, (long)5l, (long)3l, (long)5l, (long)7l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)4l, (long)4l, (long)3l, (long)3l, (long)5l, (long)5l, (long)5l, (long)7l, (long)77l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)44l, (long)12l, (long)32l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)32l, (long)3l, (long)5l, (long)6l, (long)12l, (long)44l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); } }
humaneval-HumanEval_82_prime_length.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes a string and returns true if the string // length is a prime number or false otherwise // Examples // >>> primeLength(("Hello")) // (true) // >>> primeLength(("abcdcba")) // (true) // >>> primeLength(("kittens")) // (true) // >>> primeLength(("orange")) // (false) public static boolean primeLength(String string) { return new java.math.BigInteger(String.valueOf(string.length())).isProbablePrime(100);
}
}
} public static void main(String[] args) { assert(primeLength(("Hello")) == (true)); assert(primeLength(("abcdcba")) == (true)); assert(primeLength(("kittens")) == (true)); assert(primeLength(("orange")) == (false)); assert(primeLength(("wow")) == (true)); assert(primeLength(("world")) == (true)); assert(primeLength(("MadaM")) == (true)); assert(primeLength(("Wow")) == (true)); assert(primeLength(("")) == (false)); assert(primeLength(("HI")) == (true)); assert(primeLength(("go")) == (true)); assert(primeLength(("gogo")) == (false)); assert(primeLength(("aaaaaaaaaaaaaaa")) == (false)); assert(primeLength(("Madam")) == (true)); assert(primeLength(("M")) == (false)); assert(primeLength(("0")) == (false)); } }
humaneval-HumanEval_105_by_length.json-L30
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){
} else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
arr3.push("Two");
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_148_bf.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 { // There are eight planets in our solar system: the closerst to the Sun // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, // Uranus, Neptune. // Write a function that takes two planet names as strings planet1 and planet2. // The function should return a pair containing all planets whose orbits are // located between the orbit of planet1 and the orbit of planet2, sorted by // the proximity to the sun. // The function should return an empty pair if planet1 or planet2 // are not correct planet names. // Examples // >>> bf(("Jupiter"), ("Neptune")) // (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))) // >>> bf(("Earth"), ("Mercury")) // (ArrayList<String>("Venus")) // >>> bf(("Mercury"), ("Uranus")) // (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))) public static ArrayList<String> bf(String planet1, String planet2) { ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune")); int indexPlanet1 = planets.indexOf(planet1);
int indexMin = 0; int indexMax = 0; if (indexPlanet1 >= 0 && indexPlanet2 >= 0) { if (indexPlanet1 < indexPlanet2) { indexMin = indexPlanet1; indexMax = indexPlanet2; } else { indexMin = indexPlanet2; indexMax = indexPlanet1; } ArrayList<String> planetsInBetween = new ArrayList<String>(); for (int i = indexMin + 1; i < indexMax; i++) { planetsInBetween.add(planets.get(i)); } return planetsInBetween; } else { return new ArrayList<String>(); } } }
int indexPlanet2 = planets.indexOf(planet2);
} public static void main(String[] args) { assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus"))))); assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn"))))); assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus"))))); assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList())))); assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList())))); } }
humaneval-HumanEval_105_by_length.json-L33
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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_139_special_factorial.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 { // The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // For example: // >>> specialFactorial((4l)) // (288l) // The function will receive an integer as input and should return the special // factorial of this integer. public static long specialFactorial(long n) { long result = 1; while (n > 0) { long local_result = 1; long temp = n; while (temp > 0) { local_result *= temp; temp--;
result *= local_result; n--; } return result; } }
}
} public static void main(String[] args) { assert(specialFactorial((4l)) == (288l)); assert(specialFactorial((5l)) == (34560l)); assert(specialFactorial((7l)) == (125411328000l)); assert(specialFactorial((1l)) == (1l)); } }
humaneval-HumanEval_19_sort_numbers.json-L19
js
//Input is a space-delimited string of numberals from 'zero' to 'nine'. // Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. // Return the string with numbers sorted from smallest to largest // >>> sort_numbers("three one five") // "one three five" function sort_numbers(numbers){ var numString = numbers.split(" "); var numMap = { "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9
numString.sort(function(a, b){ return numMap[a] - numMap[b]; }); numString = numString.join(" "); return numString; }
};
const assert = require('node:assert'); function test() { let candidate = sort_numbers; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("three"),"three"); assert.deepEqual(candidate("three five nine"),"three five nine"); assert.deepEqual(candidate("five zero four seven nine eight"),"zero four five seven eight nine"); assert.deepEqual(candidate("six five four three two one zero"),"zero one two three four five six"); } test();
humaneval-HumanEval_4_mean_absolute_deviation.json-L11
js
//For a given array of input numbers, calculate Mean Absolute Deviation // around the mean of this dataset. // Mean Absolute Deviation is the average absolute difference between each // element and a centerpoint (mean in this case): // MAD = average | x - x_mean | // >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) // 1.0 function mean_absolute_deviation(numbers){ var sum = 0; for(var i = 0; i < numbers.length; i++){
} var mean = sum / numbers.length; var sum_abs_diff = 0; for(var i = 0; i < numbers.length; i++){ sum_abs_diff += Math.abs(numbers[i] - mean); } return sum_abs_diff / numbers.length; }
sum += numbers[i];
const assert = require('node:assert'); function test() { let candidate = mean_absolute_deviation; assert.deepEqual(candidate([1.0, 2.0]),0.5); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0]),1.0); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0]),1.2); } test();
humaneval-HumanEval_159_eat.json-L36
py
from typing import List def eat(number: int, need: int, remaining: int) -> List[int]: """ You're a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return an array of [ total number of eaten carrots after your meals, the number of carrots left after your meals ] if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. Example: >>> eat(5, 6, 10) [11, 4] >>> eat(4, 8, 9) [12, 1] >>> eat(1, 10, 10) [11, 0] >>> eat(2, 11, 5) [7, 0] Variables: @number : integer the number of carrots that you have eaten. @need : integer the number of carrots that you need to eat. @remaining : integer the number of remaining carrots thet exist in stock Constrain: * 0 <= number <= 1000 * 0 <= need <= 1000 * 0 <= remaining <= 1000 Have fun :) """
return [number + min(need, remaining), max(remaining - need, 0)]
def check(candidate): assert candidate(5, 6, 10) == [11, 4] assert candidate(4, 8, 9) == [12, 1] assert candidate(1, 10, 10) == [11, 0] assert candidate(2, 11, 5) == [7, 0] assert candidate(4, 5, 7) == [9, 2] assert candidate(4, 5, 1) == [5, 0] def test_check(): check(eat) test_check()
humaneval-HumanEval_94_skjkasdkd.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 { // You are given an array array list of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) // (10l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) // (25l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) // (13l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) // (11l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) // (3l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) // (7l) public static long skjkasdkd(ArrayList<Long> lst) { long largestPrime = 0l; for (Long item : lst) { long number = item; int counter = 0; if (item == 1) { continue; }
counter = 1; } else { int l = 1; while (l <= (int) number) { if (number % l == 0) { counter++; } l++; } } if (counter == 2) { if (number > largestPrime) { largestPrime = number; } } } if (largestPrime == 0) { return 0l; } else { long output = 0l; while (largestPrime > 0) { output += largestPrime % 10; largestPrime /= 10; } return output; } } }
if (item == 2) {
} public static void main(String[] args) { assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) == (10l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) == (25l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) == (13l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) == (11l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) == (3l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) == (7l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l, (long)123456l, (long)127l, (long)7l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)127l, (long)97l, (long)8192l)))) == (10l)); } }
humaneval-HumanEval_158_find_max.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 { // 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()); }
@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); } }
words.sort(new Comparator<String>() {
} 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_137_compare_one.json-L24
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b
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
else:
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_64_vowels_count.json-L18
py
def vowels_count(s: str) -> int: """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count('abcde') 2 >>> vowels_count('ACEDY') 3 """ s = s.lower() i = 0 count = 0 while i < len(s): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'):
if (s[i] == 'y' and i == len(s) - 1): count += 1 i += 1 return count
count += 1
def check(candidate): assert candidate('abcde') == 2 assert candidate('Alone') == 3 assert candidate('key') == 2 assert candidate('bye') == 1 assert candidate('keY') == 2 assert candidate('bYe') == 1 assert candidate('ACEDY') == 3 def test_check(): check(vowels_count) test_check()
humaneval-HumanEval_143_words_in_sentence.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 { // 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;
if (word.length() == prime) { isPrime = true; break; } } if (isPrime) { ans.append(word + " "); } } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
for (int prime : primes) {
} 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_117_select_words.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) {
String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) { ret.add(word); } } return ret; } }
ArrayList<String> ret = new ArrayList<String>();
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L34
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:
elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') 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('A')
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_40_triples_sum_to_zero.json-L27
js
//triples_sum_to_zero takes an array of integers as an input. // it returns true if there are three distinct elements in the array that // sum to zero, and false otherwise. // >>> triples_sum_to_zero([1, 3, 5, 0]) // false // >>> triples_sum_to_zero([1, 3, -2, 1]) // true // >>> triples_sum_to_zero([1, 2, 3, 7]) // false // >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) // true // >>> triples_sum_to_zero([1]) // false function triples_sum_to_zero(l){ for (var i = 0; i < l.length; i++) { for (var j = 0; j < l.length; j++) { for (var k = 0; k < l.length; k++) { if (i !== j && i !== k && j !== k) { if (l[i] + l[j] + l[k] === 0) { return true; } } } } } return false;
}
const assert = require('node:assert'); function test() { let candidate = triples_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, 5, -1]),false); assert.deepEqual(candidate([1, 3, -2, 1]),true); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([1, 2, 5, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 9, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([1, 3, 5, -100]),false); assert.deepEqual(candidate([100, 3, 5, -100]),false); } test();
humaneval-HumanEval_105_by_length.json-L27
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){
} else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
arr3.push("One");
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_80_is_happy.json-L21
js
//You are given a string s. // Your task is to check if the string is hapjs or not. // A string is hapjs if its length is at least 3 and every 3 consecutive letters are distinct // For example: // >>> is_happy(a) // false // >>> is_happy(aa) // false // >>> is_happy(abcd) // true // >>> is_happy(aabb) // false // >>> is_happy(adb) // true // >>> is_happy(xyy) // false function is_happy(s){ let happy = true; if(s.length<3){ happy = false;
for(let i=2; i<s.length; i++){ if(s[i]===s[i-1] || s[i]===s[i-2]){ happy = false; } } return happy; }
}
const assert = require('node:assert'); function test() { let candidate = is_happy; assert.deepEqual(candidate("a"),false); assert.deepEqual(candidate("aa"),false); assert.deepEqual(candidate("abcd"),true); assert.deepEqual(candidate("aabb"),false); assert.deepEqual(candidate("adb"),true); assert.deepEqual(candidate("xyy"),false); assert.deepEqual(candidate("iopaxpoi"),true); assert.deepEqual(candidate("iopaxioi"),false); } test();
humaneval-HumanEval_150_x_or_y.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 { // A simple program which should return the value of x if n is // a prime number and should return the value of y otherwise. // Examples: // >>> xOrY((7l), (34l), (12l)) // (34l) // >>> xOrY((15l), (8l), (5l)) // (5l) public static long xOrY(long n, long x, long y) {
if (nBig.isProbablePrime(100)) { return x; } else { return y; } } }
BigInteger nBig = BigInteger.valueOf(n);
} public static void main(String[] args) { assert(xOrY((7l), (34l), (12l)) == (34l)); assert(xOrY((15l), (8l), (5l)) == (5l)); assert(xOrY((3l), (33l), (5212l)) == (33l)); assert(xOrY((1259l), (3l), (52l)) == (3l)); assert(xOrY((7919l), (-1l), (12l)) == (-1l)); assert(xOrY((3609l), (1245l), (583l)) == (583l)); assert(xOrY((91l), (56l), (129l)) == (129l)); assert(xOrY((6l), (34l), (1234l)) == (1234l)); assert(xOrY((1l), (2l), (0l)) == (0l)); assert(xOrY((2l), (2l), (0l)) == (2l)); } }
humaneval-HumanEval_76_is_simple_power.json-L21
py
def is_simple_power(x: int, n: int) -> bool: """Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: >>> is_simple_power(1, 4) true >>> is_simple_power(2, 2) true >>> is_simple_power(8, 2) true >>> is_simple_power(3, 2) false >>> is_simple_power(3, 1) false >>> is_simple_power(5, 3) false """ if x == 0: return False
while x > 1: if x % n != 0: return False x /= n return True
else:
def check(candidate): assert candidate(16, 2) == True assert candidate(143214, 16) == False assert candidate(4, 2) == True assert candidate(9, 3) == True assert candidate(16, 4) == True assert candidate(24, 2) == False assert candidate(128, 4) == False assert candidate(12, 6) == False assert candidate(1, 1) == True assert candidate(1, 12) == True def test_check(): check(is_simple_power) test_check()
humaneval-HumanEval_111_histogram.json-L32
js
//Given a string representing a space separated lowercase letters, return an object // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram("a b c") // {"a": 1, "b": 1, "c": 1} // >>> histogram("a b b a") // {"a": 2, "b": 2} // >>> histogram("a b c a b") // {"a": 2, "b": 2} // >>> histogram("b b b b a") // {"b": 4} // >>> histogram("") // {} function histogram(test){ if (test.length === 0){ return {}; } var lst = test.split(" "); var count = {}; for (var i = 0; i < lst.length; i++){ if (count[lst[i]]){ count[lst[i]] += 1; } else{ count[lst[i]] = 1; } } console.log(count); var max = 0; var result = {};
if (count[key] > max){ max = count[key]; result = {}; result[key] = max; } else if (count[key] === max){ result[key] = max; } } return result; }
for (var key in count){
const assert = require('node:assert'); function test() { let candidate = histogram; assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate("b b b b a"),{"b": 4}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate(""),{}); assert.deepEqual(candidate("a"),{"a": 1}); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L40
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') elif x > 2.7:
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_75_is_multiply_prime.json-L24
js
//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 function is_multiply_prime(a){ a = Math.abs(a); const prime = [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]; let i = 0; let check = []; while(a != 1){ if(a % prime[i] == 0){ a = a / prime[i]; check.push(prime[i]); }else{ i++; } } if(check.length == 3){ return true; }else{
} }
return false;
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_124_valid_date.json-L48
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) { if (day < 1 || day > 29) return valid_date; } 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;
}
}
} 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_138_is_equal_to_sum_even.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 { // Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> isEqualToSumEven((4l)) // (false) // >>> isEqualToSumEven((6l)) // (false) // >>> isEqualToSumEven((8l)) // (true) public static boolean isEqualToSumEven(long n) { if (n < 4) { return false; } long d = 2; if (n % 2 == 1) { d = 1; } long minX = d; long maxX = n / 4; while (minX <= maxX) { long x = (minX + maxX) / 2; long y = n - 2 * x; if (y % 2 == 1) { y--; } if (2 * x + y < n) { minX = x + 1; } else if (2 * x + y > n) { maxX = x - 1; } else {
} } return false; } }
return true;
} public static void main(String[] args) { assert(isEqualToSumEven((4l)) == (false)); assert(isEqualToSumEven((6l)) == (false)); assert(isEqualToSumEven((8l)) == (true)); assert(isEqualToSumEven((10l)) == (true)); assert(isEqualToSumEven((11l)) == (false)); assert(isEqualToSumEven((12l)) == (true)); assert(isEqualToSumEven((13l)) == (false)); assert(isEqualToSumEven((16l)) == (true)); } }
humaneval-HumanEval_79_decimal_to_binary.json-L12
js
//You will be given a number in decimal form and your task is to convert it to // binary format. The function should return a string, with each character representing a binary // number. Each character in the string will be '0' or '1'. // There will be an extra couple of characters 'db' at the beginning and at the end of the string. // The extra characters are there to help with the format. // Examples: // >>> decimal_to_binary(15) // "db1111db" // >>> decimal_to_binary(32) // "db100000db" function decimal_to_binary(decimal){
}
return `db${decimal.toString(2)}db`;
const assert = require('node:assert'); function test() { let candidate = decimal_to_binary; assert.deepEqual(candidate(0),"db0db"); assert.deepEqual(candidate(32),"db100000db"); assert.deepEqual(candidate(103),"db1100111db"); assert.deepEqual(candidate(15),"db1111db"); } test();
humaneval-HumanEval_82_prime_length.json-L22
py
def prime_length(string: str) -> bool: """Write a function that takes a string and returns True if the string length is a prime number or False otherwise Examples >>> prime_length('Hello') True >>> prime_length('abcdcba') True >>> prime_length('kittens') True >>> prime_length('orange') False """ num = len(string) if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else:
pass
return False
def check(candidate): assert candidate('Hello') == True assert candidate('abcdcba') == True assert candidate('kittens') == True assert candidate('orange') == False assert candidate('wow') == True assert candidate('world') == True assert candidate('MadaM') == True assert candidate('Wow') == True assert candidate('') == False assert candidate('HI') == True assert candidate('go') == True assert candidate('gogo') == False assert candidate('aaaaaaaaaaaaaaa') == False assert candidate('Madam') == True assert candidate('M') == False assert candidate('0') == False def test_check(): check(prime_length) test_check()
humaneval-HumanEval_118_get_closest_vowel.json-L42
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 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: // >>> getClosestVowel(("yogurt")) // ("u") // >>> getClosestVowel(("FULL")) // ("U") // >>> getClosestVowel(("quick")) // ("") // >>> getClosestVowel(("ab")) // ("") public static String getClosestVowel(String word) { final String vowels = "aeiou"; final String consonants = "bcdfghjklmnpqrstvwxyz"; List<Integer> idx = new ArrayList<>(); word = word.toLowerCase(); for (int i = 0; i < word.length(); i++) { if (vowels.indexOf(word.charAt(i)) != -1) { idx.add(i); } } for (int i = idx.size() - 1; i >= 0; i--) { int j = idx.get(i); if (j == 0 || j == word.length() - 1) continue; char left = word.charAt(j - 1); char right = word.charAt(j + 1); if (consonants.indexOf(left) != -1 && consonants.indexOf(right) != -1) { return String.valueOf(word.charAt(j)); } }
} }
return "";
} public static void main(String[] args) { assert(getClosestVowel(("yogurt")).equals(("u"))); assert(getClosestVowel(("full")).equals(("u"))); assert(getClosestVowel(("easy")).equals((""))); assert(getClosestVowel(("eAsy")).equals((""))); assert(getClosestVowel(("ali")).equals((""))); assert(getClosestVowel(("bad")).equals(("a"))); assert(getClosestVowel(("most")).equals(("o"))); assert(getClosestVowel(("ab")).equals((""))); assert(getClosestVowel(("ba")).equals((""))); assert(getClosestVowel(("quick")).equals((""))); assert(getClosestVowel(("anime")).equals(("i"))); assert(getClosestVowel(("Asia")).equals((""))); assert(getClosestVowel(("Above")).equals(("o"))); } }
humaneval-HumanEval_107_even_odd_palindrome.json-L38
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{ odd++; } } return [even, 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_42_incr_list.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 array list with elements incremented by 1. // >>> incrList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l))) // >>> incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))) // (new ArrayList<Long>(Arrays.asList((long)6l, (long)4l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))) public static ArrayList<Long> incrList(ArrayList<Long> l) { for (int i = 0; i < l.size(); i++) { l.set(i, l.get(i) + 1l);
return l; } }
}
} public static void main(String[] args) { assert(incrList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l))))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)2l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)3l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))))); } }
humaneval-HumanEval_0_has_close_elements.json-L11
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 false; }
return true;
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_83_starts_one_ends.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 { // Given a positive integer n, return the count of the numbers of n-digit // positive integers that start or end with 1. public static long startsOneEnds(long n) { long lower = (long) Math.pow(10, n - 1); long upper = (long) Math.pow(10, n) - 1; long count = 0; for (long i = lower; i <= upper; i++) {
if (s.startsWith("1") || s.endsWith("1")) count++; } return count; } }
String s = "" + i;
} public static void main(String[] args) { assert(startsOneEnds((1l)) == (1l)); assert(startsOneEnds((2l)) == (18l)); assert(startsOneEnds((3l)) == (180l)); assert(startsOneEnds((4l)) == (1800l)); assert(startsOneEnds((5l)) == (18000l)); } }
humaneval-HumanEval_108_count_nums.json-L27
py
from typing import List def count_nums(arr: List[int]) -> int: """ 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 """ n = 0 for i in arr: if i < 0: i = abs(i) s = -1 * int(str(i)[0]) for j in str(i)[1:]: s += int(j) else: s = 0 for j in str(i): s += int(j)
n += 1 return n
if s > 0:
def check(candidate): assert candidate([]) == 0 assert candidate([-1, -2, 0]) == 0 assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6 assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5 assert candidate([1, 100, 98, -7, 1, -1]) == 4 assert candidate([12, 23, 34, -45, -56, 0]) == 5 assert candidate([0, 1]) == 1 assert candidate([1]) == 1 def test_check(): check(count_nums) test_check()
humaneval-HumanEval_20_find_closest_elements.json-L15
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp
for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
temp_index, temp2_index = temp2_index, temp_index
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_111_histogram.json-L36
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string representing a space separated lowercase letters, return a hash map // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram(("a b c")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) { HashMap<String,Long> s = new HashMap<String,Long>(); if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" "); for (String sss : ss) { if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0;
if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; } }
for (String key : hm.keySet()) {
} public static void main(String[] args) { assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("")).equals((new HashMap<String,Long>()))); assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l))))); } }
humaneval-HumanEval_95_check_dict_case.json-L26
py
from typing import Dict def check_dict_case(dict: Dict[str, str]) -> bool: """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: >>> 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 """ if len(dict) == 0: return False if any(not isinstance(x, str) for x in dict.keys()): return False if any(not x.islower() for x in dict.keys()): if any(not x.isupper() for x in dict.keys()):
return True
return False
def check(candidate): assert candidate({ 'p': 'pineapple', 'b': 'banana' }) == True assert candidate({ 'p': 'pineapple', 'A': 'banana', 'B': 'banana' }) == False assert candidate({ 'p': 'pineapple', '5': 'banana', 'a': 'apple' }) == False assert candidate({ 'Name': 'John', 'Age': '36', 'City': 'Houston' }) == False assert candidate({ 'STATE': 'NC', 'ZIP': '12345' }) == True assert candidate({ 'fruit': 'Orange', 'taste': 'Sweet' }) == True assert candidate({ }) == False def test_check(): check(check_dict_case) test_check()
humaneval-HumanEval_33_sort_third.json-L45
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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)); j++; } else { l_s.add(l_r.get(i - j)); }
return l_s; } }
}
} 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_55_fib.json-L10
py
def fib(n: int) -> int: """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """
f0, f1 = 0, 1 for i in range(n - 1): f0, f1 = f1, f0 + f1 return f1
assert n >= 1
def check(candidate): assert candidate(10) == 55 assert candidate(1) == 1 assert candidate(8) == 21 assert candidate(11) == 89 assert candidate(12) == 144 def test_check(): check(fib) test_check()
humaneval-HumanEval_21_rescale_to_unit.json-L14
js
//Given array of numbers (of at least two elements), apply a linear transform to that array, // such that the smallest number will become 0 and the largest will become 1 // >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) // [0.0, 0.25, 0.5, 0.75, 1.0] function rescale_to_unit(numbers){ var min = Math.min.apply(Math, numbers); var max = Math.max.apply(Math, numbers); var sub = max - min; var unit = []; for (var i = 0; i < numbers.length; i++) { unit.push((numbers[i] - min) / sub); } return unit;
}
const assert = require('node:assert'); function test() { let candidate = rescale_to_unit; assert.deepEqual(candidate([2.0, 49.9]),[0.0, 1.0]); assert.deepEqual(candidate([100.0, 49.9]),[1.0, 0.0]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0]),[0.0, 0.25, 0.5, 0.75, 1.0]); assert.deepEqual(candidate([2.0, 1.0, 5.0, 3.0, 4.0]),[0.25, 0.0, 1.0, 0.5, 0.75]); assert.deepEqual(candidate([12.0, 11.0, 15.0, 13.0, 14.0]),[0.25, 0.0, 1.0, 0.5, 0.75]); } test();
humaneval-HumanEval_133_sum_squares.json-L17
js
//You are given an array of numbers. // You need to return the sum of squared numbers in the given array, // round each element in the array to the upper int(Ceiling) first. // Examples: // >>> lst([1.0, 2.0, 3.0]) // 14 // >>> lst([1.0, 4.0, 9.0]) // 98 // >>> lst([1.0, 3.0, 5.0, 7.0]) // 84 // >>> lst([1.4, 4.2, 0.0]) // 29 // >>> lst([-2.4, 1.0, 1.0]) // 6 function sum_squares(lst){ return lst.map(num => Math.ceil(num)).reduce((sum, num) => sum + num ** 2, 0);
}
const assert = require('node:assert'); function test() { let candidate = sum_squares; assert.deepEqual(candidate([1.0, 2.0, 3.0]),14); assert.deepEqual(candidate([1.0, 2.0, 3.0]),14); assert.deepEqual(candidate([1.0, 3.0, 5.0, 7.0]),84); assert.deepEqual(candidate([1.4, 4.2, 0.0]),29); assert.deepEqual(candidate([-2.4, 1.0, 1.0]),6); assert.deepEqual(candidate([100.0, 1.0, 15.0, 2.0]),10230); assert.deepEqual(candidate([10000.0, 10000.0]),200000000); assert.deepEqual(candidate([-1.4, 4.6, 6.3]),75); assert.deepEqual(candidate([-1.4, 17.9, 18.9, 19.9]),1086); assert.deepEqual(candidate([0.0]),0); assert.deepEqual(candidate([-1.0]),1); assert.deepEqual(candidate([-1.0, 1.0, 0.0]),2); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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";
} 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; } }
num -= 1000;
} 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_11_string_xor.json-L15
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> stringXor(("010"), ("110")) // ("100") public static String stringXor(String a, String b) { StringBuilder c = new StringBuilder();
c.append(a.charAt(i) ^ b.charAt(i)); } return c.toString(); } }
for (int i = 0; i < a.length(); i++) {
} public static void main(String[] args) { assert(stringXor(("111000"), ("101010")).equals(("010010"))); assert(stringXor(("1"), ("1")).equals(("0"))); assert(stringXor(("0101"), ("0000")).equals(("0101"))); } }
humaneval-HumanEval_90_next_smallest.json-L22
js
//You are given an array of integers. // Write a function next_smallest() that returns the 2nd smallest element of the array. // Return undefined if there is no such element. // >>> next_smallest([1, 2, 3, 4, 5]) // 2 // >>> next_smallest([5, 1, 4, 3, 2]) // 2 // >>> next_smallest([]) // undefined // >>> next_smallest([1, 1]) // undefined function next_smallest(lst){ if(lst.length<=1){ return undefined; } var smallest=Math.min(...lst); var second_smallest=Number.MAX_VALUE; for(var i in lst){ if(lst[i]>smallest&&lst[i]<second_smallest){ second_smallest=lst[i]; }
if(second_smallest==Number.MAX_VALUE){ return undefined; } return second_smallest; }
}
const assert = require('node:assert'); function test() { let candidate = next_smallest; assert.deepEqual(candidate([1, 2, 3, 4, 5]),2); assert.deepEqual(candidate([5, 1, 4, 3, 2]),2); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([1, 1, 1, 1, 0]),1); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([-35, 34, 12, -45]),-35); } test();
humaneval-HumanEval_135_can_arrange.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 { // 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;
} } return p; } }
break;
} 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_150_x_or_y.json-L11
js
//A simple program which should return the value of x if n is // a prime number and should return the value of y otherwise. // Examples: // >>> x_or_y(7, 34, 12) // 34 // >>> x_or_y(15, 8, 5) // 5 function x_or_y(n, x, y){ if(n<2){ return y;
for(var i=2; i<n; i++){ if(n%i==0){ return y; } } return x; }
}
const assert = require('node:assert'); function test() { let candidate = x_or_y; assert.deepEqual(candidate(7, 34, 12),34); assert.deepEqual(candidate(15, 8, 5),5); assert.deepEqual(candidate(3, 33, 5212),33); assert.deepEqual(candidate(1259, 3, 52),3); assert.deepEqual(candidate(7919, -1, 12),-1); assert.deepEqual(candidate(3609, 1245, 583),583); assert.deepEqual(candidate(91, 56, 129),129); assert.deepEqual(candidate(6, 34, 1234),1234); assert.deepEqual(candidate(1, 2, 0),0); assert.deepEqual(candidate(2, 2, 0),2); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L23
py
from typing import List def get_odd_collatz(n: int) -> List[int]: """ Given a positive integer n, return a sorted 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 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. >>> get_odd_collatz(5) [1, 5] """ collatz_list = []
while (current_num > 1): collatz_list.append(current_num) if (current_num % 2 == 0): current_num = current_num // 2 else: current_num = current_num * 3 + 1 collatz_list.append(1) return sorted(list(set([x for x in collatz_list if x % 2 != 0])))
current_num = n
def check(candidate): assert candidate(14) == [1, 5, 7, 11, 13, 17] assert candidate(5) == [1, 5] assert candidate(12) == [1, 3, 5] assert candidate(1) == [1] def test_check(): check(get_odd_collatz) test_check()
humaneval-HumanEval_125_split_words.json-L17
py
from typing import Union, List def split_words(txt: str) -> Union[List[str], int]: """ Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 Examples >>> split_words('Hello world!') ['Hello', 'world!'] >>> split_words('Hello,world!') ['Hello', 'world!'] >>> split_words('abcdef') 3 """ alphabet = [chr(letter) for letter in range(ord('a'), ord('z') + 1)]
return txt.split(' ') elif ',' in txt: return txt.split(',') else: return len([letter for letter in txt if letter in alphabet and alphabet.index(letter) % 2 == 1])
if ' ' in txt:
def check(candidate): assert candidate('Hello world!') == ['Hello', 'world!'] assert candidate('Hello,world!') == ['Hello', 'world!'] assert candidate('Hello world,!') == ['Hello', 'world,!'] assert candidate('Hello,Hello,world !') == ['Hello,Hello,world', '!'] assert candidate('abcdef') == 3 assert candidate('aaabb') == 2 assert candidate('aaaBb') == 1 assert candidate('') == 0 def test_check(): check(split_words) test_check()
humaneval-HumanEval_24_largest_divisor.json-L7
py
def largest_divisor(n: int) -> int: """ For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """ divisor = n - 1
divisor -= 1 return divisor
while n % divisor != 0:
def check(candidate): assert candidate(3) == 1 assert candidate(7) == 1 assert candidate(10) == 5 assert candidate(100) == 50 assert candidate(49) == 7 def test_check(): check(largest_divisor) test_check()
humaneval-HumanEval_55_fib.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return 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_39_prime_fib.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 { // prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> primeFib((1l)) // (2l) // >>> primeFib((2l)) // (3l) // >>> primeFib((3l)) // (5l) // >>> primeFib((4l)) // (13l) // >>> primeFib((5l)) // (89l) public static long primeFib(long n) { long fib = 1; long prev = 0;
while (count != n) { long tmp = fib; fib += prev; prev = tmp; if (BigInteger.valueOf(fib).isProbablePrime(1)) { count++; } } return fib; } }
long count = 0;
} public static void main(String[] args) { assert(primeFib((1l)) == (2l)); assert(primeFib((2l)) == (3l)); assert(primeFib((3l)) == (5l)); assert(primeFib((4l)) == (13l)); assert(primeFib((5l)) == (89l)); assert(primeFib((6l)) == (233l)); assert(primeFib((7l)) == (1597l)); assert(primeFib((8l)) == (28657l)); assert(primeFib((9l)) == (514229l)); assert(primeFib((10l)) == (433494437l)); } }
humaneval-HumanEval_108_count_nums.json-L19
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();
sum += Number(str[0] + str[1]); for(var j = 2; j < str.length; j++) { sum += Number(str[j]); } } else { for(var k = 0; k < str.length; k++) { sum += Number(str[k]); } } if(sum > 0) { count++; } } return count; }
if(str[0] === '-') {
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_152_compare.json-L22
js
//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 arrays of scores and guesses of equal length, where each index shows a match. // Return an array 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([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]) // [0, 0, 0, 0, 3, 3] // >>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2]) // [4, 4, 1, 0, 0, 6] function compare(game, guess){ let result = []; for(let i = 0; i < game.length; i++){ if(game[i] === guess[i]){ result.push(0); } else { result.push(Math.abs(game[i] - guess[i])); } }
}
return result;
const assert = require('node:assert'); function test() { let candidate = compare; assert.deepEqual(candidate([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]),[0, 0, 0, 0, 3, 3]); assert.deepEqual(candidate([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]),[0, 0, 0, 0, 0, 0]); assert.deepEqual(candidate([1, 2, 3], [-1, -2, -3]),[2, 4, 6]); assert.deepEqual(candidate([1, 2, 3, 5], [-1, 2, 3, 4]),[2, 0, 0, 1]); } test();