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_35_max_element.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return maximum element in the array list. // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (3l) // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))) // (123l) public static long maxElement(ArrayList<Long> l) { Long max = Long.MIN_VALUE; for (int i = 0; i < l.size(); i += 1) { if (l.get(i) > max) { max = l.get(i); } } return max; }
}
} public static void main(String[] args) { assert(maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (3l)); assert(maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)124l, (long)1l, (long)-10l)))) == (124l)); } }
humaneval-HumanEval_28_concatenate.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 { // Concatenate array list of strings into a single string // >>> concatenate((new ArrayList<String>(Arrays.asList()))) // ("") // >>> concatenate((new ArrayList<String>(Arrays.asList((String)"a", (String)"b", (String)"c")))) // ("abc") public static String concatenate(ArrayList<String> strings) {
} }
return strings.stream().collect(Collectors.joining());
} public static void main(String[] args) { assert(concatenate((new ArrayList<String>(Arrays.asList()))).equals((""))); assert(concatenate((new ArrayList<String>(Arrays.asList((String)"x", (String)"y", (String)"z")))).equals(("xyz"))); assert(concatenate((new ArrayList<String>(Arrays.asList((String)"x", (String)"y", (String)"z", (String)"w", (String)"k")))).equals(("xyzwk"))); } }
humaneval-HumanEval_84_solve.json-L20
js
//Given a positive integer N, return the total sum of its digits in binary. // Example // >>> solve(1000) // "1" // >>> solve(150) // "110" // >>> solve(147) // "1100" // Variables: // @N integer // Constraints: 0 ≤ N ≤ 10000. // Output: // a string of binary number function solve(N){ let newN = N.toString(); let total = 0; for(let i = 0; i < newN.length; i++){ let digit = newN[i]; total += parseInt(digit);
return total.toString(2); }
}
const assert = require('node:assert'); function test() { let candidate = solve; assert.deepEqual(candidate(1000),"1"); assert.deepEqual(candidate(150),"110"); assert.deepEqual(candidate(147),"1100"); assert.deepEqual(candidate(333),"1001"); assert.deepEqual(candidate(963),"10010"); } test();
humaneval-HumanEval_71_triangle_area.json-L17
py
def triangle_area(a: int, b: int, c: int) -> float: """ Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: >>> triangle_area(3, 4, 5) 6.0 >>> triangle_area(1, 2, 10) -1 """ if a + b > c and a + c > b and b + c > a: perimeter = (a + b + c) / 2 area = (perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c)) ** 0.5
else: return -1
return round(area, 2)
def check(candidate): assert candidate(3, 4, 5) == 6.0 assert candidate(1, 2, 10) == -1 assert candidate(4, 8, 5) == 8.18 assert candidate(2, 2, 2) == 1.73 assert candidate(1, 2, 3) == -1 assert candidate(10, 5, 7) == 16.25 assert candidate(2, 6, 3) == -1 assert candidate(1, 1, 1) == 0.43 assert candidate(2, 2, 10) == -1 def test_check(): check(triangle_area) test_check()
humaneval-HumanEval_63_fibfib.json-L16
js
//The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib(1) // 0 // >>> fibfib(5) // 4 // >>> fibfib(8) // 24 function fibfib(n){ if(n <= 0){ return 0;
if(n == 1){ return 0; } if(n == 2){ return 1; } return fibfib(n-1) + fibfib(n-2) + fibfib(n-3); }
}
const assert = require('node:assert'); function test() { let candidate = fibfib; assert.deepEqual(candidate(2),1); assert.deepEqual(candidate(1),0); assert.deepEqual(candidate(5),4); assert.deepEqual(candidate(8),24); assert.deepEqual(candidate(10),81); assert.deepEqual(candidate(12),274); assert.deepEqual(candidate(14),927); } test();
humaneval-HumanEval_58_common.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 sorted unique common elements for two array lists. // >>> common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l))) // >>> common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))) public static ArrayList<Long> common(ArrayList<Long> l1, ArrayList<Long> l2) { return new ArrayList<Long>( l1.stream() .filter(l2::contains) .collect(Collectors.toSet()) ); }
}
} public static void main(String[] args) { assert(common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_156_int_to_mini_roman.json-L21
js
//Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> int_to_mini_roman(19) // "xix" // >>> int_to_mini_roman(152) // "clii" // >>> int_to_mini_roman(426) // "cdxxvi" function int_to_mini_roman(number){ var roman_conversion = { 1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl",
9: "ix", 5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number); key_list.sort(function(a, b){return b-a}); for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i]; break; } } } return output; }
10: "x",
const assert = require('node:assert'); function test() { let candidate = int_to_mini_roman; assert.deepEqual(candidate(19),"xix"); assert.deepEqual(candidate(152),"clii"); assert.deepEqual(candidate(251),"ccli"); assert.deepEqual(candidate(426),"cdxxvi"); assert.deepEqual(candidate(500),"d"); assert.deepEqual(candidate(1),"i"); assert.deepEqual(candidate(4),"iv"); assert.deepEqual(candidate(43),"xliii"); assert.deepEqual(candidate(90),"xc"); assert.deepEqual(candidate(94),"xciv"); assert.deepEqual(candidate(532),"dxxxii"); assert.deepEqual(candidate(900),"cm"); assert.deepEqual(candidate(994),"cmxciv"); assert.deepEqual(candidate(1000),"m"); } test();
humaneval-HumanEval_141_file_name_check.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\.");
return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result; } String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; } } if (count > 3) { return result; } if (name.length() == 0) { return result; } if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes"; } }
if (tokens.length != 2) {
} public static void main(String[] args) { assert(fileNameCheck(("example.txt")).equals(("Yes"))); assert(fileNameCheck(("1example.dll")).equals(("No"))); assert(fileNameCheck(("s1sdf3.asd")).equals(("No"))); assert(fileNameCheck(("K.dll")).equals(("Yes"))); assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes"))); assert(fileNameCheck(("His12FILE94.exe")).equals(("No"))); assert(fileNameCheck(("_Y.txt")).equals(("No"))); assert(fileNameCheck(("?aREYA.exe")).equals(("No"))); assert(fileNameCheck(("/this_is_valid.dll")).equals(("No"))); assert(fileNameCheck(("this_is_valid.wow")).equals(("No"))); assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes"))); assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No"))); assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No"))); assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No"))); assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No"))); assert(fileNameCheck(("all.exe.txt")).equals(("No"))); assert(fileNameCheck(("I563_No.exe")).equals(("Yes"))); assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes"))); assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes"))); assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No"))); assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No"))); assert(fileNameCheck(("final..txt")).equals(("No"))); assert(fileNameCheck(("final132")).equals(("No"))); assert(fileNameCheck(("_f4indsartal132.")).equals(("No"))); assert(fileNameCheck((".txt")).equals(("No"))); assert(fileNameCheck(("s.")).equals(("No"))); } }
humaneval-HumanEval_135_can_arrange.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 { // 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--) {
p = (long)i; break; } } return p; } }
if (arr.get(i) < arr.get(i - 1)) {
} 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_41_car_race_collision.json-L14
py
def car_race_collision(n: int) -> int: """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ l = n * n
left_cars = [i for i in range(l)] right_cars = [i for i in range(l)] for i in range(l): for j in range(l): if left_cars[i] == right_cars[j]: count += 1 return count
count = 0
def check(candidate): assert candidate(2) == 4 assert candidate(3) == 9 assert candidate(4) == 16 assert candidate(8) == 64 assert candidate(10) == 100 def test_check(): check(car_race_collision) test_check()
humaneval-HumanEval_138_is_equal_to_sum_even.json-L12
py
def is_equal_to_sum_even(n: int) -> bool: """Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example >>> is_equal_to_sum_even(4) False >>> is_equal_to_sum_even(6) False >>> is_equal_to_sum_even(8) True """ if n < 8:
return n % 2 == 0
return False
def check(candidate): assert candidate(4) == False assert candidate(6) == False assert candidate(8) == True assert candidate(10) == True assert candidate(11) == False assert candidate(12) == True assert candidate(13) == False assert candidate(16) == True def test_check(): check(is_equal_to_sum_even) test_check()
humaneval-HumanEval_21_rescale_to_unit.json-L6
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 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; }
var min = Math.min.apply(Math, numbers);
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_105_by_length.json-L52
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine");
} return arr3; }
}
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_131_digits.json-L15
js
//Given a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits(1) // 1 // >>> digits(4) // 0 // >>> digits(235) // 15 function digits(n){ if(!n){ return "error"; } if(n < 0){
} var temp = 0; var prod = 1; var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp; odd = false; } } if(odd){ return 0; } return prod; }
return "error";
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_77_iscube.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes an integer a and returns true // if this ingeger is a cube of some integer number. // Note: you may assume the input is always valid. // Examples: // >>> iscube((1l)) // (true) // >>> iscube((2l)) // (false) // >>> iscube((-1l)) // (true) // >>> iscube((64l)) // (true) // >>> iscube((0l)) // (true) // >>> iscube((180l)) // (false) public static boolean iscube(long a) { return a==0l||(a>0l&&Math.pow(Math.round(Math.pow(a, 1.0/3.0)), 3)==a)||(a<0l&&Math.pow(Math.round(Math.pow(-a, 1.0/3.0)), 3)==-a);
}
}
} public static void main(String[] args) { assert(iscube((1l)) == (true)); assert(iscube((2l)) == (false)); assert(iscube((-1l)) == (true)); assert(iscube((64l)) == (true)); assert(iscube((180l)) == (false)); assert(iscube((1000l)) == (true)); assert(iscube((0l)) == (true)); assert(iscube((1729l)) == (false)); } }
humaneval-HumanEval_141_file_name_check.json-L50
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result; } String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; } } if (count > 3) { return result; } if (name.length() == 0) { return result; } if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes";
}
}
} public static void main(String[] args) { assert(fileNameCheck(("example.txt")).equals(("Yes"))); assert(fileNameCheck(("1example.dll")).equals(("No"))); assert(fileNameCheck(("s1sdf3.asd")).equals(("No"))); assert(fileNameCheck(("K.dll")).equals(("Yes"))); assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes"))); assert(fileNameCheck(("His12FILE94.exe")).equals(("No"))); assert(fileNameCheck(("_Y.txt")).equals(("No"))); assert(fileNameCheck(("?aREYA.exe")).equals(("No"))); assert(fileNameCheck(("/this_is_valid.dll")).equals(("No"))); assert(fileNameCheck(("this_is_valid.wow")).equals(("No"))); assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes"))); assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No"))); assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No"))); assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No"))); assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No"))); assert(fileNameCheck(("all.exe.txt")).equals(("No"))); assert(fileNameCheck(("I563_No.exe")).equals(("Yes"))); assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes"))); assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes"))); assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No"))); assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No"))); assert(fileNameCheck(("final..txt")).equals(("No"))); assert(fileNameCheck(("final132")).equals(("No"))); assert(fileNameCheck(("_f4indsartal132.")).equals(("No"))); assert(fileNameCheck((".txt")).equals(("No"))); assert(fileNameCheck(("s.")).equals(("No"))); } }
humaneval-HumanEval_115_max_fill.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 { // 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) {
for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity; if (level % capacity != 0l) { units += 1l; } count += units; } return count; } }
long level = 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_6_parse_nested_parens.json-L14
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0; var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){ level += 1; if (level > maxlevel){
} } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
maxlevel = level;
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_81_numerical_letter_grade.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 { // 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 array list of GPAs for some students and you have to write // a function that can output an array array 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: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) {
} else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-"); } else { letterGrades.add("E"); } } return letterGrades; } }
letterGrades.add("C+");
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_49_modp.json-L17
js
//Return 2^n modulo p (be aware of numerics). // >>> modp(3, 5) // 3 // >>> modp(1101, 101) // 2 // >>> modp(0, 101) // 1 // >>> modp(3, 11) // 8 // >>> modp(100, 101) // 1 function modp(n, p){ var result = 1; while(n>0){ result = (result*2)%p; n--;
return result; }
}
const assert = require('node:assert'); function test() { let candidate = modp; assert.deepEqual(candidate(3, 5),3); assert.deepEqual(candidate(1101, 101),2); assert.deepEqual(candidate(0, 101),1); assert.deepEqual(candidate(3, 11),8); assert.deepEqual(candidate(100, 101),1); assert.deepEqual(candidate(30, 5),4); assert.deepEqual(candidate(31, 5),3); } test();
humaneval-HumanEval_144_simplify.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Your task is to implement a function that will simplify the expression // x * n. The function returns true if x * n evaluates to a whole number and false // otherwise. Both x and n, are string representation of a fraction, and have the following format, // <numerator>/<denominator> where both numerator and denominator are positive whole numbers. // You can assume that x, and n are valid fractions, and do not have zero as denominator. // >>> simplify(("1/5"), ("5/1")) // (true) // >>> simplify(("1/6"), ("2/1")) // (false) // >>> simplify(("7/10"), ("10/2")) // (false) public static boolean simplify(String x, String n) { String[] nums = x.split("/"); String[] n_nums = n.split("/"); int x_num = Integer.parseInt(nums[0]); int n_num = Integer.parseInt(n_nums[0]); int x_denom = Integer.parseInt(nums[1]); int n_denom = Integer.parseInt(n_nums[1]);
int res_denom = x_denom * n_denom; return (res_num % res_denom == 0); } }
int res_num = x_num * n_num;
} public static void main(String[] args) { assert(simplify(("1/5"), ("5/1")) == (true)); assert(simplify(("1/6"), ("2/1")) == (false)); assert(simplify(("5/1"), ("3/1")) == (true)); assert(simplify(("7/10"), ("10/2")) == (false)); assert(simplify(("2/10"), ("50/10")) == (true)); assert(simplify(("7/2"), ("4/2")) == (true)); assert(simplify(("11/6"), ("6/1")) == (true)); assert(simplify(("2/3"), ("5/2")) == (false)); assert(simplify(("5/2"), ("3/5")) == (false)); assert(simplify(("2/4"), ("8/4")) == (true)); assert(simplify(("2/4"), ("4/2")) == (true)); assert(simplify(("1/5"), ("5/1")) == (true)); assert(simplify(("1/5"), ("1/5")) == (false)); } }
humaneval-HumanEval_117_select_words.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e':
case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) { ret.add(word); } } return ret; } }
case 'i':
} 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_95_check_dict_case.json-L23
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()):
if any(not x.islower() for x in dict.keys()): if any(not x.isupper() for x in dict.keys()): return False 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_64_vowels_count.json-L21
js
//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 function vowels_count(s){ s=s.toLowerCase(); var vowels = ['a','e','i','o','u']; var count = 0; for(var i=0; i<s.length; i++){ if(vowels.indexOf(s[i])!=-1){ count++; } } if(s[s.length-1]=='y'){ count++;
return count; }
}
const assert = require('node:assert'); function test() { let candidate = vowels_count; assert.deepEqual(candidate("abcde"),2); assert.deepEqual(candidate("Alone"),3); assert.deepEqual(candidate("key"),2); assert.deepEqual(candidate("bye"),1); assert.deepEqual(candidate("keY"),2); assert.deepEqual(candidate("bYe"),1); assert.deepEqual(candidate("ACEDY"),3); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L51
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 array list of GPAs for some students and you have to write // a function that can output an array array 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: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) { letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C");
letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-"); } else { letterGrades.add("E"); } } return letterGrades; } }
} else if (currentGrade > 1.3f) {
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_153_Strongest_Extension.json-L21
py
from typing import List def Strongest_Extension(class_name: str, extensions: List[str]) -> str: """You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -1). Example: >>> Strongest_Extension('my_class', ['AA', 'Be', 'CC']) 'my_class.AA' """
for extension in extensions: n_uppercase = sum(1 for c in extension if c.isupper()) n_lowercase = sum(1 for c in extension if c.islower()) if n_uppercase - n_lowercase > best_strength: best_strength = n_uppercase - n_lowercase best_extension = extension return class_name + '.' + best_extension
best_strength, best_extension = -1, ''
def check(candidate): assert candidate('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) == 'Watashi.eIGHt8OKe' assert candidate('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg']) == 'Boku123.YEs.WeCaNe' assert candidate('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321']) == '__YESIMHERE.NuLl__' assert candidate('K', ['Ta', 'TAR', 't234An', 'cosSo']) == 'K.TAR' assert candidate('__HAHA', ['Tab', '123', '781345', '-_-']) == '__HAHA.123' assert candidate('YameRore', ['HhAas', 'okIWILL123', 'WorkOut', 'Fails', '-_-']) == 'YameRore.okIWILL123' assert candidate('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) == 'finNNalLLly.WoW' assert candidate('_', ['Bb', '91245']) == '_.Bb' assert candidate('Sp', ['671235', 'Bb']) == 'Sp.671235' def test_check(): check(Strongest_Extension) test_check()
humaneval-HumanEval_90_next_smallest.json-L26
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_123_get_odd_collatz.json-L16
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = []
var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) } if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
var odd_numbers = []
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_98_count_upper.json-L14
js
//Given a string s, count the number of uppercase vowels in even indices. // For example: // >>> count_upper("aBCdEf") // 1 // >>> count_upper("abcdefg") // 0 // >>> count_upper("dBBE") // 0 function count_upper(s){ var index; var result = 0; var vowel = ['A', 'E', 'I', 'O', 'U']; for (index = 0; index < s.length; index += 2){
result += 1; } } return result; }
if (vowel.indexOf(s[index]) > -1){
const assert = require('node:assert'); function test() { let candidate = count_upper; assert.deepEqual(candidate("aBCdEf"),1); assert.deepEqual(candidate("abcdefg"),0); assert.deepEqual(candidate("dBBE"),0); assert.deepEqual(candidate("B"),0); assert.deepEqual(candidate("U"),1); assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("EEEE"),2); } test();
humaneval-HumanEval_72_will_it_fly.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 { // Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) {
} for (int i = 0; i < q.size() / 2; i++) { if (q.get(i) != q.get(q.size() - 1 - i)) { return false; } } return true; } }
return false;
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_110_exchange.json-L37
js
//In this problem, you will implement a function that takes two arrays of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array of only even numbers. // There is no limit on the number of exchanged elements between lst1 and lst2. // If it is possible to exchange elements between the lst1 and lst2 to make // all the elements of lst1 to be even, return "YES". // Otherwise, return "NO". // For example: // >>> exchange([1, 2, 3, 4], [1, 2, 3, 4]) // "YES" // >>> exchange([1, 2, 3, 4], [1, 5, 3, 4]) // "NO" // It is assumed that the input arrays will be non-empty. function exchange(lst1, lst2){ var num1 = 0; var num2 = 0; var exchange = true; while(num1 < lst1.length && exchange){ if(lst1[num1] % 2 !== 0){ exchange = false; if(num2 < lst2.length){ while(num2 < lst2.length && exchange == false){ if(lst2[num2] % 2 == 0){ lst1[num1] = lst2[num2]; exchange = true; } num2++; } } } num1++; } if(exchange){ return "YES"; }else{ return "NO";
}
}
const assert = require('node:assert'); function test() { let candidate = exchange; assert.deepEqual(candidate([1, 2, 3, 4], [1, 2, 3, 4]),"YES"); assert.deepEqual(candidate([1, 2, 3, 4], [1, 5, 3, 4]),"NO"); assert.deepEqual(candidate([1, 2, 3, 4], [2, 1, 4, 3]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 4]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 3]),"NO"); assert.deepEqual(candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]),"NO"); assert.deepEqual(candidate([100, 200], [200, 200]),"YES"); } test();
humaneval-HumanEval_71_triangle_area.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given the lengths of the three sides of a triangle. Return the area of // the triangle rounded to 2 decimal points if the three sides form a valid triangle. // Otherwise return -1 // Three sides make a valid triangle when the sum of any two sides is greater // than the third side. // Example: // >>> triangleArea((3l), (4l), (5l)) // (6.0f) // >>> triangleArea((1l), (2l), (10l)) // (float)-1l public static float triangleArea(long a, long b, long c) { if(a + b > c && a + c > b && b + c > a) { float s = (a + b + c) / 2.0f; float area = (float)Math.sqrt(s * (s - a) * (s - b) * (s - c)); return (float)Math.round(area * 100) / 100;
return -1; } }
}
} public static void main(String[] args) { assert(triangleArea((3l), (4l), (5l)) == (6.0f)); assert(triangleArea((1l), (2l), (10l)) == (float)-1l); assert(triangleArea((4l), (8l), (5l)) == (8.18f)); assert(triangleArea((2l), (2l), (2l)) == (1.73f)); assert(triangleArea((1l), (2l), (3l)) == (float)-1l); assert(triangleArea((10l), (5l), (7l)) == (16.25f)); assert(triangleArea((2l), (6l), (3l)) == (float)-1l); assert(triangleArea((1l), (1l), (1l)) == (0.43f)); assert(triangleArea((2l), (2l), (10l)) == (float)-1l); } }
humaneval-HumanEval_1_separate_paren_groups.json-L23
py
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ paren_string = paren_string.replace(' ', '') groups = [] group = '' open_count = 0 for c in paren_string: if c == '(': open_count += 1 elif c == ')': open_count -= 1 group += c if open_count == 0: groups.append(group)
return groups
group = ''
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())'] assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))'] assert candidate('(()(())((())))') == ['(()(())((())))'] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())'] def test_check(): check(separate_paren_groups) test_check()
humaneval-HumanEval_95_check_dict_case.json-L45
js
//Given an object, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; } } else if (case_type == 1){ if (key != key.toUpperCase()){ return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } } else{
} } return true; }
return false;
const assert = require('node:assert'); function test() { let candidate = check_dict_case; assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true); assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false); assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false); assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false); assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true); assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true); assert.deepEqual(candidate({}),false); } test();
humaneval-HumanEval_119_match_parens.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given an array array list of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))) // ("Yes") // >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))) // ("No") public static String matchParens(ArrayList<String> lst) { String s1 = lst.get(0); String s2 = lst.get(1);
String s4 = s2+s1; int c1 = 0; int c2 = 0; for (int i = 0; i < s3.length(); i++) { if (s3.charAt(i) == '(') c1 += 1; else c1 -= 1; if (c1 < 0) break; } for (int i = 0; i < s4.length(); i++) { if (s4.charAt(i) == '(') c2 += 1; else c2 -= 1; if (c2 < 0) break; } if (c1 == 0 || c2 == 0) return "Yes"; else return "No"; } }
String s3 = s1+s2;
} public static void main(String[] args) { assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes"))); } }
humaneval-HumanEval_39_prime_fib.json-L24
js
//prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> prime_fib(1) // 2 // >>> prime_fib(2) // 3 // >>> prime_fib(3) // 5 // >>> prime_fib(4) // 13 // >>> prime_fib(5) // 89 function prime_fib(n){ function isPrime(number){ if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false;
} return true; } } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b; b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
}
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_137_compare_one.json-L56
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None
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
elif isinstance(a, str) and isinstance(b, int):
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_119_match_parens.json-L24
js
//You are given an array of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> match_parens(["()(", ")"]) // "Yes" // >>> match_parens([")", ")"]) // "No" function match_parens(lst){ const open = '('; const close = ')'; const is_good = (s) => { let stack = []; for (let p of s){ if (p === open){ stack.push(p); } else if (p === close){ if (stack.length === 0){
} stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
return false;
const assert = require('node:assert'); function test() { let candidate = match_parens; assert.deepEqual(candidate(["()(", ")"]),"Yes"); assert.deepEqual(candidate([")", ")"]),"No"); assert.deepEqual(candidate(["(()(())", "())())"]),"No"); assert.deepEqual(candidate([")())", "(()()("]),"Yes"); assert.deepEqual(candidate(["(())))", "(()())(("]),"Yes"); assert.deepEqual(candidate(["()", "())"]),"No"); assert.deepEqual(candidate(["(()(", "()))()"]),"Yes"); assert.deepEqual(candidate(["((((", "((())"]),"No"); assert.deepEqual(candidate([")(()", "(()("]),"No"); assert.deepEqual(candidate([")(", ")("]),"No"); assert.deepEqual(candidate(["(", ")"]),"Yes"); assert.deepEqual(candidate([")", "("]),"Yes"); } test();
humaneval-HumanEval_125_split_words.json-L22
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); } else if(txt.includes(',')){ return txt.split(','); } else{ let count = 0; for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){
count++; } } } return count; } }
if(txt[i] == txt[i].toLowerCase()){
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L21
py
def is_multiply_prime(a: int) -> bool: """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: >>> is_multiply_prime(30) True 30 = 2 * 3 * 5 """ n = a d = 2 prime_factors = [] while d * d <= n: if n % d == 0: prime_factors.append(d) n //= d else: d += 1 if n > 1: prime_factors.append(n)
return True else: return False
if len(prime_factors) == 3:
def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(105) == True assert candidate(126) == False assert candidate(729) == False assert candidate(891) == False assert candidate(1001) == True def test_check(): check(is_multiply_prime) test_check()
humaneval-HumanEval_49_modp.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 2^n modulo p (be aware of numerics). // >>> modp((3l), (5l)) // (3l) // >>> modp((1101l), (101l)) // (2l) // >>> modp((0l), (101l)) // (1l) // >>> modp((3l), (11l)) // (8l) // >>> modp((100l), (101l)) // (1l) public static long modp(long n, long p) { if (n == 0) return 1; long sqrt = modp(n / 2, p); sqrt = (sqrt * sqrt) % p; if (n % 2 == 0) {
} return (sqrt * 2) % p; } }
return sqrt;
} public static void main(String[] args) { assert(modp((3l), (5l)) == (3l)); assert(modp((1101l), (101l)) == (2l)); assert(modp((0l), (101l)) == (1l)); assert(modp((3l), (11l)) == (8l)); assert(modp((100l), (101l)) == (1l)); assert(modp((30l), (5l)) == (4l)); assert(modp((31l), (5l)) == (3l)); } }
humaneval-HumanEval_21_rescale_to_unit.json-L9
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;
for (var i = 0; i < numbers.length; i++) { unit.push((numbers[i] - min) / sub); } return unit; }
var 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_3_below_zero.json-L17
js
//You're given an array of deposit and withdrawal operations on a bank account that starts with // zero balance. Your task is to detect if at any point the balance of account fallls below zero, and // at that point function should return true. Otherwise it should return false. // >>> below_zero([1, 2, 3]) // false // >>> below_zero([1, 2, -4, 5]) // true function below_zero(operations){ var sum = 0; for (var i = 0; i < operations.length; i++) { sum += operations[i]; if (sum < 0) { return true; } } return false;
}
const assert = require('node:assert'); function test() { let candidate = below_zero; assert.deepEqual(candidate([]),false); assert.deepEqual(candidate([1, 2, -3, 1, 2, -3]),false); assert.deepEqual(candidate([1, 2, -4, 5, 6]),true); assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -4]),false); assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -5]),true); assert.deepEqual(candidate([1, -2, 2, -2, 5, -5, 4, -4]),true); } test();
humaneval-HumanEval_128_prod_signs.json-L31
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)
sign_arr.append(-1) else: sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
elif num < 0:
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_6_parse_nested_parens.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 { // Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parseNestedParens(("(()()) ((())) () ((())()())")) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))) public static ArrayList<Long> parseNestedParens(String paren_string) { ArrayList<Long> result = new ArrayList<Long>(); String[] paren_strings = paren_string.split(" "); for (String paren : paren_strings) { long max_depth = 0; long current_depth = 0; for (char c : paren.toCharArray()) { if (c == '(') { current_depth += 1;
} else if (c == ')') { current_depth -= 1; } } result.add(max_depth); } return result; } }
max_depth = Math.max(max_depth, current_depth);
} public static void main(String[] args) { assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))))); assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l))))); } }
humaneval-HumanEval_89_encrypt.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 { // 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") public static String encrypt(String s) { StringBuffer b = new StringBuffer(); for (char c : s.toCharArray()) { b.append((char)((c+4) > 'z' ? (((c+4)%'z')+'a'-1) : c+4)); } return b.toString(); }
}
} public static void main(String[] args) { assert(encrypt(("hi")).equals(("lm"))); assert(encrypt(("asdfghjkl")).equals(("ewhjklnop"))); assert(encrypt(("gf")).equals(("kj"))); assert(encrypt(("et")).equals(("ix"))); assert(encrypt(("faewfawefaewg")).equals(("jeiajeaijeiak"))); assert(encrypt(("hellomyfriend")).equals(("lippsqcjvmirh"))); assert(encrypt(("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh")).equals(("hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"))); assert(encrypt(("a")).equals(("e"))); } }
humaneval-HumanEval_83_starts_one_ends.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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++) { String s = "" + i; if (s.startsWith("1") || s.endsWith("1")) count++; }
} }
return count;
} 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_124_valid_date.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 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;
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; } }
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
} 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_143_words_in_sentence.json-L20
js
//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: // >>> words_in_sentence("This is a test") // "is" // Example 2: // >>> words_in_sentence("lets go for swimming") // "go for" // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters function words_in_sentence(sentence){ return sentence.split(' ').filter(word => { var number = word.length; var isPrime = true; if(number === 1 || number === 0){
} for(var i = 2; i < number; i++){ if(number % i === 0){ isPrime = false; break; } } return isPrime; }).join(' '); }
return false;
const assert = require('node:assert'); function test() { let candidate = words_in_sentence; assert.deepEqual(candidate("This is a test"),"is"); assert.deepEqual(candidate("lets go for swimming"),"go for"); assert.deepEqual(candidate("there is no place available here"),"there is no place"); assert.deepEqual(candidate("Hi I am Hussein"),"Hi am Hussein"); assert.deepEqual(candidate("go for it"),"go for it"); assert.deepEqual(candidate("here"),""); assert.deepEqual(candidate("here is"),"is"); } test();
humaneval-HumanEval_80_is_happy.json-L18
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){
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; }
let happy = true;
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_106_f.json-L17
js
//Implement the function f that takes n as a parameter, // and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f(5) // [1, 2, 6, 24, 15] function f(n){ var result = []; var sum = 0; var factorial = 1; for(var i = 1; i <= n; i++){ if(i % 2 == 0){ for(var j = 1; j <= i; j++){ factorial *= j;
result.push(factorial); factorial = 1; }else{ for(var k = 1; k <= i; k++){ sum += k; } result.push(sum); sum = 0; } } return result; }
}
const assert = require('node:assert'); function test() { let candidate = f; assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]); assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]); assert.deepEqual(candidate(1),[1]); assert.deepEqual(candidate(3),[1, 2, 6]); } test();
humaneval-HumanEval_129_minPath.json-L66
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){
} } currCell = nextCell; } return path; }
nextCell = curr;
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_129_minPath.json-L37
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;
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; }
for(let l = 0; l < k; l++){
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_137_compare_one.json-L27
js
//Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return undefined if the values are equal. // Note: If a real number is represented as a string, the floating point might be . or , // >>> compare_one(1, 2.5) // 2.5 // >>> compare_one(1, "2,3") // "2,3" // >>> compare_one("5,1", "6") // "6" // >>> compare_one("1", 1) // undefined function compare_one(a, b){ if (typeof a === typeof b){ if (a > b) { return a; } else if (a < b) { return b; } else { return undefined; } } else if (typeof a === "string" && typeof b === "number"){ if (a[0] > b){ return a; } else if (a[0] < b){
} else { return undefined; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){ return a; } else if (a < b[0]){ return b; } else { return undefined; } } }
return b;
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_89_encrypt.json-L17
py
def encrypt(s: str) -> str: """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' """ input_string = "abcdefghijklmnopqrstuvwxyz"
for i in s: output_string += input_string[(input_string.index(i)+4)%26] return output_string
output_string = ""
def check(candidate): assert candidate('hi') == 'lm' assert candidate('asdfghjkl') == 'ewhjklnop' assert candidate('gf') == 'kj' assert candidate('et') == 'ix' assert candidate('faewfawefaewg') == 'jeiajeaijeiak' assert candidate('hellomyfriend') == 'lippsqcjvmirh' assert candidate('dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh') == 'hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl' assert candidate('a') == 'e' def test_check(): check(encrypt) test_check()
humaneval-HumanEval_44_change_base.json-L11
js
//Change numerical base of input number x to base. // return string representation after the conversion. // base numbers are less than 10. // >>> change_base(8, 3) // "22" // >>> change_base(8, 2) // "1000" // >>> change_base(7, 2) // "111" function change_base(x, base){
let q = Math.floor(x / base); if (q === 0) return r.toString(); return change_base(q, base) + r.toString(); }
let r = x % base;
const assert = require('node:assert'); function test() { let candidate = change_base; assert.deepEqual(candidate(8, 3),"22"); assert.deepEqual(candidate(9, 3),"100"); assert.deepEqual(candidate(234, 2),"11101010"); assert.deepEqual(candidate(16, 2),"10000"); assert.deepEqual(candidate(8, 2),"1000"); assert.deepEqual(candidate(7, 2),"111"); assert.deepEqual(candidate(2, 3),"2"); assert.deepEqual(candidate(3, 4),"3"); assert.deepEqual(candidate(4, 5),"4"); assert.deepEqual(candidate(5, 6),"5"); assert.deepEqual(candidate(6, 7),"6"); assert.deepEqual(candidate(7, 8),"7"); } test();
humaneval-HumanEval_108_count_nums.json-L26
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):
if s > 0: n += 1 return n
s += int(j)
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_12_longest.json-L20
js
//Out of array of strings, return the longest one. Return the first one in case of multiple // strings of the same length. Return undefined in case the input array is empty. // >>> longest([]) // undefined // >>> longest(["a", "b", "c"]) // "a" // >>> longest(["a", "bb", "ccc"]) // "ccc" function longest(strings){ var result; if (strings.length === 0) { return undefined; } for (var i = 0; i < strings.length; i++) { if (!result || strings[i].length > result.length) { result = strings[i]; } } return result;
}
const assert = require('node:assert'); function test() { let candidate = longest; assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate(["x", "y", "z"]),"x"); assert.deepEqual(candidate(["x", "yyy", "zzzz", "www", "kkkk", "abc"]),"zzzz"); } test();
humaneval-HumanEval_3_below_zero.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 { // You're given an array array list of deposit and withdrawal operations on a bank account that starts with // zero balance. Your task is to detect if at any point the balance of account fallls below zero, and // at that point function should return true. Otherwise it should return false. // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (false) // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l)))) // (true) public static boolean belowZero(ArrayList<Long> operations) { long balance = 0; for (long op : operations) { balance += op; if (balance < 0) { return true; }
return false; } }
}
} public static void main(String[] args) { assert(belowZero((new ArrayList<Long>(Arrays.asList()))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-3l, (long)1l, (long)2l, (long)-3l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l, (long)6l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-5l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-2l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (true)); } }
humaneval-HumanEval_47_median.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 median of elements in the array list l. // >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) // (float)3l // >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) // (15.0f) public static float median(ArrayList<Long> l) { float ret = 0; Collections.sort(l); int size = l.size(); if (size % 2 == 0) { ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f; } else { ret = l.get(size / 2); } return ret; }
}
} public static void main(String[] args) { assert(median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) == (float)3l); assert(median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) == (8.0f)); assert(median((new ArrayList<Long>(Arrays.asList((long)5l)))) == (float)5l); assert(median((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l)))) == (5.5f)); assert(median((new ArrayList<Long>(Arrays.asList((long)8l, (long)1l, (long)3l, (long)9l, (long)9l, (long)2l, (long)7l)))) == (float)7l); } }
humaneval-HumanEval_96_count_up_to.json-L24
js
//Implement a function that takes an non-negative integer and returns an array of the first n // integers that are prime numbers and less than n. // for example: // >>> count_up_to(5) // [2, 3] // >>> count_up_to(11) // [2, 3, 5, 7] // >>> count_up_to(0) // [] // >>> count_up_to(20) // [2, 3, 5, 7, 11, 13, 17, 19] // >>> count_up_to(1) // [] // >>> count_up_to(18) // [2, 3, 5, 7, 11, 13, 17] function count_up_to(n){ if (n < 2) return []; var output = [2]; for (var i = 3; i < n; i += 2){ var prime = true; for (var j = 3; j < i; j += 2){ if (i % j === 0){ prime = false;
} } if (prime) output.push(i); } return output; }
break;
const assert = require('node:assert'); function test() { let candidate = count_up_to; assert.deepEqual(candidate(5),[2, 3]); assert.deepEqual(candidate(6),[2, 3, 5]); assert.deepEqual(candidate(7),[2, 3, 5]); assert.deepEqual(candidate(10),[2, 3, 5, 7]); assert.deepEqual(candidate(0),[]); assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]); assert.deepEqual(candidate(1),[]); assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]); assert.deepEqual(candidate(101),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]); } test();
humaneval-HumanEval_128_prod_signs.json-L15
js
//You are given an array arr of integers and you need to return // sum of magnitudes of integers multiplied by product of all signs // of each number in the array, represented by 1, -1 or 0. // Note: return undefined for empty arr. // Example: // >>> prod_signs([1, 2, 2, -4]) // 9 // >>> prod_signs([0, 1]) // 0 // >>> prod_signs([]) // undefined function prod_signs(arr){ var total = 0; var len = arr.length;
if(len == 0){ return undefined; } else{ for(var i = 0; i < len; i++){ total += Math.abs(arr[i]); if(arr[i] < 0){ pro *= -1; } else if(arr[i] == 0){ pro *= 0; } } total *= pro; return total; } }
var pro = 1;
const assert = require('node:assert'); function test() { let candidate = prod_signs; assert.deepEqual(candidate([1, 2, 2, -4]),-9); assert.deepEqual(candidate([0, 1]),0); assert.deepEqual(candidate([1, 1, 1, 2, 3, -1, 1]),-10); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([2, 4, 1, 2, -1, -1, 9]),20); assert.deepEqual(candidate([-1, 1, -1, 1]),4); assert.deepEqual(candidate([-1, 1, 1, 1]),-4); assert.deepEqual(candidate([-1, 1, 1, 0]),0); } test();
humaneval-HumanEval_11_string_xor.json-L8
js
//Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> string_xor("010", "110") // "100" function string_xor(a, b){ var arrayA = []; var arrayB = [];
var result = ''; for (var i = 0; i < a.length; i++) { arrayA.push(parseInt(a[i])); } for (var j = 0; j < b.length; j++) { arrayB.push(parseInt(b[j])); } for (var k = 0; k < arrayA.length; k++) { if (arrayA[k] !== arrayB[k]) { arrayXOR.push(1); } else { arrayXOR.push(0); } } result = arrayXOR.join(''); return result; }
var arrayXOR = [];
const assert = require('node:assert'); function test() { let candidate = string_xor; assert.deepEqual(candidate("111000", "101010"),"010010"); assert.deepEqual(candidate("1", "1"),"0"); assert.deepEqual(candidate("0101", "0000"),"0101"); } test();
humaneval-HumanEval_120_maximum.json-L19
js
//Given an array arr of integers and a positive integer k, return a sorted array // of length k with the maximum k numbers in arr. // Example 1: // >>> maximum([-3, -4, 5], 3) // [-4, -3, 5] // Example 2: // >>> maximum([4, -4, 4], 2) // [4, 4] // Example 3: // >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1) // [2] // Note: // 1. The length of the array will be in the range of [1, 1000]. // 2. The elements in the array will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) function maximum(arr, k){ var len = arr.length; if(len === 0) return null;
return arr.sort((a, b) => a - b).slice(len - k); }
if(len === 1) return arr;
const assert = require('node:assert'); function test() { let candidate = maximum; assert.deepEqual(candidate([-3, -4, 5], 3),[-4, -3, 5]); assert.deepEqual(candidate([4, -4, 4], 2),[4, 4]); assert.deepEqual(candidate([-3, 2, 1, 2, -1, -2, 1], 1),[2]); assert.deepEqual(candidate([123, -123, 20, 0, 1, 2, -3], 3),[2, 20, 123]); assert.deepEqual(candidate([-123, 20, 0, 1, 2, -3], 4),[0, 1, 2, 20]); assert.deepEqual(candidate([5, 15, 0, 3, -13, -8, 0], 7),[-13, -8, 0, 0, 3, 5, 15]); assert.deepEqual(candidate([-1, 0, 2, 5, 3, -10], 2),[3, 5]); assert.deepEqual(candidate([1, 0, 5, -7], 1),[5]); assert.deepEqual(candidate([4, -4], 2),[-4, 4]); assert.deepEqual(candidate([-10, 10], 2),[-10, 10]); assert.deepEqual(candidate([1, 2, 3, -23, 243, -400, 0], 0),[]); } test();
humaneval-HumanEval_35_max_element.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 { // Return maximum element in the array list. // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (3l) // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))) // (123l) public static long maxElement(ArrayList<Long> l) {
for (int i = 0; i < l.size(); i += 1) { if (l.get(i) > max) { max = l.get(i); } } return max; } }
Long max = Long.MIN_VALUE;
} public static void main(String[] args) { assert(maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (3l)); assert(maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)124l, (long)1l, (long)-10l)))) == (124l)); } }
humaneval-HumanEval_52_below_threshold.json-L8
js
//Return true if all numbers in the array l are below threshold t. // >>> below_threshold([1, 2, 4, 10], 100) // true // >>> below_threshold([1, 20, 4, 10], 5) // false function below_threshold(l, t){ return l.every(x => x < t);
}
const assert = require('node:assert'); function test() { let candidate = below_threshold; assert.deepEqual(candidate([1, 2, 4, 10], 100),true); assert.deepEqual(candidate([1, 20, 4, 10], 5),false); assert.deepEqual(candidate([1, 20, 4, 10], 21),true); assert.deepEqual(candidate([1, 20, 4, 10], 22),true); assert.deepEqual(candidate([1, 8, 4, 10], 11),true); assert.deepEqual(candidate([1, 8, 4, 10], 10),false); } test();
humaneval-HumanEval_109_move_one_ball.json-L37
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // We have an array array list 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array array list will be randomly ordered. Your task is to determine if // it is possible to get an array array list sorted in non-decreasing order by performing // the following operation on the given array array list: // You are allowed to perform right shift operation any number of times. // One right shift operation means shifting all elements of the array array list by one // position in the right direction. The last element of the array array list will be moved to // the starting position in the array array list i.e. 0th index. // If it is possible to obtain the sorted array array list by performing the above operation // then return true else return false. // If the given array array list is empty then return true. // Note: The given array list is guaranteed to have unique elements. // For Example: // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) // (true) // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array array list. // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) // (false) // Explanation:It is not possible to get non-decreasing order for the given // array array list by performing any number of right shift operations. public static boolean moveOneBall(ArrayList<Long> arr) { if (arr.size() == 0) return true; ArrayList<Long> sorted = new ArrayList<Long>(arr); Collections.sort(sorted); for (int i = 0; i < arr.size(); i++) { ArrayList<Long> copy = new ArrayList<Long>(arr); long last = copy.remove(copy.size() - 1);
if (copy.equals(sorted)) return true; arr = copy; } return false; } }
copy.add(0, last);
} public static void main(String[] args) { assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)10l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList()))) == (true)); } }
humaneval-HumanEval_142_sum_squares.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 { // " // This function will take an array array list of integers. For all entries in the array list, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the array list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // Examples: // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)) // >>> lst // (long)new ArrayList<Long>(Arrays.asList()) // >>> lst // (long)new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)) public static long sumSquares(ArrayList<Long> lst) {
for (int i = 0; i < sz; i++) { if (i % 3 == 0) { lst.set(i, lst.get(i) * lst.get(i)); } else if (i % 4 == 0) { lst.set(i, lst.get(i) * lst.get(i) * lst.get(i)); } } long ans = 0; for (int i = 0; i < sz; i++) { ans += lst.get(i); } return ans; } }
int sz = lst.size();
} public static void main(String[] args) { assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (6l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)9l)))) == (14l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l, (long)1l)))) == (9l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l, (long)-1l)))) == (-3l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)0l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-5l, (long)2l, (long)-1l, (long)-5l)))) == (-126l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-56l, (long)-99l, (long)1l, (long)0l, (long)-2l)))) == (3030l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)-1l)))) == (0l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-16l, (long)-9l, (long)-2l, (long)36l, (long)36l, (long)26l, (long)-20l, (long)25l, (long)-40l, (long)20l, (long)-4l, (long)12l, (long)-26l, (long)35l, (long)37l)))) == (-14196l)); assert(sumSquares((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-3l, (long)17l, (long)-1l, (long)-15l, (long)13l, (long)-1l, (long)14l, (long)-14l, (long)-12l, (long)-5l, (long)14l, (long)-14l, (long)6l, (long)13l, (long)11l, (long)16l, (long)16l, (long)4l, (long)10l)))) == (-1448l)); } }
humaneval-HumanEval_35_max_element.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 maximum element in the array list. // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (3l) // >>> maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))) // (123l) public static long maxElement(ArrayList<Long> l) { Long max = Long.MIN_VALUE; for (int i = 0; i < l.size(); i += 1) { if (l.get(i) > max) { max = l.get(i);
} return max; } }
}
} public static void main(String[] args) { assert(maxElement((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) == (3l)); assert(maxElement((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)124l, (long)1l, (long)-10l)))) == (124l)); } }
humaneval-HumanEval_18_how_many_times.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Find how many times a given substring can be found in the original string. Count overlaping cases. // >>> howManyTimes((""), ("a")) // (0l) // >>> howManyTimes(("aaa"), ("a")) // (3l) // >>> howManyTimes(("aaaa"), ("aa")) // (3l) public static long howManyTimes(String string, String substring) { long count = 0; int index = 0; while (index != -1) {
if (index != -1) { index++; count++; } } return count; } }
index = string.indexOf(substring, index);
} public static void main(String[] args) { assert(howManyTimes((""), ("x")) == (0l)); assert(howManyTimes(("xyxyxyx"), ("x")) == (4l)); assert(howManyTimes(("cacacacac"), ("cac")) == (4l)); assert(howManyTimes(("john doe"), ("john")) == (1l)); } }
humaneval-HumanEval_162_string_to_md5.json-L15
py
from typing import Optional def string_to_md5(text: str) -> Optional[str]: """ Given a string 'text', return its md5 hash equivalent string. If 'text' is an empty string, return None. >>> string_to_md5('Hello world') '3e25960a79dbc69b674cd4ec67a72c62' """ import hashlib if not text: return None else:
return hashlib.md5(text.encode('utf-8')).hexdigest()
def check(candidate): assert candidate('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62' assert candidate('') == None assert candidate('A B C') == '0ef78513b0cb8cef12743f5aeb35f888' assert candidate('password') == '5f4dcc3b5aa765d61d8327deb882cf99' def test_check(): check(string_to_md5) test_check()
humaneval-HumanEval_109_move_one_ball.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 { // We have an array array list 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array array list will be randomly ordered. Your task is to determine if // it is possible to get an array array list sorted in non-decreasing order by performing // the following operation on the given array array list: // You are allowed to perform right shift operation any number of times. // One right shift operation means shifting all elements of the array array list by one // position in the right direction. The last element of the array array list will be moved to // the starting position in the array array list i.e. 0th index. // If it is possible to obtain the sorted array array list by performing the above operation // then return true else return false. // If the given array array list is empty then return true. // Note: The given array list is guaranteed to have unique elements. // For Example: // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) // (true) // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array array list. // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) // (false) // Explanation:It is not possible to get non-decreasing order for the given // array array list by performing any number of right shift operations. public static boolean moveOneBall(ArrayList<Long> arr) { if (arr.size() == 0) return true; ArrayList<Long> sorted = new ArrayList<Long>(arr); Collections.sort(sorted); for (int i = 0; i < arr.size(); i++) { ArrayList<Long> copy = new ArrayList<Long>(arr); long last = copy.remove(copy.size() - 1); copy.add(0, last);
arr = copy; } return false; } }
if (copy.equals(sorted)) return true;
} public static void main(String[] args) { assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)10l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList()))) == (true)); } }
humaneval-HumanEval_117_select_words.json-L37
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o':
break; default: consonants++; break; } } if (consonants == n) { ret.add(word); } } return ret; } }
case 'u':
} 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_6_parse_nested_parens.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parseNestedParens(("(()()) ((())) () ((())()())")) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))) public static ArrayList<Long> parseNestedParens(String paren_string) { ArrayList<Long> result = new ArrayList<Long>(); String[] paren_strings = paren_string.split(" "); for (String paren : paren_strings) { long max_depth = 0; long current_depth = 0; for (char c : paren.toCharArray()) { if (c == '(') { current_depth += 1; max_depth = Math.max(max_depth, current_depth);
current_depth -= 1; } } result.add(max_depth); } return result; } }
} else if (c == ')') {
} public static void main(String[] args) { assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))))); assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l))))); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L64
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 { // 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 array list of GPAs for some students and you have to write // a function that can output an array array 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: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) { letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-"); } else { letterGrades.add("E"); } } return letterGrades;
}
}
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_25_factorize.json-L17
js
//Return array of prime factors of given integer in the order from smallest to largest. // Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization. // Input number should be equal to the product of all factors // >>> factorize(8) // [2, 2, 2] // >>> factorize(25) // [5, 5] // >>> factorize(70) // [2, 5, 7] function factorize(n){ let factor = 2; let arr = []; while (n > 1) { if (n % factor == 0) { arr.push(factor); n = n / factor;
factor++; } } return arr; }
} else {
const assert = require('node:assert'); function test() { let candidate = factorize; assert.deepEqual(candidate(2),[2]); assert.deepEqual(candidate(4),[2, 2]); assert.deepEqual(candidate(8),[2, 2, 2]); assert.deepEqual(candidate(57),[3, 19]); assert.deepEqual(candidate(3249),[3, 3, 19, 19]); assert.deepEqual(candidate(185193),[3, 3, 3, 19, 19, 19]); assert.deepEqual(candidate(20577),[3, 19, 19, 19]); assert.deepEqual(candidate(18),[2, 3, 3]); } test();
humaneval-HumanEval_102_choose_num.json-L14
js
//This function takes two positive numbers x and y and returns the // biggest even integer number that is in the range [x, y] inclusive. If // there's no such number, then the function should return -1. // For example: // >>> choose_num(12, 15) // 14 // >>> choose_num(13, 12) // -1 function choose_num(x, y){ var num = -1; for(var i = x; i <= y; i++){ if(i % 2 == 0){ num = i;
} return num; }
}
const assert = require('node:assert'); function test() { let candidate = choose_num; assert.deepEqual(candidate(12, 15),14); assert.deepEqual(candidate(13, 12),-1); assert.deepEqual(candidate(33, 12354),12354); assert.deepEqual(candidate(5234, 5233),-1); assert.deepEqual(candidate(6, 29),28); assert.deepEqual(candidate(27, 10),-1); assert.deepEqual(candidate(7, 7),-1); assert.deepEqual(candidate(546, 546),546); } test();
humaneval-HumanEval_120_maximum.json-L17
js
//Given an array arr of integers and a positive integer k, return a sorted array // of length k with the maximum k numbers in arr. // Example 1: // >>> maximum([-3, -4, 5], 3) // [-4, -3, 5] // Example 2: // >>> maximum([4, -4, 4], 2) // [4, 4] // Example 3: // >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1) // [2] // Note: // 1. The length of the array will be in the range of [1, 1000]. // 2. The elements in the array will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) function maximum(arr, k){
if(len === 0) return null; if(len === 1) return arr; return arr.sort((a, b) => a - b).slice(len - k); }
var len = arr.length;
const assert = require('node:assert'); function test() { let candidate = maximum; assert.deepEqual(candidate([-3, -4, 5], 3),[-4, -3, 5]); assert.deepEqual(candidate([4, -4, 4], 2),[4, 4]); assert.deepEqual(candidate([-3, 2, 1, 2, -1, -2, 1], 1),[2]); assert.deepEqual(candidate([123, -123, 20, 0, 1, 2, -3], 3),[2, 20, 123]); assert.deepEqual(candidate([-123, 20, 0, 1, 2, -3], 4),[0, 1, 2, 20]); assert.deepEqual(candidate([5, 15, 0, 3, -13, -8, 0], 7),[-13, -8, 0, 0, 3, 5, 15]); assert.deepEqual(candidate([-1, 0, 2, 5, 3, -10], 2),[3, 5]); assert.deepEqual(candidate([1, 0, 5, -7], 1),[5]); assert.deepEqual(candidate([4, -4], 2),[-4, 4]); assert.deepEqual(candidate([-10, 10], 2),[-10, 10]); assert.deepEqual(candidate([1, 2, 3, -23, 243, -400, 0], 0),[]); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L23
py
def is_multiply_prime(a: int) -> bool: """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: >>> is_multiply_prime(30) True 30 = 2 * 3 * 5 """ n = a d = 2 prime_factors = [] while d * d <= n: if n % d == 0: prime_factors.append(d) n //= d else: d += 1 if n > 1: prime_factors.append(n) if len(prime_factors) == 3: return True
return False
else:
def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(105) == True assert candidate(126) == False assert candidate(729) == False assert candidate(891) == False assert candidate(1001) == True def test_check(): check(is_multiply_prime) test_check()
humaneval-HumanEval_61_correct_bracketing.json-L22
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else {
} } } if (opens.length == 0){ return true; } else { return false; } }
return false;
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') {
temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } } return output; } }
if (open_paren == 0) {
} public static void main(String[] args) { assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())"))))); assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))"))))); assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))"))))); assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))))); } }
humaneval-HumanEval_118_get_closest_vowel.json-L19
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 = [];
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]; } } }
if (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_147_get_max_triples.json-L18
js
//You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> get_max_triples(5) // 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). function get_max_triples(n){ let result = 0; let arr = []; for(let i = 1; i<=n; i++){ arr.push(i*i-i+1); } for(let i = 0; i<arr.length; i++){
for(let k = j+1; k<arr.length; k++){ if((arr[i]+arr[j]+arr[k])%3 === 0){ result++; } } } } return result; }
for(let j = i+1; j<arr.length; j++){
const assert = require('node:assert'); function test() { let candidate = get_max_triples; assert.deepEqual(candidate(5),1); assert.deepEqual(candidate(6),4); assert.deepEqual(candidate(10),36); assert.deepEqual(candidate(100),53361); } test();
humaneval-HumanEval_95_check_dict_case.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 hash map, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given hash map is empty. // Examples: // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "b", "banana")))) // (true) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "A", "banana", "B", "banana")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", 8l, "banana", "a", "apple")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) // (true) public static boolean checkDictCase(HashMap<String,String> dict) { if (dict.isEmpty()) { return false; } boolean allLowerCase = dict.keySet().stream().allMatch(k -> k.matches("^[a-z]+$")); boolean allUpperCase = dict.keySet().stream().allMatch(k -> k.matches("^[A-Z]+$")); return allLowerCase || allUpperCase; }
}
} public static void main(String[] args) { assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "b", "banana")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "A", "banana", "B", "banana")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "5", "banana", "a", "apple")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("fruit", "Orange", "taste", "Sweet")))) == (true)); assert(checkDictCase((new HashMap<String,String>())) == (false)); } }
humaneval-HumanEval_78_hex_key.json-L27
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++){
result += 1; } } return result; }
if(primes.includes(num[x])){
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_24_largest_divisor.json-L9
js
//For a given number n, find the largest number that divides n evenly, smaller than n // >>> largest_divisor(15) // 5 function largest_divisor(n){ let ld = 0; for(i=1; i<n; i++){ if(n%i===0){ if(i>ld){
} } } return ld; }
ld = i;
const assert = require('node:assert'); function test() { let candidate = largest_divisor; assert.deepEqual(candidate(3),1); assert.deepEqual(candidate(7),1); assert.deepEqual(candidate(10),5); assert.deepEqual(candidate(100),50); assert.deepEqual(candidate(49),7); } test();
humaneval-HumanEval_74_total_match.json-L22
py
from typing import List def total_match(lst1: List[str], lst2: List[str]) -> List[str]: """ Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples >>> 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'] """
count2 = sum([len(s) for s in lst2]) if count1 == count2: return lst1 if count1 < count2: return lst1 return lst2
count1 = sum([len(s) for s in lst1])
def check(candidate): assert candidate([], []) == [] assert candidate(['hi', 'admin'], ['hi', 'hi']) == ['hi', 'hi'] assert candidate(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) == ['hi', 'admin'] assert candidate(['4'], ['1', '2', '3', '4', '5']) == ['4'] assert candidate(['hi', 'admin'], ['hI', 'Hi']) == ['hI', 'Hi'] assert candidate(['hi', 'admin'], ['hI', 'hi', 'hi']) == ['hI', 'hi', 'hi'] assert candidate(['hi', 'admin'], ['hI', 'hi', 'hii']) == ['hi', 'admin'] assert candidate([], ['this']) == [] assert candidate(['this'], []) == [] def test_check(): check(total_match) test_check()
humaneval-HumanEval_106_f.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 { // Implement the function f that takes n as a parameter, // and returns an array array list of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))) public static ArrayList<Long> f(long n) { ArrayList<Long> ret = new ArrayList<Long>(); for (long i = 1l; i <= n; i++) { long v = 0l; if (i % 2 == 0) { v = 1l; for (long j = 2l; j <= i; j++) { v *= j; } } else { v = (i * (i + 1l)) / 2l; } ret.add(v);
return ret; } }
}
} public static void main(String[] args) { assert(f((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))))); assert(f((7l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l, (long)720l, (long)28l))))); assert(f((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); assert(f((3l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l))))); } }
humaneval-HumanEval_3_below_zero.json-L12
py
from typing import List def below_zero(operations: List[int]) -> bool: """ You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """
for operation in operations: balance += operation if balance < 0: return True return False print(below_zero([1, 2, 3])) print(below_zero([1, 2, -4, 5]))
balance = 0
def check(candidate): assert candidate([]) == False assert candidate([1, 2, -3, 1, 2, -3]) == False assert candidate([1, 2, -4, 5, 6]) == True assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True def test_check(): check(below_zero) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L57
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 array list of GPAs for some students and you have to write // a function that can output an array array 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: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) { letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D");
letterGrades.add("D-"); } else { letterGrades.add("E"); } } return letterGrades; } }
} else if (currentGrade > 0.0f) {
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_68_pluck.json-L43
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given an array array list representing a branch of a tree that has non-negative integer nodes // your task is to pluck one of the nodes and return it. // The plucked node should be the node with the smallest even value. // If multiple nodes with the same smallest even value are found return the node that has smallest index. // The plucked node should be returned in an array array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // Explanation: 0 is the smallest value, but there are two zeros, // so we will choose the first zero, which has the smallest index. // Constraints: // * 1 <= nodes.length <= 10000 // * 0 <= node.value public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i; minValue = arr.get(i); }
} ArrayList<Long> newArr = new ArrayList<Long>(); if (minIndex == -1) { return newArr; } newArr.add(minValue); newArr.add((long)minIndex); return newArr; } }
}
} 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_94_skjkasdkd.json-L22
js
//You are given an array of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) // 10 // >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) // 25 // >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) // 13 // >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) // 11 // >>> skjkasdkd([0, 81, 12, 3, 1, 21]) // 3 // >>> skjkasdkd([0, 8, 1, 2, 1, 7]) // 7 function skjkasdkd(lst){ function prime(n){ if (n<2) return false; for (let i=2; i<=Math.sqrt(n); i++){ if (n%i==0) return false; }
} let max = Math.max(...lst.filter(x=>prime(x))); let digits = String(max).split(''); let sum = 0; for (let i=0; i<digits.length; i++){ sum += Number(digits[i]); } return sum; }
return true;
const assert = require('node:assert'); function test() { let candidate = skjkasdkd; assert.deepEqual(candidate([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]),10); assert.deepEqual(candidate([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]),25); assert.deepEqual(candidate([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]),13); assert.deepEqual(candidate([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]),11); assert.deepEqual(candidate([0, 81, 12, 3, 1, 21]),3); assert.deepEqual(candidate([0, 8, 1, 2, 1, 7]),7); assert.deepEqual(candidate([8191]),19); assert.deepEqual(candidate([8191, 123456, 127, 7]),19); assert.deepEqual(candidate([127, 97, 8192]),10); } test();
humaneval-HumanEval_126_is_sorted.json-L65
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of numbers, return whether or not they are sorted // in ascending order. If array list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) // (false) public static boolean isSorted(ArrayList<Long> lst) { if (lst.size() == 0) { return true; } else { int running_max = 0; int previous_number = 0; boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue(); } else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } }
} } }
return true;
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_126_is_sorted.json-L33
js
//Given an array of numbers, return whether or not they are sorted // in ascending order. If array has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> is_sorted([5]) // true // >>> is_sorted([1, 2, 3, 4, 5]) // true // >>> is_sorted([1, 3, 2, 4, 5]) // false // >>> is_sorted([1, 2, 3, 4, 5, 6]) // true // >>> is_sorted([1, 2, 3, 4, 5, 6, 7]) // true // >>> is_sorted([1, 3, 2, 4, 5, 6, 7]) // false // >>> is_sorted([1, 2, 2, 3, 3, 4]) // true // >>> is_sorted([1, 2, 2, 2, 3, 4]) // false function is_sorted(lst){ var last = null; var dupe_found = false; for (var x of lst){ if (last == null){ last = x; } else if (x < last){ return false; } else if (x == last){ if (dupe_found){ return false; } else {
} } else { last = x; dupe_found = false; } } return true; }
dupe_found = true;
const assert = require('node:assert'); function test() { let candidate = is_sorted; assert.deepEqual(candidate([5]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, 7]),false); assert.deepEqual(candidate([]),true); assert.deepEqual(candidate([1]),true); assert.deepEqual(candidate([3, 2, 1]),false); assert.deepEqual(candidate([1, 2, 2, 2, 3, 4]),false); assert.deepEqual(candidate([1, 2, 3, 3, 3, 4]),false); assert.deepEqual(candidate([1, 2, 2, 3, 3, 4]),true); assert.deepEqual(candidate([1, 2, 3, 4]),true); } test();
humaneval-HumanEval_150_x_or_y.json-L12
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; }
if(n%i==0){ return y; } } return x; }
for(var i=2; i<n; i++){
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_93_encode.json-L26
py
def encode(message: str) -> str: """ Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' """ def swap_case(ch: str) -> str: if ch.isupper(): return ch.lower() else: return ch.upper() def encode_vowel(ch: str) -> str: if ch.lower() in 'aeiou': if ch.lower() in 'wxyz': return ch.lower() return chr(ord(ch) + 2) return ch
return ''.join(map(lambda ch: encode_vowel(swap_case(ch)), message))
def check(candidate): assert candidate('TEST') == 'tgst' assert candidate('Mudasir') == 'mWDCSKR' assert candidate('YES') == 'ygs' assert candidate('This is a message') == 'tHKS KS C MGSSCGG' assert candidate('I DoNt KnOw WhAt tO WrItE') == 'k dQnT kNqW wHcT Tq wRkTg' def test_check(): check(encode) test_check()
humaneval-HumanEval_105_by_length.json-L15
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 = [];
var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
for(var i = 0; i < arr.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_111_histogram.json-L26
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{
} } console.log(count); var max = 0; var result = {}; for (var key in count){ if (count[key] > max){ max = count[key]; result = {}; result[key] = max; } else if (count[key] === max){ result[key] = max; } } return result; }
count[lst[i]] = 1;
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_158_find_max.json-L14
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = "";
var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
for(var i = 0; i < words.length; i++){
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_156_int_to_mini_roman.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 { // 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; }
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; } }
if (num >= 50) {
} 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"))); } }