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_107_even_odd_palindrome.json-L24
js
//Given a positive integer n, return an array that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // Example 1: // >>> even_odd_palindrome(3) // [1, 2] // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // Example 2: // >>> even_odd_palindrome(12) // [4, 6] // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // Note: // 1. 1 <= n <= 10^3 // 2. returned array has the number of even and odd integer palindromes respectively. function even_odd_palindrome(n){ var pal = []; var isPalindrome = function(x){ var y = x.toString().split('').reverse().join(''); return y == x; } for(var i = 1; i <= n; i++){ if(isPalindrome(i)){
} } var odd = 0; var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){ even++; } else{ odd++; } } return [even, odd]; }
pal.push(i);
const assert = require('node:assert'); function test() { let candidate = even_odd_palindrome; assert.deepEqual(candidate(123),[8, 13]); assert.deepEqual(candidate(12),[4, 6]); assert.deepEqual(candidate(3),[1, 2]); assert.deepEqual(candidate(63),[6, 8]); assert.deepEqual(candidate(25),[5, 6]); assert.deepEqual(candidate(19),[4, 6]); assert.deepEqual(candidate(9),[4, 5]); assert.deepEqual(candidate(1),[0, 1]); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L12
js
//Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separate_paren_groups("( ) (( )) (( )( ))") // ["()", "(())", "(()())"] function separate_paren_groups(paren_string){ var count = 0; var group = ''; var groups = []; for (var i = 0; i < paren_string.length; i++){
count++; group += paren_string[i]; } else if (paren_string[i] === ')'){ count--; group += paren_string[i]; } if (count === 0 && group){ groups.push(group); group = ''; } } return groups; }
if (paren_string[i] === '('){
const assert = require('node:assert'); function test() { let candidate = separate_paren_groups; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]); assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]); assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]); assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]); } test();
humaneval-HumanEval_95_check_dict_case.json-L24
py
from typing import Dict def check_dict_case(dict: Dict[str, str]) -> bool: """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: >>> check_dict_case({ 'a': 'apple', 'b': 'banana' }) True >>> check_dict_case({ 'a': 'apple', 'A': 'banana', 'B': 'banana' }) False >>> check_dict_case({ 'a': 'apple', 8: 'banana', 'a': 'apple' }) False >>> check_dict_case({ 'Name': 'John', 'Age': '36', 'City': 'Houston' }) False >>> check_dict_case({ 'STATE': 'NC', 'ZIP': '12345' }) True """ if len(dict) == 0: return False if any(not isinstance(x, str) for x in dict.keys()): return False
if any(not x.isupper() for x in dict.keys()): return False return True
if any(not x.islower() for x in dict.keys()):
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_139_special_factorial.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // For example: // >>> specialFactorial((4l)) // (288l) // The function will receive an integer as input and should return the special // factorial of this integer. public static long specialFactorial(long n) { long result = 1; while (n > 0) { long local_result = 1; long temp = n; while (temp > 0) {
temp--; } result *= local_result; n--; } return result; } }
local_result *= temp;
} public static void main(String[] args) { assert(specialFactorial((4l)) == (288l)); assert(specialFactorial((5l)) == (34560l)); assert(specialFactorial((7l)) == (125411328000l)); assert(specialFactorial((1l)) == (1l)); } }
humaneval-HumanEval_104_unique_digits.json-L29
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of positive integers x. return a sorted array list of all // elements that hasn't any even digit. // Note: Returned array list should be sorted in increasing order. // For example: // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))) // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> uniqueDigits(ArrayList<Long> x) { ArrayList<Long> b = new ArrayList<Long>(); for (int i = 0; i < x.size(); i++) { if (x.get(i) < 0) { x.set(i, x.get(i)*(long)-1); } boolean unique = true; long z = x.get(i); while (z > 0) { long y = z % 10; if (y % 2 == 0) { unique = false;
} z = z / 10; } if (unique) { b.add(x.get(i)); } } Collections.sort(b); return b; } }
break;
} public static void main(String[] args) { assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)12345l, (long)2033l, (long)111l, (long)151l)))).equals((new ArrayList<Long>(Arrays.asList((long)111l, (long)151l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)135l, (long)103l, (long)31l)))).equals((new ArrayList<Long>(Arrays.asList((long)31l, (long)135l))))); } }
humaneval-HumanEval_4_mean_absolute_deviation.json-L12
js
//For a given array of input numbers, calculate Mean Absolute Deviation // around the mean of this dataset. // Mean Absolute Deviation is the average absolute difference between each // element and a centerpoint (mean in this case): // MAD = average | x - x_mean | // >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) // 1.0 function mean_absolute_deviation(numbers){ var sum = 0; for(var i = 0; i < numbers.length; i++){ sum += numbers[i];
var mean = sum / numbers.length; var sum_abs_diff = 0; for(var i = 0; i < numbers.length; i++){ sum_abs_diff += Math.abs(numbers[i] - mean); } return sum_abs_diff / numbers.length; }
}
const assert = require('node:assert'); function test() { let candidate = mean_absolute_deviation; assert.deepEqual(candidate([1.0, 2.0]),0.5); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0]),1.0); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0]),1.2); } test();
humaneval-HumanEval_156_int_to_mini_roman.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 a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100;
if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
}
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_124_valid_date.json-L35
py
def valid_date(date: str) -> bool: """You have to write a function which validates a given date string and returns True if the date is valid otherwise False. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy >>> valid_date('03-11-2000') True >>> valid_date('15-01-2012') False >>> valid_date('04-0-2040') False >>> valid_date('06-04-2020') True >>> valid_date('06/04/2020') False """ if not date: return False days_per_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] date_list = [int(d) for d in date.split('-')] if len(date_list) != 3: return False if date_list[0] < 1 or date_list[0] > 12: return False if date_list[1] < 1 or date_list[1] > days_per_month[date_list[0] - 1]: return False
return False return True
if len(str(date_list[2])) != 4:
def check(candidate): assert candidate('03-11-2000') == True assert candidate('15-01-2012') == False assert candidate('04-0-2040') == False assert candidate('06-04-2020') == True assert candidate('01-01-2007') == True assert candidate('03-32-2011') == False assert candidate('') == False assert candidate('04-31-3000') == False assert candidate('06-06-2005') == True assert candidate('21-31-2000') == False assert candidate('04-12-2003') == True assert candidate('04122003') == False assert candidate('20030412') == False assert candidate('2003-04') == False assert candidate('2003-04-12') == False assert candidate('04-2003') == False def test_check(): check(valid_date) test_check()
humaneval-HumanEval_57_monotonic.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 true is array list elements are monotonically increasing or decreasing. // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l)))) // (true) // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l)))) // (false) // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l)))) // (true) public static boolean monotonic(ArrayList<Long> l) { long a = l.get(0); boolean inc = true; boolean dec = true; for (int i = 1; i < l.size(); i++) { if (l.get(i) < a) { inc = false;
if (l.get(i) > a) { dec = false; } a = l.get(i); } return inc || dec; } }
}
} public static void main(String[] args) { assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l)))) == (false)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)5l, (long)60l)))) == (false)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)60l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)9l, (long)9l, (long)9l, (long)9l)))) == (true)); } }
humaneval-HumanEval_117_select_words.json-L45
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) {
} } return ret; } }
ret.add(word);
} 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_37_sort_even.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the odd indicies, while its values at the even indicies are equal // to the values of the even indicies of l, but sorted. // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>(); ArrayList<Long> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } index++; } Collections.sort(evenIndexed); index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else {
} index++; } return res; } }
res.add(num);
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_92_any_int.json-L23
py
def any_int(x: float, y: float, z: float) -> bool: """ Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples >>> any_int(5, 2, 7) True >>> any_int(3, 2, 2) False >>> any_int(3, -2, 1) True >>> any_int(3.6, -2.2, 2) False """
return all([type(x) is int, type(y) is int, type(z) is int]) and (x == y + z or y == x + z or z == x + y)
def check(candidate): assert candidate(2, 3, 1) == True assert candidate(2.5, 2, 3) == False assert candidate(1.5, 5, 3.5) == False assert candidate(2, 6, 2) == False assert candidate(4, 2, 2) == True assert candidate(2.2, 2.2, 2.2) == False assert candidate(-4, 6, 2) == True assert candidate(2, 1, 1) == True assert candidate(3, 4, 7) == True assert candidate(3.0, 4, 7) == False def test_check(): check(any_int) test_check()
humaneval-HumanEval_1_separate_paren_groups.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string 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 (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } } return output; } }
if (c == '(') {
} 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_104_unique_digits.json-L21
py
from typing import List def unique_digits(x: List[int]) -> List[int]: """Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing order. For example: >>> unique_digits([15, 33, 1422, 1]) [1, 15, 33] >>> unique_digits([152, 323, 1422, 10]) [] """ s=[] for i in x: temp=i while temp: if temp%2==0: s.append(i)
temp=temp//10 for i in s: x.remove(i) return sorted(x)
break
def check(candidate): assert candidate([15, 33, 1422, 1]) == [1, 15, 33] assert candidate([152, 323, 1422, 10]) == [] assert candidate([12345, 2033, 111, 151]) == [111, 151] assert candidate([135, 103, 31]) == [31, 135] def test_check(): check(unique_digits) test_check()
humaneval-HumanEval_35_max_element.json-L14
py
from typing import List def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ max_elem = l[0] for i in range(1, len(l)): if l[i] > max_elem: max_elem = l[i]
return max_elem
def check(candidate): assert candidate([1, 2, 3]) == 3 assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124 def test_check(): check(max_element) test_check()
humaneval-HumanEval_147_get_max_triples.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 { // You are given a positive integer n. You have to create an integer array array list a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { arrayList.add(i * i - i + 1); } for (int i = 0; i < arrayList.size(); i++) {
for (int k = j + 1; k < arrayList.size(); k++) { if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { count++; } } } } return count; } }
for (int j = i + 1; j < arrayList.size(); j++) {
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_143_words_in_sentence.json-L22
py
def words_in_sentence(sentence: str) -> str: """ 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 """ def is_prime(n: int) -> bool:
return False for i in range(2, n): if n % i == 0: return False return True words = sentence.split() prime_words = [] for word in words: if is_prime(len(word)): prime_words.append(word) return ' '.join(prime_words)
if n <= 1:
def check(candidate): assert candidate('This is a test') == 'is' assert candidate('lets go for swimming') == 'go for' assert candidate('there is no place available here') == 'there is no place' assert candidate('Hi I am Hussein') == 'Hi am Hussein' assert candidate('go for it') == 'go for it' assert candidate('here') == '' assert candidate('here is') == 'is' def test_check(): check(words_in_sentence) test_check()
humaneval-HumanEval_24_largest_divisor.json-L9
py
def largest_divisor(n: int) -> int: """ For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """ divisor = n - 1 while n % divisor != 0: divisor -= 1
return divisor
def check(candidate): assert candidate(3) == 1 assert candidate(7) == 1 assert candidate(10) == 5 assert candidate(100) == 50 assert candidate(49) == 7 def test_check(): check(largest_divisor) test_check()
humaneval-HumanEval_5_intersperse.json-L7
js
//Insert a number 'delimeter' between every two consecutive elements of input array `numbers' // >>> intersperse([], 4) // [] // >>> intersperse([1, 2, 3], 4) // [1, 4, 2, 4, 3] function intersperse(numbers, delimeter){
for(var i = 0; i < numbers.length; i++){ result.push(numbers[i]); if(i !== numbers.length - 1){ result.push(delimeter); } } return result; }
var result = [];
const assert = require('node:assert'); function test() { let candidate = intersperse; assert.deepEqual(candidate([], 7),[]); assert.deepEqual(candidate([5, 6, 3, 2], 8),[5, 8, 6, 8, 3, 8, 2]); assert.deepEqual(candidate([2, 2, 2], 2),[2, 2, 2, 2, 2]); } test();
humaneval-HumanEval_126_is_sorted.json-L62
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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_158_find_max.json-L19
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j];
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; }
if(unique_word[char] === undefined){
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_0_has_close_elements.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 { // Check if in given array list of numbers, are any two numbers closer to each other than // given threshold. // >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f))), (0.5f)) // (false) // >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.8f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.3f)) // (true) public static boolean hasCloseElements(ArrayList<Float> numbers, float threshold) { Collections.sort(numbers); for (int i = 0; i < numbers.size() - 1; i++) { if (numbers.get(i+1) - numbers.get(i) < threshold) { return true; }
return false; } }
}
} public static void main(String[] args) { assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.3f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.05f)) == (false)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.95f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.8f)) == (false)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.1f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (1.0f)) == (true)); assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (0.5f)) == (false)); } }
humaneval-HumanEval_19_sort_numbers.json-L13
py
def sort_numbers(numbers: str) -> str: """ Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five' """ words = numbers.split() res = '' mapper = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} for word in sorted(words, key=lambda x: mapper[x]): res += ' ' + word
return res.strip()
def check(candidate): assert candidate('') == '' assert candidate('three') == 'three' assert candidate('three five nine') == 'three five nine' assert candidate('five zero four seven nine eight') == 'zero four five seven eight nine' assert candidate('six five four three two one zero') == 'zero one two three four five six' def test_check(): check(sort_numbers) test_check()
humaneval-HumanEval_43_pairs_sum_to_zero.json-L15
js
//pairs_sum_to_zero takes an array of integers as an input. // it returns true if there are two distinct elements in the array that // sum to zero, and false otherwise. // >>> pairs_sum_to_zero([1, 3, 5, 0]) // false // >>> pairs_sum_to_zero([1, 3, -2, 1]) // false // >>> pairs_sum_to_zero([1, 2, 3, 7]) // false // >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) // true // >>> pairs_sum_to_zero([1]) // false function pairs_sum_to_zero(l){
while (i < l.length){ var j = i+1 while (j < l.length){ if ((l[i] + l[j]) === 0){ return true } j = j + 1 } i = i + 1 } return false }
var i = 0
const assert = require('node:assert'); function test() { let candidate = pairs_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, -2, 1]),false); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 5, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([-3, 9, -1, 3, 2, 30]),true); assert.deepEqual(candidate([-3, 9, -1, 3, 2, 31]),true); assert.deepEqual(candidate([-3, 9, -1, 4, 2, 30]),false); assert.deepEqual(candidate([-3, 9, -1, 4, 2, 31]),false); } test();
humaneval-HumanEval_24_largest_divisor.json-L14
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 { // For a given number n, find the largest number that divides n evenly, smaller than n // >>> largestDivisor((15l)) // (5l) public static long largestDivisor(long n) { for (long i = 2; i <= Math.floor(Math.sqrt(n)); i++) {
return n / i; } } return 1; } }
if (n % i == 0) {
} public static void main(String[] args) { assert(largestDivisor((3l)) == (1l)); assert(largestDivisor((7l)) == (1l)); assert(largestDivisor((10l)) == (5l)); assert(largestDivisor((100l)) == (50l)); assert(largestDivisor((49l)) == (7l)); } }
humaneval-HumanEval_51_remove_vowels.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 { // remove_vowels is a function that takes string and returns string without vowels. // >>> removeVowels(("")) // ("") // >>> removeVowels(("abcdef")) // ("bcdf") // >>> removeVowels(("aaaaa")) // ("") // >>> removeVowels(("aaBAA")) // ("B") // >>> removeVowels(("zbcd")) // ("zbcd") public static String removeVowels(String text) { String vowels = "aeiouAEIOU"; String newText = ""; for (int i = 0; i < text.length(); i++) { if (vowels.indexOf(text.charAt(i)) == -1) { newText += text.charAt(i);
} return newText; } }
}
} public static void main(String[] args) { assert(removeVowels(("")).equals((""))); assert(removeVowels(("abcdef\nghijklm")).equals(("bcdf\nghjklm"))); assert(removeVowels(("fedcba")).equals(("fdcb"))); assert(removeVowels(("eeeee")).equals((""))); assert(removeVowels(("acBAA")).equals(("cB"))); assert(removeVowels(("EcBOO")).equals(("cB"))); assert(removeVowels(("ybcd")).equals(("ybcd"))); } }
humaneval-HumanEval_155_even_odd_count.json-L12
js
//Given an integer. return an array that has the number of even and odd digits respectively. // Example: // >>> even_odd_count(-12) // [1, 1] // >>> even_odd_count(123) // [1, 2] function even_odd_count(num){ num = Math.abs(num); var evens = 0; var odds = 0; for(var i = 0; i < num.toString().length; i++){
evens ++; } else{ odds ++; } } return [evens, odds]; }
if(num.toString()[i] % 2 == 0){
const assert = require('node:assert'); function test() { let candidate = even_odd_count; assert.deepEqual(candidate(7),[0, 1]); assert.deepEqual(candidate(-78),[1, 1]); assert.deepEqual(candidate(3452),[2, 2]); assert.deepEqual(candidate(346211),[3, 3]); assert.deepEqual(candidate(-345821),[3, 3]); assert.deepEqual(candidate(-2),[1, 0]); assert.deepEqual(candidate(-45347),[2, 3]); assert.deepEqual(candidate(0),[1, 0]); } test();
humaneval-HumanEval_108_count_nums.json-L29
py
from typing import List def count_nums(arr: List[int]) -> int: """ Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums([]) 0 >>> count_nums([-1, 11, -11]) 1 >>> count_nums([1, 1, 2]) 3 """ n = 0 for i in arr: if i < 0: i = abs(i) s = -1 * int(str(i)[0]) for j in str(i)[1:]: s += int(j) else: s = 0 for j in str(i): s += int(j) if s > 0: n += 1
return n
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_157_right_angle_triangle.json-L14
js
//Given the lengths of the three sides of a triangle. Return true if the three // sides form a right-angled triangle, false otherwise. // A right-angled triangle is a triangle in which one angle is right angle or // 90 degree. // Example: // >>> right_angle_triangle(3, 4, 5) // true // >>> right_angle_triangle(1, 2, 3) // false function right_angle_triangle(a, b, c){ if(a**2 + b**2 == c**2 || b**2 + c**2 == a**2 || a**2 + c**2 == b**2) { return true; } else {
} }
return false;
const assert = require('node:assert'); function test() { let candidate = right_angle_triangle; assert.deepEqual(candidate(3, 4, 5),true); assert.deepEqual(candidate(1, 2, 3),false); assert.deepEqual(candidate(10, 6, 8),true); assert.deepEqual(candidate(2, 2, 2),false); assert.deepEqual(candidate(7, 24, 25),true); assert.deepEqual(candidate(10, 5, 7),false); assert.deepEqual(candidate(5, 12, 13),true); assert.deepEqual(candidate(15, 8, 17),true); assert.deepEqual(candidate(48, 55, 73),true); assert.deepEqual(candidate(1, 1, 1),false); assert.deepEqual(candidate(2, 2, 10),false); } test();
humaneval-HumanEval_20_find_closest_elements.json-L23
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp:
temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
if numbers[i] > numbers[j]:
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_125_split_words.json-L28
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); } else if(txt.includes(',')){ return txt.split(','); } else{ let count = 0; for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){ if(txt[i] == txt[i].toLowerCase()){ count++; } } } return count;
}
}
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_41_car_race_collision.json-L17
js
//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. function car_race_collision(n){ let num_collisions = 0; let left_to_right = Array(n).fill(1); let right_to_left = Array(n).fill(1); for (let i = 0; i < left_to_right.length; i++) { for (let j = 0; j < right_to_left.length; j++) { if (left_to_right[i] == right_to_left[j]) { num_collisions++;
} } return num_collisions; }
}
const assert = require('node:assert'); function test() { let candidate = car_race_collision; assert.deepEqual(candidate(2),4); assert.deepEqual(candidate(3),9); assert.deepEqual(candidate(4),16); assert.deepEqual(candidate(8),64); assert.deepEqual(candidate(10),100); } test();
humaneval-HumanEval_14_all_prefixes.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return array list of all prefixes from shortest to longest of the input string // >>> allPrefixes(("abc")) // (new ArrayList<String>(Arrays.asList((String)"a", (String)"ab", (String)"abc"))) public static ArrayList<String> allPrefixes(String string) { ArrayList<String> result = new ArrayList<String>(); for (int i = 0; i < string.length(); i++) { result.add(string.substring(0, i + 1));
return result; } }
}
} public static void main(String[] args) { assert(allPrefixes(("")).equals((new ArrayList<String>(Arrays.asList())))); assert(allPrefixes(("asdfgh")).equals((new ArrayList<String>(Arrays.asList((String)"a", (String)"as", (String)"asd", (String)"asdf", (String)"asdfg", (String)"asdfgh"))))); assert(allPrefixes(("WWW")).equals((new ArrayList<String>(Arrays.asList((String)"W", (String)"WW", (String)"WWW"))))); } }
humaneval-HumanEval_20_find_closest_elements.json-L29
py
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1]) temp_index, temp2_index = 0, 1 if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index]
temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
else:
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_75_is_multiply_prime.json-L33
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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: // >>> isMultiplyPrime((30l)) // (true) // 30 = 2 * 3 * 5 public static boolean isMultiplyPrime(long a) { if (a == 1) { return false; } if (a == 2) { return true; } long copyOfInput = a; ArrayList<Long> arr = new ArrayList<Long>(); while (a % 2 == 0) { arr.add(2l); a /= 2; } for (long i = 3; i <= Math.sqrt(a); i += 2) { while (a % i == 0) { arr.add(i); a /= i;
} if (a > 2) { arr.add(a); } return arr.size() == 3; } }
}
} public static void main(String[] args) { assert(isMultiplyPrime((5l)) == (false)); assert(isMultiplyPrime((30l)) == (true)); assert(isMultiplyPrime((8l)) == (true)); assert(isMultiplyPrime((10l)) == (false)); assert(isMultiplyPrime((125l)) == (true)); assert(isMultiplyPrime((105l)) == (true)); assert(isMultiplyPrime((126l)) == (false)); assert(isMultiplyPrime((729l)) == (false)); assert(isMultiplyPrime((891l)) == (false)); assert(isMultiplyPrime((1001l)) == (true)); } }
humaneval-HumanEval_39_prime_fib.json-L37
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_158_find_max.json-L37
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } 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; }
}
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_12_longest.json-L13
py
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) None >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """
return None else: long = strings[0] for s in strings: if len(s) > len(long): long = s return long
if not strings:
def check(candidate): assert candidate([]) == None assert candidate(['x', 'y', 'z']) == 'x' assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz' def test_check(): check(longest) test_check()
humaneval-HumanEval_153_Strongest_Extension.json-L24
js
//You will be given the name of a class (a string) and an array of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array. // For example, if you are given "Slices" as the class and an array of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> Strongest_Extension("my_class", ["AA", "Be", "CC"]) // "my_class.AA" function Strongest_Extension(class_name, extensions){ var output = class_name + "."; var min_strength = 1; for (var i = 0; i < extensions.length; i++) { var strength = -1*(extensions[i].replace(/[^A-Z]/g, "").length - extensions[i].replace(/[^a-z]/g, "").length); if (strength < min_strength) { min_strength = strength;
} } return output; }
output = class_name + "." + extensions[i];
const assert = require('node:assert'); function test() { let candidate = Strongest_Extension; assert.deepEqual(candidate("Watashi", ["tEN", "niNE", "eIGHt8OKe"]),"Watashi.eIGHt8OKe"); assert.deepEqual(candidate("Boku123", ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]),"Boku123.YEs.WeCaNe"); assert.deepEqual(candidate("__YESIMHERE", ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]),"__YESIMHERE.NuLl__"); assert.deepEqual(candidate("K", ["Ta", "TAR", "t234An", "cosSo"]),"K.TAR"); assert.deepEqual(candidate("__HAHA", ["Tab", "123", "781345", "-_-"]),"__HAHA.123"); assert.deepEqual(candidate("YameRore", ["HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"]),"YameRore.okIWILL123"); assert.deepEqual(candidate("finNNalLLly", ["Die", "NowW", "Wow", "WoW"]),"finNNalLLly.WoW"); assert.deepEqual(candidate("_", ["Bb", "91245"]),"_.Bb"); assert.deepEqual(candidate("Sp", ["671235", "Bb"]),"Sp.671235"); } test();
humaneval-HumanEval_88_sort_array.json-L24
js
//Given an array of non-negative integers, return a cojs of the given array after sorting, // you will sort the given array in ascending order if the sum( first index value, last index value) is odd, // or sort it in descending order if the sum( first index value, last index value) is even. // Note: // * don't change the given array. // Examples: // >>> sort_array([]) // [] // >>> sort_array([5]) // [5] // >>> sort_array([2, 4, 3, 0, 1, 5]) // [0, 1, 2, 3, 4, 5] // >>> sort_array([2, 4, 3, 0, 1, 5, 6]) // [6, 5, 4, 3, 2, 1, 0] function sort_array(array){ let sum = array[0] + array[array.length - 1]; let newArr = []; if(sum % 2 === 0){ newArr = array.sort(function(a, b){return b - a;}); }else{ newArr = array.sort(function(a, b){return a - b;}); } return newArr;
}
const assert = require('node:assert'); function test() { let candidate = sort_array; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5]),[5]); assert.deepEqual(candidate([2, 4, 3, 0, 1, 5]),[0, 1, 2, 3, 4, 5]); assert.deepEqual(candidate([2, 4, 3, 0, 1, 5, 6]),[6, 5, 4, 3, 2, 1, 0]); assert.deepEqual(candidate([2, 1]),[1, 2]); assert.deepEqual(candidate([15, 42, 87, 32, 11, 0]),[0, 11, 15, 32, 42, 87]); assert.deepEqual(candidate([21, 14, 23, 11]),[23, 21, 14, 11]); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L25
js
//It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array of GPAs for some students and you have to write // a function that can output an array of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) // ["A+", "B", "C-", "C", "A-"] function numerical_letter_grade(grades){ var grades_array = [];
if (grades[i] >= 4.0){ grades_array.push("A+"); } else if (grades[i] > 3.7){ grades_array.push("A"); } else if (grades[i] > 3.3){ grades_array.push("A-"); } else if (grades[i] > 3.0){ grades_array.push("B+"); } else if (grades[i] > 2.7){ grades_array.push("B"); } else if (grades[i] > 2.3){ grades_array.push("B-"); } else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); } else if (grades[i] > 1.3){ grades_array.push("C-"); } else if (grades[i] > 1.0){ grades_array.push("D+"); } else if (grades[i] > 0.7){ grades_array.push("D"); } else if (grades[i] > 0.0){ grades_array.push("D-"); } else if (grades[i] == 0.0){ grades_array.push("E"); } } return grades_array; }
for (var i = 0; i < grades.length; i++){
const assert = require('node:assert'); function test() { let candidate = numerical_letter_grade; assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]); assert.deepEqual(candidate([1.2]),["D+"]); assert.deepEqual(candidate([0.5]),["D-"]); assert.deepEqual(candidate([0.0]),["E"]); assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]); assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]); } test();
humaneval-HumanEval_39_prime_fib.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 { // prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> primeFib((1l)) // (2l) // >>> primeFib((2l)) // (3l) // >>> primeFib((3l)) // (5l) // >>> primeFib((4l)) // (13l) // >>> primeFib((5l)) // (89l) public static long primeFib(long n) { long fib = 1; long prev = 0; long count = 0; while (count != n) { long tmp = fib; fib += prev; prev = tmp; if (BigInteger.valueOf(fib).isProbablePrime(1)) { count++; }
return fib; } }
}
} public static void main(String[] args) { assert(primeFib((1l)) == (2l)); assert(primeFib((2l)) == (3l)); assert(primeFib((3l)) == (5l)); assert(primeFib((4l)) == (13l)); assert(primeFib((5l)) == (89l)); assert(primeFib((6l)) == (233l)); assert(primeFib((7l)) == (1597l)); assert(primeFib((8l)) == (28657l)); assert(primeFib((9l)) == (514229l)); assert(primeFib((10l)) == (433494437l)); } }
humaneval-HumanEval_156_int_to_mini_roman.json-L44
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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; }
res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
if (num >= 90) {
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_16_count_distinct_characters.json-L10
js
//Given a string, find out how many distinct characters (regardless of case) does it consist of // >>> count_distinct_characters("xyzXYZ") // 3 // >>> count_distinct_characters("Jerry") // 4 function count_distinct_characters(string){ var arr = string.split(""); var result = []; for(var i = 0; i < arr.length; i++){
result.push(arr[i].toLowerCase()); } } return result.length; }
if(result.indexOf(arr[i].toLowerCase()) < 0){
const assert = require('node:assert'); function test() { let candidate = count_distinct_characters; assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("abcde"),5); assert.deepEqual(candidate("abcdecadeCADE"),5); assert.deepEqual(candidate("aaaaAAAAaaaa"),1); assert.deepEqual(candidate("Jerry jERRY JeRRRY"),5); } test();
humaneval-HumanEval_12_longest.json-L12
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) {
} for (var i = 0; i < strings.length; i++) { if (!result || strings[i].length > result.length) { result = strings[i]; } } return result; }
return undefined;
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_121_solution.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a non-empty array list of integers, return the sum of all of the odd elements that are in even positions. // Examples // >>> solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) // (12l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) // (9l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) // (0l) public static long solution(ArrayList<Long> lst) { long sum = 0; for (int i = 0; i < lst.size(); i++) { if (i % 2 == 0 && lst.get(i) % 2 == 1) { sum += lst.get(i); } } return sum; }
}
} public static void main(String[] args) { assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) == (12l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) == (9l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l)))) == (5l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)23l, (long)32l)))) == (23l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)13l, (long)2l, (long)9l)))) == (3l)); } }
humaneval-HumanEval_35_max_element.json-L10
py
from typing import List def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """
for i in range(1, len(l)): if l[i] > max_elem: max_elem = l[i] return max_elem
max_elem = l[0]
def check(candidate): assert candidate([1, 2, 3]) == 3 assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124 def test_check(): check(max_element) test_check()
humaneval-HumanEval_1_separate_paren_groups.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 { // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) {
} } } return output; } }
output.add(temp.toString());
} 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_80_is_happy.json-L24
js
//You are given a string s. // Your task is to check if the string is hapjs or not. // A string is hapjs if its length is at least 3 and every 3 consecutive letters are distinct // For example: // >>> is_happy(a) // false // >>> is_happy(aa) // false // >>> is_happy(abcd) // true // >>> is_happy(aabb) // false // >>> is_happy(adb) // true // >>> is_happy(xyy) // false function is_happy(s){ let happy = true; if(s.length<3){ happy = false; } for(let i=2; i<s.length; i++){ if(s[i]===s[i-1] || s[i]===s[i-2]){
} } return happy; }
happy = false;
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_115_max_fill.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given 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) {
for (ArrayList<Long> well : grid) { long level = 0l; for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity; if (level % capacity != 0l) { units += 1l; } count += units; } return count; } }
long count = 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_117_select_words.json-L24
py
from typing import List def select_words(s: str, n: int) -> List[str]: """Given a string s and a natural number n, you have been tasked to implement a function that returns a 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 list. Note: you may assume the input string contains only letters and spaces. Examples: >>> select_words('Mary had a little lamb', 4) ['little'] >>> select_words('Mary had a little lamb', 3) ['Mary', 'lamb'] >>> select_words('simple white space', 2) [] >>> select_words('Hello world', 4) ['world'] >>> select_words('Uncle sam', 3) ['Uncle'] """ CONSONANTS = 'bcdfghjklmnpqrstvwxyz' words = s.split() result = []
count = 0 for char in word: if char.lower() in CONSONANTS: count += 1 if count == n: result.append(word) return result
for word in words:
def check(candidate): assert candidate('Mary had a little lamb', 4) == ['little'] assert candidate('Mary had a little lamb', 3) == ['Mary', 'lamb'] assert candidate('simple white space', 2) == [] assert candidate('Hello world', 4) == ['world'] assert candidate('Uncle sam', 3) == ['Uncle'] assert candidate('', 4) == [] assert candidate('a b c d e f', 1) == ['b', 'c', 'd', 'f'] def test_check(): check(select_words) test_check()
humaneval-HumanEval_119_match_parens.json-L21
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){
} else if (p === close){ if (stack.length === 0){ return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
stack.push(p);
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_91_is_bored.json-L18
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You'll be given a string of words, and your task is to count the number // of boredoms. A boredom is a sentence that starts with the word "I". // Sentences are delimited by '.', '?' or '!'. // For example: // >>> isBored(("Hello world")) // (0l) // >>> isBored(("The sky is blue. The sun is shining. I love this weather")) // (1l) public static long isBored(String S) {
String[] sentences = S.split("\\.\\s|\\?\\s|\\!\\s"); for (String sentence : sentences) { String[] words = sentence.split("\\s"); if (words.length > 0 && words[0].equals("I")) { boredoms++; } } return boredoms; } }
long boredoms = 0;
} public static void main(String[] args) { assert(isBored(("Hello world")) == (0l)); assert(isBored(("Is the sky blue?")) == (0l)); assert(isBored(("I love It !")) == (1l)); assert(isBored(("bIt")) == (0l)); assert(isBored(("I feel good today. I will be productive. will kill It")) == (2l)); assert(isBored(("You and I are going for a walk")) == (0l)); } }
humaneval-HumanEval_160_do_algebra.json-L27
js
//Given two arrays operator, and operand. The first array has basic algebra operations, and // the second array is an array of integers. Use the two given arrays to build the algebric // expression and return the evaluation of this expression. // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // Example: // operator['+', '*', '-'] // array = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array is equal to the length of operand array minus one. // Operand is an array of of non-negative integers. // Operator array has at least one operator, and operand array has at least two operands. function do_algebra(operator, operand){ let do_again; let count = 0; let temp; let answer; while(count < operator.length){ switch(operator[count]){ case '*':
operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '//': operand[count] = Math.floor(operand[count] / operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '**': operand[count] = Math.pow(operand[count], operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break; case '-': answer -= operand[0]; break; } operand.splice(0, 1); operator.splice(0, 1); } return answer; }
operand[count] = operand[count] * operand[count + 1];
const assert = require('node:assert'); function test() { let candidate = do_algebra; assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37); assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9); assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8); } test();
humaneval-HumanEval_86_anti_shuffle.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 { // Write a function that takes a string and returns an ordered version of it. // Ordered version of string, is a string where all words (separated by space) // are replaced by a new word where all the characters arranged in // ascending order based on ascii value. // Note: You should keep the order of words and blank spaces in the sentence. // For example: // >>> antiShuffle(("Hi")) // ("Hi") // >>> antiShuffle(("hello")) // ("ehllo") // >>> antiShuffle(("Hello World!!!")) // ("Hello !!!Wdlor") public static String antiShuffle(String s) { StringBuilder sb = new StringBuilder(); String[] words = s.split(" "); for (String word : words) { char[] chars = word.toCharArray(); Arrays.sort(chars); sb.append(new String(chars)); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); }
}
} public static void main(String[] args) { assert(antiShuffle(("Hi")).equals(("Hi"))); assert(antiShuffle(("hello")).equals(("ehllo"))); assert(antiShuffle(("number")).equals(("bemnru"))); assert(antiShuffle(("abcd")).equals(("abcd"))); assert(antiShuffle(("Hello World!!!")).equals(("Hello !!!Wdlor"))); assert(antiShuffle(("")).equals((""))); assert(antiShuffle(("Hi. My name is Mister Robot. How are you?")).equals((".Hi My aemn is Meirst .Rboot How aer ?ouy"))); } }
humaneval-HumanEval_41_car_race_collision.json-L12
js
//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. function car_race_collision(n){ let num_collisions = 0; let left_to_right = Array(n).fill(1);
for (let i = 0; i < left_to_right.length; i++) { for (let j = 0; j < right_to_left.length; j++) { if (left_to_right[i] == right_to_left[j]) { num_collisions++; } } } return num_collisions; }
let right_to_left = Array(n).fill(1);
const assert = require('node:assert'); function test() { let candidate = car_race_collision; assert.deepEqual(candidate(2),4); assert.deepEqual(candidate(3),9); assert.deepEqual(candidate(4),16); assert.deepEqual(candidate(8),64); assert.deepEqual(candidate(10),100); } test();
humaneval-HumanEval_118_get_closest_vowel.json-L22
js
//You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> get_closest_vowel("yogurt") // "u" // >>> get_closest_vowel("FULL") // "U" // >>> get_closest_vowel("quick") // "" // >>> get_closest_vowel("ab") // "" function get_closest_vowel(word){ let vowels = ["a", "e", "i", "o", "u"]; let i = word.length - 1; let result = []; if (word.length === 1) { return "" } else {
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]; } } }
while (i >= 0) {
const assert = require('node:assert'); function test() { let candidate = get_closest_vowel; assert.deepEqual(candidate("yogurt"),"u"); assert.deepEqual(candidate("full"),"u"); assert.deepEqual(candidate("easy"),""); assert.deepEqual(candidate("eAsy"),""); assert.deepEqual(candidate("ali"),""); assert.deepEqual(candidate("bad"),"a"); assert.deepEqual(candidate("most"),"o"); assert.deepEqual(candidate("ab"),""); assert.deepEqual(candidate("ba"),""); assert.deepEqual(candidate("quick"),""); assert.deepEqual(candidate("anime"),"i"); assert.deepEqual(candidate("Asia"),""); assert.deepEqual(candidate("Above"),"o"); } test();
humaneval-HumanEval_33_sort_third.json-L14
py
from typing import List def sort_third(l: List[int]) -> List[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """ for i in range(2, len(l), 3): j = i - 2
l[j], l[j + 3] = l[j + 3], l[j] j -= 3 return l
while j >= 0 and l[j] > l[j + 3]:
def check(candidate): assert candidate([5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5] assert candidate([5, 8, 3, 4, 6, 9, 2]) == [2, 8, 3, 4, 6, 9, 5] assert candidate([5, 6, 9, 4, 8, 3, 2]) == [2, 6, 9, 4, 8, 3, 5] assert candidate([5, 6, 3, 4, 8, 9, 2, 1]) == [2, 6, 3, 4, 8, 9, 5, 1] def test_check(): check(sort_third) test_check()
humaneval-HumanEval_122_add_elements.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 { // Given a non-empty array array list of integers arr and an integer k, return // the sum of the elements with at most two digits from the first k elements of arr. // Example: // >>> addElements((new ArrayList<Long>(Arrays.asList((long)111l, (long)21l, (long)3l, (long)4000l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l))), (4l)) // (24l) // Constraints: // 1. 1 <= len(arr) <= 100 // 2. 1 <= k <= len(arr) public static long addElements(ArrayList<Long> arr, long k) { return arr.stream().limit(k).filter(x -> x < 100).reduce(0l, (x, y) -> x + y);
}
}
} public static void main(String[] args) { assert(addElements((new ArrayList<Long>(Arrays.asList((long)1l, (long)-2l, (long)-3l, (long)41l, (long)57l, (long)76l, (long)87l, (long)88l, (long)99l))), (3l)) == (-4l)); assert(addElements((new ArrayList<Long>(Arrays.asList((long)111l, (long)121l, (long)3l, (long)4000l, (long)5l, (long)6l))), (2l)) == (0l)); assert(addElements((new ArrayList<Long>(Arrays.asList((long)11l, (long)21l, (long)3l, (long)90l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l))), (4l)) == (125l)); assert(addElements((new ArrayList<Long>(Arrays.asList((long)111l, (long)21l, (long)3l, (long)4000l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l))), (4l)) == (24l)); assert(addElements((new ArrayList<Long>(Arrays.asList((long)1l))), (1l)) == (1l)); } }
humaneval-HumanEval_20_find_closest_elements.json-L17
js
//From a supplied array of numbers (of length at least two) select and return two that are the closest to each // other and return them in order (smaller number, larger number). // >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) // [2.0, 2.2] // >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) // [2.0, 2.0] function find_closest_elements(numbers){ let closest = Math.abs(numbers[0] - numbers[1]); let a = numbers[0]; let b = numbers[1]; for (let i = 0; i < numbers.length; i++) { for (let j = i + 1; j < numbers.length; j++) { if (Math.abs(numbers[i] - numbers[j]) < closest) { closest = Math.abs(numbers[i] - numbers[j]); a = numbers[i]; b = numbers[j];
} } return a > b ? [b, a] : [a, b]; }
}
const assert = require('node:assert'); function test() { let candidate = find_closest_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]); } test();
humaneval-HumanEval_129_minPath.json-L64
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++){
if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
let curr = neighbours[i];
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_13_greatest_common_divisor.json-L7
js
//Return a greatest common divisor of two integers a and b // >>> greatest_common_divisor(3, 5) // 1 // >>> greatest_common_divisor(25, 15) // 5 function greatest_common_divisor(a, b){
let min = Math.min(a, b) if (max % min == 0) { return min } else { return greatest_common_divisor(min, max % min) } }
let max = Math.max(a, b)
const assert = require('node:assert'); function test() { let candidate = greatest_common_divisor; assert.deepEqual(candidate(3, 7),1); assert.deepEqual(candidate(10, 15),5); assert.deepEqual(candidate(49, 14),7); assert.deepEqual(candidate(144, 60),12); } test();
humaneval-HumanEval_11_string_xor.json-L20
js
//Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> string_xor("010", "110") // "100" function string_xor(a, b){ var arrayA = []; var arrayB = []; var arrayXOR = []; var result = ''; for (var i = 0; i < a.length; i++) { arrayA.push(parseInt(a[i])); } for (var j = 0; j < b.length; j++) { arrayB.push(parseInt(b[j])); } for (var k = 0; k < arrayA.length; k++) { if (arrayA[k] !== arrayB[k]) { arrayXOR.push(1); }
arrayXOR.push(0); } } result = arrayXOR.join(''); return result; }
else {
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_153_Strongest_Extension.json-L39
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You will be given the name of a class (a string) and an array array list of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array list. // For example, if you are given "Slices" as the class and an array array list of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC")))) // ("my_class.AA") public static String StrongestExtension(String class_name, ArrayList<String> extensions) { if (extensions.size() == 0) { return class_name; } int strength = Integer.MIN_VALUE; String strongest = ""; for (String s : extensions) { int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count(); int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count(); int diff = cap - sm; if (diff > strength) { strength = diff; strongest = s; }
return class_name + "." + strongest; } }
}
} public static void main(String[] args) { assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe"))); assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe"))); assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__"))); assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR"))); assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123"))); assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123"))); assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW"))); assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb"))); assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235"))); } }
humaneval-HumanEval_60_sum_to_n.json-L18
js
//sum_to_n is a function that sums numbers from 1 to n. // >>> sum_to_n(30) // 465 // >>> sum_to_n(100) // 5050 // >>> sum_to_n(5) // 15 // >>> sum_to_n(10) // 55 // >>> sum_to_n(1) // 1 function sum_to_n(n){ var sum = 0; for(var i = 1; i <= n; i++){ sum += i; } return sum;
}
const assert = require('node:assert'); function test() { let candidate = sum_to_n; assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(6),21); assert.deepEqual(candidate(11),66); assert.deepEqual(candidate(30),465); assert.deepEqual(candidate(100),5050); } test();
humaneval-HumanEval_143_words_in_sentence.json-L17
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 isPrime = true; if(number === 1 || number === 0){ return false; } for(var i = 2; i < number; i++){ if(number % i === 0){ isPrime = false; break; } } return isPrime; }).join(' '); }
var number = word.length;
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_138_is_equal_to_sum_even.json-L20
js
//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> is_equal_to_sum_even(4) // false // >>> is_equal_to_sum_even(6) // false // >>> is_equal_to_sum_even(8) // true function is_equal_to_sum_even(n){ let m =0; for(let i=2;i<n;i+=2){ for(let j=2;j<n;j+=2){ for(let k=2;k<n;k+=2){ for(let l=2;l<n;l+=2){ if((i+j+k+l)==n){ m=1; break; } }
} } if(m==1){ return true; } else{ return false; } }
}
const assert = require('node:assert'); function test() { let candidate = is_equal_to_sum_even; assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),true); assert.deepEqual(candidate(11),false); assert.deepEqual(candidate(12),true); assert.deepEqual(candidate(13),false); assert.deepEqual(candidate(16),true); } test();
humaneval-HumanEval_126_is_sorted.json-L63
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_65_circular_shift.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 { // Circular shift the digits of the integer x, shift the digits right by shift // and return the result as a string. // If shift > number of digits, return digits reversed. // >>> circularShift((12l), (1l)) // ("21") // >>> circularShift((12l), (2l)) // ("12") public static String circularShift(long x, long shift) { String digits = String.valueOf(x); if (shift > digits.length()) { return new StringBuilder(digits).reverse().toString(); } return (digits.substring(digits.length() - (int)shift, digits.length()) + digits.substring(0, digits.length() - (int)shift));
}
}
} public static void main(String[] args) { assert(circularShift((100l), (2l)).equals(("001"))); assert(circularShift((12l), (2l)).equals(("12"))); assert(circularShift((97l), (8l)).equals(("79"))); assert(circularShift((12l), (1l)).equals(("21"))); assert(circularShift((11l), (101l)).equals(("11"))); } }
humaneval-HumanEval_69_search.json-L17
py
from typing import List def search(lst: List[int]) -> int: """ You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: >>> search([4, 1, 2, 2, 3, 1]) 2 >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) 3 >>> search([5, 5, 4, 4, 4]) -1 """
for i in lst: if i in dic: dic[i] += 1 else: dic[i] = 1 maxValue = -1 for key, value in dic.items(): if value >= key and key > maxValue: maxValue = key return maxValue
dic = dict()
def check(candidate): assert candidate([5, 5, 5, 5, 1]) == 1 assert candidate([4, 1, 4, 1, 4, 4]) == 4 assert candidate([3, 3]) == -1 assert candidate([8, 8, 8, 8, 8, 8, 8, 8]) == 8 assert candidate([2, 3, 3, 2, 2]) == 2 assert candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]) == 1 assert candidate([3, 2, 8, 2]) == 2 assert candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1 assert candidate([8, 8, 3, 6, 5, 6, 4]) == -1 assert candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]) == 1 assert candidate([1, 9, 10, 1, 3]) == 1 assert candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]) == 5 assert candidate([1]) == 1 assert candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]) == 4 assert candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]) == 2 assert candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1 assert candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]) == 4 assert candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]) == 4 assert candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]) == 2 assert candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]) == -1 assert candidate([10]) == -1 assert candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2 assert candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1 assert candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]) == 1 assert candidate([3, 10, 10, 9, 2]) == -1 def test_check(): check(search) test_check()
humaneval-HumanEval_93_encode.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes a message, and encodes in such a // way that it swaps case of all letters, replaces all vowels in // the message with the letter that appears 2 places ahead of that // vowel in the english alphabet. // Assume only letters. // Examples: // >>> encode(("test")) // ("TGST") // >>> encode(("This is a message")) // ("tHKS KS C MGSSCGG") public static String encode(String message) { char[] arr = message.toCharArray(); char[] vowels = "AEIOUaeiou".toCharArray(); for (int i = 0; i < arr.length; i++) { if (Arrays.binarySearch(vowels, arr[i]) > -1) { arr[i] = (char) (arr[i] + 2);
if (Character.isUpperCase(arr[i])) { arr[i] = Character.toLowerCase(arr[i]); } else { arr[i] = Character.toUpperCase(arr[i]); } } return new String(arr); } }
}
} public static void main(String[] args) { assert(encode(("TEST")).equals(("tgst"))); assert(encode(("Mudasir")).equals(("mWDCSKR"))); assert(encode(("YES")).equals(("ygs"))); assert(encode(("This is a message")).equals(("tHKS KS C MGSSCGG"))); assert(encode(("I DoNt KnOw WhAt tO WrItE")).equals(("k dQnT kNqW wHcT Tq wRkTg"))); } }
humaneval-HumanEval_152_compare.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 { // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two array array lists of scores and guesses of equal length, where each index shows a match. // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))) // >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l))) public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) { ArrayList<Long> result = new ArrayList<Long>(); for (int i = 0; i < game.size(); i++) { if (game.get(i) != guess.get(i)) { result.add(Math.abs(game.get(i) - guess.get(i)));
result.add((long)0); } } return result; } }
} else {
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_105_by_length.json-L47
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"); }
arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
else if(num == 8){
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_30_get_positive.json-L7
js
//Return only positive numbers in the array. // >>> get_positive([-1, 2, -4, 5, 6]) // [2, 5, 6] // >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) // [5, 3, 2, 3, 9, 123, 1] function get_positive(l){
}
return l.filter(e=>e>0);
const assert = require('node:assert'); function test() { let candidate = get_positive; assert.deepEqual(candidate([-1, -2, 4, 5, 6]),[4, 5, 6]); assert.deepEqual(candidate([5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10]),[5, 3, 2, 3, 3, 9, 123, 1]); assert.deepEqual(candidate([-1, -2]),[]); assert.deepEqual(candidate([]),[]); } test();
humaneval-HumanEval_138_is_equal_to_sum_even.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 { // Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> isEqualToSumEven((4l)) // (false) // >>> isEqualToSumEven((6l)) // (false) // >>> isEqualToSumEven((8l)) // (true) public static boolean isEqualToSumEven(long n) { if (n < 4) { return false; } long d = 2; if (n % 2 == 1) { d = 1; } long minX = d; long maxX = n / 4; while (minX <= maxX) { long x = (minX + maxX) / 2; long y = n - 2 * x; if (y % 2 == 1) { y--; } if (2 * x + y < n) { minX = x + 1; } else if (2 * x + y > n) {
} else { return true; } } return false; } }
maxX = x - 1;
} public static void main(String[] args) { assert(isEqualToSumEven((4l)) == (false)); assert(isEqualToSumEven((6l)) == (false)); assert(isEqualToSumEven((8l)) == (true)); assert(isEqualToSumEven((10l)) == (true)); assert(isEqualToSumEven((11l)) == (false)); assert(isEqualToSumEven((12l)) == (true)); assert(isEqualToSumEven((13l)) == (false)); assert(isEqualToSumEven((16l)) == (true)); } }
humaneval-HumanEval_14_all_prefixes.json-L5
js
//Return array of all prefixes from shortest to longest of the input string // >>> all_prefixes("abc") // ["a", "ab", "abc"] function all_prefixes(string){
for (var i = 1; i <= string.length; i++){ result.push(string.slice(0, i)); } return result; }
var result = [];
const assert = require('node:assert'); function test() { let candidate = all_prefixes; assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("asdfgh"),["a", "as", "asd", "asdf", "asdfg", "asdfgh"]); assert.deepEqual(candidate("WWW"),["W", "WW", "WWW"]); } test();
humaneval-HumanEval_8_sum_product.json-L16
py
from typing import List, Tuple def sum_product(numbers: List[int]) -> Tuple[int, int]: """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """ sum = 0 product = 1 for i in numbers: sum += i product *= i
return (sum, product)
def check(candidate): assert candidate([]) == (0, 1) assert candidate([1, 1, 1]) == (3, 1) assert candidate([100, 0]) == (100, 0) assert candidate([3, 5, 7]) == (15, 105) assert candidate([10]) == (10, 10) def test_check(): check(sum_product) test_check()
humaneval-HumanEval_56_correct_bracketing.json-L20
py
def correct_bracketing(brackets: str) -> bool: """ brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('<') False >>> correct_bracketing('<>') True >>> correct_bracketing('<<><>>') True >>> correct_bracketing('><<>') False """ num_left_brackets = 0 for bracket in brackets: if bracket == '<': num_left_brackets += 1 elif bracket == '>': num_left_brackets -= 1
return False return num_left_brackets == 0
if num_left_brackets < 0:
def check(candidate): assert candidate('<>') == True assert candidate('<<><>>') == True assert candidate('<><><<><>><>') == True assert candidate('<><><<<><><>><>><<><><<>>>') == True assert candidate('<<<><>>>>') == False assert candidate('><<>') == False assert candidate('<') == False assert candidate('<<<<') == False assert candidate('>') == False assert candidate('<<>') == False assert candidate('<><><<><>><>><<>') == False assert candidate('<><><<><>><>>><>') == False def test_check(): check(correct_bracketing) test_check()
humaneval-HumanEval_35_max_element.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 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_108_count_nums.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 count_nums which takes an array array list 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. // >>> countNums((new ArrayList<Long>(Arrays.asList()))) // (0l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)11l, (long)-11l)))) // (1l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l)))) // (3l) public static long countNums(ArrayList<Long> arr) { long result = 0l; for (long i : arr) { String str = String.valueOf(i); int sum = 0; if (str.startsWith("-")) { sum = sum - (int) Character.getNumericValue(str.charAt(1)); for (int j = 2; j < str.length(); j++) { sum = sum + (int) Character.getNumericValue(str.charAt(j)); } } else { for (int j = 0; j < str.length(); j++) { sum = sum + (int) Character.getNumericValue(str.charAt(j)); } } if (sum > 0) { result++;
} return result; } }
}
} public static void main(String[] args) { assert(countNums((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)0l)))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l, (long)-2l, (long)3l, (long)4l, (long)5l)))) == (6l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)6l, (long)9l, (long)-6l, (long)0l, (long)1l, (long)5l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)100l, (long)98l, (long)-7l, (long)1l, (long)-1l)))) == (4l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)12l, (long)23l, (long)34l, (long)-45l, (long)-56l, (long)0l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l)))) == (1l)); } }
humaneval-HumanEval_41_car_race_collision.json-L16
js
//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. function car_race_collision(n){ let num_collisions = 0; let left_to_right = Array(n).fill(1); let right_to_left = Array(n).fill(1); for (let i = 0; i < left_to_right.length; i++) { for (let j = 0; j < right_to_left.length; j++) { if (left_to_right[i] == right_to_left[j]) {
} } } return num_collisions; }
num_collisions++;
const assert = require('node:assert'); function test() { let candidate = car_race_collision; assert.deepEqual(candidate(2),4); assert.deepEqual(candidate(3),9); assert.deepEqual(candidate(4),16); assert.deepEqual(candidate(8),64); assert.deepEqual(candidate(10),100); } test();
humaneval-HumanEval_107_even_odd_palindrome.json-L27
py
from typing import Tuple def even_odd_palindrome(n: int) -> Tuple[int, int]: """ Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: >>> even_odd_palindrome(3) (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: >>> even_odd_palindrome(12) (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. """ return (
sum(1 for i in range(1, n + 1) if str(i) == str(i)[::-1] and i % 2 != 0) )
sum(1 for i in range(1, n + 1) if str(i) == str(i)[::-1] and i % 2 == 0),
def check(candidate): assert candidate(123) == (8, 13) assert candidate(12) == (4, 6) assert candidate(3) == (1, 2) assert candidate(63) == (6, 8) assert candidate(25) == (5, 6) assert candidate(19) == (4, 6) assert candidate(9) == (4, 5) assert candidate(1) == (0, 1) def test_check(): check(even_odd_palindrome) test_check()
humaneval-HumanEval_68_pluck.json-L36
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given 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;
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; } }
long minValue = -1;
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_153_Strongest_Extension.json-L28
js
//You will be given the name of a class (a string) and an array of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array. // For example, if you are given "Slices" as the class and an array of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> Strongest_Extension("my_class", ["AA", "Be", "CC"]) // "my_class.AA" function Strongest_Extension(class_name, extensions){ var output = class_name + "."; var min_strength = 1; for (var i = 0; i < extensions.length; i++) { var strength = -1*(extensions[i].replace(/[^A-Z]/g, "").length - extensions[i].replace(/[^a-z]/g, "").length); if (strength < min_strength) { min_strength = strength; output = class_name + "." + extensions[i]; } } return output;
}
const assert = require('node:assert'); function test() { let candidate = Strongest_Extension; assert.deepEqual(candidate("Watashi", ["tEN", "niNE", "eIGHt8OKe"]),"Watashi.eIGHt8OKe"); assert.deepEqual(candidate("Boku123", ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]),"Boku123.YEs.WeCaNe"); assert.deepEqual(candidate("__YESIMHERE", ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]),"__YESIMHERE.NuLl__"); assert.deepEqual(candidate("K", ["Ta", "TAR", "t234An", "cosSo"]),"K.TAR"); assert.deepEqual(candidate("__HAHA", ["Tab", "123", "781345", "-_-"]),"__HAHA.123"); assert.deepEqual(candidate("YameRore", ["HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"]),"YameRore.okIWILL123"); assert.deepEqual(candidate("finNNalLLly", ["Die", "NowW", "Wow", "WoW"]),"finNNalLLly.WoW"); assert.deepEqual(candidate("_", ["Bb", "91245"]),"_.Bb"); assert.deepEqual(candidate("Sp", ["671235", "Bb"]),"Sp.671235"); } test();
humaneval-HumanEval_156_int_to_mini_roman.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 { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l";
} if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
num -= 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"))); } }
humaneval-HumanEval_61_correct_bracketing.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 { // brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correctBracketing(("(")) // (false) // >>> correctBracketing(("()")) // (true) // >>> correctBracketing(("(()())")) // (true) // >>> correctBracketing((")(()")) // (false) public static boolean correctBracketing(String brackets) { int balance = 0;
if (brackets.charAt(i) == '(') { balance++; } else { balance--; } if (balance < 0) { return false; } } return balance == 0; } }
for (int i = 0; i < brackets.length(); i++) {
} public static void main(String[] args) { assert(correctBracketing(("()")) == (true)); assert(correctBracketing(("(()())")) == (true)); assert(correctBracketing(("()()(()())()")) == (true)); assert(correctBracketing(("()()((()()())())(()()(()))")) == (true)); assert(correctBracketing(("((()())))")) == (false)); assert(correctBracketing((")(()")) == (false)); assert(correctBracketing(("(")) == (false)); assert(correctBracketing(("((((")) == (false)); assert(correctBracketing((")")) == (false)); assert(correctBracketing(("(()")) == (false)); assert(correctBracketing(("()()(()())())(()")) == (false)); assert(correctBracketing(("()()(()())()))()")) == (false)); } }
humaneval-HumanEval_158_find_max.json-L22
py
from typing import List def find_max(words: List[str]) -> str: """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. >>> find_max(['name', 'of', 'string']) 'string' >>> find_max(['name', 'enam', 'game']) 'enam' >>> find_max(['aaaaaaa', 'bb', 'cc']) 'aaaaaaa' """ max_num = 0 max_word = "" for word in words: unique_num = len(set(word)) if unique_num > max_num: max_num = unique_num
elif unique_num == max_num: if word < max_word: max_word = word return max_word
max_word = word
def check(candidate): assert candidate(['name', 'of', 'string']) == 'string' assert candidate(['name', 'enam', 'game']) == 'enam' assert candidate(['aaaaaaa', 'bb', 'cc']) == 'aaaaaaa' assert candidate(['abc', 'cba']) == 'abc' assert candidate(['play', 'this', 'game', 'of', 'footbott']) == 'footbott' assert candidate(['we', 'are', 'gonna', 'rock']) == 'gonna' assert candidate(['we', 'are', 'a', 'mad', 'nation']) == 'nation' assert candidate(['this', 'is', 'a', 'prrk']) == 'this' assert candidate(['b']) == 'b' assert candidate(['play', 'play', 'play']) == 'play' def test_check(): check(find_max) test_check()
humaneval-HumanEval_76_is_simple_power.json-L24
py
def is_simple_power(x: int, n: int) -> bool: """Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: >>> is_simple_power(1, 4) true >>> is_simple_power(2, 2) true >>> is_simple_power(8, 2) true >>> is_simple_power(3, 2) false >>> is_simple_power(3, 1) false >>> is_simple_power(5, 3) false """ if x == 0: return False else: while x > 1: if x % n != 0:
x /= n return True
return False
def check(candidate): assert candidate(16, 2) == True assert candidate(143214, 16) == False assert candidate(4, 2) == True assert candidate(9, 3) == True assert candidate(16, 4) == True assert candidate(24, 2) == False assert candidate(128, 4) == False assert candidate(12, 6) == False assert candidate(1, 1) == True assert candidate(1, 12) == True def test_check(): check(is_simple_power) test_check()
humaneval-HumanEval_77_iscube.json-L21
js
//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(1) // true // >>> iscube(2) // false // >>> iscube(-1) // true // >>> iscube(64) // true // >>> iscube(0) // true // >>> iscube(180) // false function iscube(a){ if(Math.cbrt(a)%1==0){ return true; }else{
} }
return false;
const assert = require('node:assert'); function test() { let candidate = iscube; assert.deepEqual(candidate(1),true); assert.deepEqual(candidate(2),false); assert.deepEqual(candidate(-1),true); assert.deepEqual(candidate(64),true); assert.deepEqual(candidate(180),false); assert.deepEqual(candidate(1000),true); assert.deepEqual(candidate(0),true); assert.deepEqual(candidate(1729),false); } test();
humaneval-HumanEval_27_flip_case.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 { // For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flipCase(("Hello")) // ("hELLO") public static String flipCase(String string) { String answer = ""; for (int i = 0; i < string.length(); i++) {
answer += Character.toUpperCase(string.charAt(i)); } else { answer += Character.toLowerCase(string.charAt(i)); } } return answer; } }
if (Character.isLowerCase(string.charAt(i))) {
} public static void main(String[] args) { assert(flipCase(("")).equals((""))); assert(flipCase(("Hello!")).equals(("hELLO!"))); assert(flipCase(("These violent delights have violent ends")).equals(("tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"))); } }
humaneval-HumanEval_10_make_palindrome.json-L15
js
//Find the shortest palindrome that begins with a supplied string. // Algorithm idea is simple: // - Find the longest postfix of supplied string that is a palindrome. // - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. // >>> make_palindrome("") // "" // >>> make_palindrome("cat") // "catac" // >>> make_palindrome("cata") // "catac" function make_palindrome(string){ var string_length = string.length; var is_palindrome = function(s){ return s == s.split("").reverse().join("");
var i = string_length; while(i > 0){ if(is_palindrome(string.substring(0, i))){ return string + string.substring(0, string_length - i).split("").reverse().join(""); } i--; } return string; }
};
const assert = require('node:assert'); function test() { let candidate = make_palindrome; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("x"),"x"); assert.deepEqual(candidate("xyz"),"xyzyx"); assert.deepEqual(candidate("xyx"),"xyx"); assert.deepEqual(candidate("jerry"),"jerryrrej"); } test();
humaneval-HumanEval_104_unique_digits.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 { // Given an array array list of positive integers x. return a sorted array list of all // elements that hasn't any even digit. // Note: Returned array list should be sorted in increasing order. // For example: // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))) // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> uniqueDigits(ArrayList<Long> x) { ArrayList<Long> b = new ArrayList<Long>();
if (x.get(i) < 0) { x.set(i, x.get(i)*(long)-1); } boolean unique = true; long z = x.get(i); while (z > 0) { long y = z % 10; if (y % 2 == 0) { unique = false; break; } z = z / 10; } if (unique) { b.add(x.get(i)); } } Collections.sort(b); return b; } }
for (int i = 0; i < x.size(); i++) {
} public static void main(String[] args) { assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)12345l, (long)2033l, (long)111l, (long)151l)))).equals((new ArrayList<Long>(Arrays.asList((long)111l, (long)151l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)135l, (long)103l, (long)31l)))).equals((new ArrayList<Long>(Arrays.asList((long)31l, (long)135l))))); } }
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L34
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // Examples: // >>> checkIfLastCharIsALetter(("apple pie")) // (false) // >>> checkIfLastCharIsALetter(("apple pi e")) // (true) // >>> checkIfLastCharIsALetter(("apple pi e ")) // (false) // >>> checkIfLastCharIsALetter(("")) // (false) public static boolean checkIfLastCharIsALetter(String txt) { if (txt.length() == 0) { return false; } int len = txt.length(); if (txt.substring(len - 1, len).matches("[A-Z]") || txt.substring(len - 1, len).matches("[a-z]")) { if (len == 1) { return true; } if (txt.substring(len - 2, len - 1).matches(" ")) { return true; }
return false; } }
}
} public static void main(String[] args) { assert(checkIfLastCharIsALetter(("apple")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e")) == (true)); assert(checkIfLastCharIsALetter(("eeeee")) == (false)); assert(checkIfLastCharIsALetter(("A")) == (true)); assert(checkIfLastCharIsALetter(("Pumpkin pie ")) == (false)); assert(checkIfLastCharIsALetter(("Pumpkin pie 1")) == (false)); assert(checkIfLastCharIsALetter(("")) == (false)); assert(checkIfLastCharIsALetter(("eeeee e ")) == (false)); assert(checkIfLastCharIsALetter(("apple pie")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e ")) == (false)); } }
humaneval-HumanEval_12_longest.json-L13
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_152_compare.json-L20
py
from typing import List def compare(game: List[int], guess: List[int]) -> List[int]: """I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: >>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]) [0, 0, 0, 0, 3, 3] >>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2]) [4, 4, 1, 0, 0, 6] """
return [abs(game[i] - guess[i]) for i in range(len(game))]
def check(candidate): assert candidate([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3] assert candidate([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]) == [0, 0, 0, 0, 0, 0] assert candidate([1, 2, 3], [-1, -2, -3]) == [2, 4, 6] assert candidate([1, 2, 3, 5], [-1, 2, 3, 4]) == [2, 0, 0, 1] def test_check(): check(compare) test_check()
humaneval-HumanEval_90_next_smallest.json-L25
py
from typing import List, Optional def next_smallest(lst: List[int]) -> Optional[int]: """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. >>> next_smallest([1, 2, 3, 4, 5]) 2 >>> next_smallest([5, 1, 4, 3, 2]) 2 >>> next_smallest([]) None >>> next_smallest([1, 1]) None """ if len(lst) < 2: return None min1 = min(lst[0], lst[1]) min2 = max(lst[0], lst[1]) for i in range(2, len(lst)): if lst[i] < min1: min2 = min1 min1 = lst[i]
min2 = lst[i] return min2 if min1 != min2 else None
elif lst[i] < min2:
def check(candidate): assert candidate([1, 2, 3, 4, 5]) == 2 assert candidate([5, 1, 4, 3, 2]) == 2 assert candidate([]) == None assert candidate([1, 1]) == None assert candidate([1, 1, 1, 1, 0]) == 1 assert candidate([1, 1]) == None assert candidate([-35, 34, 12, -45]) == -35 def test_check(): check(next_smallest) test_check()
humaneval-HumanEval_105_by_length.json-L22
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();
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; }
arr2.reverse();
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_96_count_up_to.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 a function that takes an non-negative integer and returns an array array list of the first n // integers that are prime numbers and less than n. // for example: // >>> countUpTo((5l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))) // >>> countUpTo((11l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l))) // >>> countUpTo((0l)) // (new ArrayList<Long>(Arrays.asList())) // >>> countUpTo((20l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l))) // >>> countUpTo((1l)) // (new ArrayList<Long>(Arrays.asList())) // >>> countUpTo((18l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))) public static ArrayList<Long> countUpTo(long n) { ArrayList<Long> arrayList = new ArrayList<Long>(); for (long i = 2l; i < n; i++) { boolean isPrime = true; for (long j = 2l; j < i; j++) { if (i % j == 0) {
break; } } if (isPrime) { arrayList.add(i); } } return arrayList; } }
isPrime = false;
} public static void main(String[] args) { assert(countUpTo((5l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))))); assert(countUpTo((6l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l))))); assert(countUpTo((7l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l))))); assert(countUpTo((10l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l))))); assert(countUpTo((0l)).equals((new ArrayList<Long>(Arrays.asList())))); assert(countUpTo((22l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l))))); assert(countUpTo((1l)).equals((new ArrayList<Long>(Arrays.asList())))); assert(countUpTo((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))))); assert(countUpTo((47l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l, (long)23l, (long)29l, (long)31l, (long)37l, (long)41l, (long)43l))))); assert(countUpTo((101l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l, (long)19l, (long)23l, (long)29l, (long)31l, (long)37l, (long)41l, (long)43l, (long)47l, (long)53l, (long)59l, (long)61l, (long)67l, (long)71l, (long)73l, (long)79l, (long)83l, (long)89l, (long)97l))))); } }
humaneval-HumanEval_86_anti_shuffle.json-L22
js
//Write a function that takes a string and returns an ordered version of it. // Ordered version of string, is a string where all words (separated by space) // are replaced by a new word where all the characters arranged in // ascending order based on ascii value. // Note: You should keep the order of words and blank spaces in the sentence. // For example: // >>> anti_shuffle("Hi") // "Hi" // >>> anti_shuffle("hello") // "ehllo" // >>> anti_shuffle("Hello World!!!") // "Hello !!!Wdlor" function anti_shuffle(s){ var result = []; var strings = s.split(" "); strings.forEach(function(str){ var temp = str.split(""); temp.sort(); result.push(temp.join("")); }); return result.join(" ");
}
const assert = require('node:assert'); function test() { let candidate = anti_shuffle; assert.deepEqual(candidate("Hi"),"Hi"); assert.deepEqual(candidate("hello"),"ehllo"); assert.deepEqual(candidate("number"),"bemnru"); assert.deepEqual(candidate("abcd"),"abcd"); assert.deepEqual(candidate("Hello World!!!"),"Hello !!!Wdlor"); assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hi. My name is Mister Robot. How are you?"),".Hi My aemn is Meirst .Rboot How aer ?ouy"); } test();
humaneval-HumanEval_148_bf.json-L18
js
//There are eight planets in our solar system: the closerst to the Sun // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, // Uranus, Neptune. // Write a function that takes two planet names as strings planet1 and planet2. // The function should return an array containing all planets whose orbits are // located between the orbit of planet1 and the orbit of planet2, sorted by // the proximity to the sun. // The function should return an empty array if planet1 or planet2 // are not correct planet names. // Examples // >>> bf("Jupiter", "Neptune") // ["Saturn", "Uranus"] // >>> bf("Earth", "Mercury") // "Venus" // >>> bf("Mercury", "Uranus") // ["Venus", "Earth", "Mars", "Jupiter", "Saturn"] function bf(planet1, planet2){
'Mercury':1, 'Venus':2, 'Earth':3, 'Mars':4, 'Jupiter':5, 'Saturn':6, 'Uranus':7, 'Neptune':8 } if(!planets[planet1] || !planets[planet2]){ return []; } var keys = Object.keys(planets); var position1 = keys.indexOf(planet1); var position2 = keys.indexOf(planet2); if(position1 > position2){ var temp = position1; position1 = position2; position2 = temp; } var res = []; for(var i = position1 + 1; i < position2; i++){ res.push(keys[i]); } return res; }
var planets = {
const assert = require('node:assert'); function test() { let candidate = bf; assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]); assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]); assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Earth"),[]); assert.deepEqual(candidate("Mars", "Earth"),[]); assert.deepEqual(candidate("Jupiter", "Makemake"),[]); } test();