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_110_exchange.json-L25
js
//In this problem, you will implement a function that takes two arrays of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array of only even numbers. // There is no limit on the number of exchanged elements between lst1 and lst2. // If it is possible to exchange elements between the lst1 and lst2 to make // all the elements of lst1 to be even, return "YES". // Otherwise, return "NO". // For example: // >>> exchange([1, 2, 3, 4], [1, 2, 3, 4]) // "YES" // >>> exchange([1, 2, 3, 4], [1, 5, 3, 4]) // "NO" // It is assumed that the input arrays will be non-empty. function exchange(lst1, lst2){ var num1 = 0; var num2 = 0; var exchange = true; while(num1 < lst1.length && exchange){ if(lst1[num1] % 2 !== 0){ exchange = false; if(num2 < lst2.length){ while(num2 < lst2.length && exchange == false){ if(lst2[num2] % 2 == 0){ lst1[num1] = lst2[num2];
} num2++; } } } num1++; } if(exchange){ return "YES"; }else{ return "NO"; } }
exchange = true;
const assert = require('node:assert'); function test() { let candidate = exchange; assert.deepEqual(candidate([1, 2, 3, 4], [1, 2, 3, 4]),"YES"); assert.deepEqual(candidate([1, 2, 3, 4], [1, 5, 3, 4]),"NO"); assert.deepEqual(candidate([1, 2, 3, 4], [2, 1, 4, 3]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 4]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 3]),"NO"); assert.deepEqual(candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]),"NO"); assert.deepEqual(candidate([100, 200], [200, 200]),"YES"); } test();
humaneval-HumanEval_96_count_up_to.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 { // 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) {
for (long i = 2l; i < n; i++) { boolean isPrime = true; for (long j = 2l; j < i; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) { arrayList.add(i); } } return arrayList; } }
ArrayList<Long> arrayList = new ArrayList<Long>();
} 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_150_x_or_y.json-L16
js
//A simple program which should return the value of x if n is // a prime number and should return the value of y otherwise. // Examples: // >>> x_or_y(7, 34, 12) // 34 // >>> x_or_y(15, 8, 5) // 5 function x_or_y(n, x, y){ if(n<2){ return y; } for(var i=2; i<n; i++){ if(n%i==0){ return y; }
return x; }
}
const assert = require('node:assert'); function test() { let candidate = x_or_y; assert.deepEqual(candidate(7, 34, 12),34); assert.deepEqual(candidate(15, 8, 5),5); assert.deepEqual(candidate(3, 33, 5212),33); assert.deepEqual(candidate(1259, 3, 52),3); assert.deepEqual(candidate(7919, -1, 12),-1); assert.deepEqual(candidate(3609, 1245, 583),583); assert.deepEqual(candidate(91, 56, 129),129); assert.deepEqual(candidate(6, 34, 1234),1234); assert.deepEqual(candidate(1, 2, 0),0); assert.deepEqual(candidate(2, 2, 0),2); } test();
humaneval-HumanEval_80_is_happy.json-L21
py
def is_happy(s: str) -> bool: """You are given a string s. Your task is to check if the string is happy or not. A string is happy 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 """ n = len(s) if n < 3:
else: for i in range(n - 2): if s[i] == s[i + 1] or s[i] == s[i + 2] or s[i + 1] == s[i + 2]: return False return True
return False
def check(candidate): assert candidate('a') == False assert candidate('aa') == False assert candidate('abcd') == True assert candidate('aabb') == False assert candidate('adb') == True assert candidate('xyy') == False assert candidate('iopaxpoi') == True assert candidate('iopaxioi') == False def test_check(): check(is_happy) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L54
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') elif x > 2.7: final.append('B') elif x > 2.3: final.append('B-') elif x > 2.0: final.append('C+') elif x > 1.7: final.append('C') elif x > 1.3: final.append('C-') elif x > 1.0: final.append('D+') elif x > 0.7: final.append('D') elif x > 0.0:
else: final.append('E') return final
final.append('D-')
def check(candidate): assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-'] assert candidate([1.2]) == ['D+'] assert candidate([0.5]) == ['D-'] assert candidate([0.0]) == ['E'] assert candidate([1.0, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+'] assert candidate([0.0, 0.7]) == ['E', 'D-'] def test_check(): check(numerical_letter_grade) test_check()
humaneval-HumanEval_43_pairs_sum_to_zero.json-L21
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){ var i = 0 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 }
}
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_155_even_odd_count.json-L16
py
from typing import Tuple def even_odd_count(num: int) -> Tuple[int, int]: """Given an integer. return a tuple that has the number of even and odd digits respectively. Example: >>> even_odd_count(-12) (1, 1) >>> even_odd_count(123) (1, 2) """ num_str = str(abs(num)) even_count = 0 odd_count = 0 for ch in num_str:
if digit % 2 == 0: even_count += 1 else: odd_count += 1 return even_count, odd_count
digit = int(ch)
def check(candidate): assert candidate(7) == (0, 1) assert candidate(-78) == (1, 1) assert candidate(3452) == (2, 2) assert candidate(346211) == (3, 3) assert candidate(-345821) == (3, 3) assert candidate(-2) == (1, 0) assert candidate(-45347) == (2, 3) assert candidate(0) == (1, 0) def test_check(): check(even_odd_count) test_check()
humaneval-HumanEval_134_check_if_last_char_is_a_letter.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 { // 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_10_make_palindrome.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Find the shortest palindrome that begins with a supplied string. // Algorithm idea is simple: // - Find the longest postfix of supplied string that is a palindrome. // - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. // >>> makePalindrome(("")) // ("") // >>> makePalindrome(("cat")) // ("catac") // >>> makePalindrome(("cata")) // ("catac") public static String makePalindrome(String string) { StringBuilder newString = new StringBuilder(string); String reverse = new StringBuilder(string).reverse().toString(); for (int index = 0; index < string.length(); index++) { if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { newString.append(reverse.substring(string.length() - index)); break; } }
} }
return newString.toString();
} public static void main(String[] args) { assert(makePalindrome(("")).equals((""))); assert(makePalindrome(("x")).equals(("x"))); assert(makePalindrome(("xyz")).equals(("xyzyx"))); assert(makePalindrome(("xyx")).equals(("xyx"))); assert(makePalindrome(("jerry")).equals(("jerryrrej"))); } }
humaneval-HumanEval_107_even_odd_palindrome.json-L37
js
//Given a positive integer n, return an array that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // Example 1: // >>> even_odd_palindrome(3) // [1, 2] // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // Example 2: // >>> even_odd_palindrome(12) // [4, 6] // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // Note: // 1. 1 <= n <= 10^3 // 2. returned array has the number of even and odd integer palindromes respectively. function even_odd_palindrome(n){ var pal = []; var isPalindrome = function(x){ var y = x.toString().split('').reverse().join(''); return y == x; } for(var i = 1; i <= n; i++){ if(isPalindrome(i)){ pal.push(i); } } var odd = 0; var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){ even++; } else{ odd++; } }
}
return [even, odd];
const assert = require('node:assert'); function test() { let candidate = even_odd_palindrome; assert.deepEqual(candidate(123),[8, 13]); assert.deepEqual(candidate(12),[4, 6]); assert.deepEqual(candidate(3),[1, 2]); assert.deepEqual(candidate(63),[6, 8]); assert.deepEqual(candidate(25),[5, 6]); assert.deepEqual(candidate(19),[4, 6]); assert.deepEqual(candidate(9),[4, 5]); assert.deepEqual(candidate(1),[0, 1]); } test();
humaneval-HumanEval_158_find_max.json-L32
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){
max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
if(word < 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_30_get_positive.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 only positive numbers in the array list. // >>> getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)-4l, (long)5l, (long)6l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)6l))) // >>> getPositive((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)3l, (long)9l, (long)123l, (long)1l))) public static ArrayList<Long> getPositive(ArrayList<Long> l) { return (new ArrayList<Long>(l.stream().filter(x -> x > 0).collect(Collectors.toList())));
}
}
} public static void main(String[] args) { assert(getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)4l, (long)5l, (long)6l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)5l, (long)6l))))); assert(getPositive((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)3l, (long)3l, (long)9l, (long)123l, (long)1l))))); assert(getPositive((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(getPositive((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_48_is_palindrome.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Checks if given string is a palindrome // >>> isPalindrome(("")) // (true) // >>> isPalindrome(("aba")) // (true) // >>> isPalindrome(("aaaaa")) // (true) // >>> isPalindrome(("zbcd")) // (false) public static boolean isPalindrome(String text) { boolean isPalindrome = true; int left = 0; int right = text.length() - 1; while (left < right) { if (text.charAt(left) != text.charAt(right)) { isPalindrome = false; break; } left++; right--; } return isPalindrome; }
}
} public static void main(String[] args) { assert(isPalindrome(("")) == (true)); assert(isPalindrome(("aba")) == (true)); assert(isPalindrome(("aaaaa")) == (true)); assert(isPalindrome(("zbcd")) == (false)); assert(isPalindrome(("xywyx")) == (true)); assert(isPalindrome(("xywyz")) == (false)); assert(isPalindrome(("xywzx")) == (false)); } }
humaneval-HumanEval_152_compare.json-L19
js
//I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two arrays of scores and guesses of equal length, where each index shows a match. // Return an array of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]) // [0, 0, 0, 0, 3, 3] // >>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2]) // [4, 4, 1, 0, 0, 6] function compare(game, guess){ let result = []; for(let i = 0; i < game.length; i++){ if(game[i] === guess[i]){ result.push(0); } else {
} } return result; }
result.push(Math.abs(game[i] - guess[i]));
const assert = require('node:assert'); function test() { let candidate = compare; assert.deepEqual(candidate([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]),[0, 0, 0, 0, 3, 3]); assert.deepEqual(candidate([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]),[0, 0, 0, 0, 0, 0]); assert.deepEqual(candidate([1, 2, 3], [-1, -2, -3]),[2, 4, 6]); assert.deepEqual(candidate([1, 2, 3, 5], [-1, 2, 3, 4]),[2, 0, 0, 1]); } test();
humaneval-HumanEval_33_sort_third.json-L40
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) { min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) {
j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
l_s.add(l_e.get(j));
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_91_is_bored.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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) { long boredoms = 0; 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; }
}
} 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_66_digitSum.json-L19
js
//Task // Write a function that takes a string as input and returns the sum of the upper characters only' // ASCII codes. // Examples: // >>> digitSum("") // 0 // >>> digitSum("abAB") // 131 // >>> digitSum("abcCd") // 67 // >>> digitSum("helloE") // 69 // >>> digitSum("woArBld") // 131 // >>> digitSum("aAaaaXa") // 153 function digitSum(s){ var sum = 0;
if(s[i] >= 'A' && s[i] <= 'Z'){ sum += s.charCodeAt(i); } } return sum; }
for(var i = 0; i < s.length; i++){
const assert = require('node:assert'); function test() { let candidate = digitSum; assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("abAB"),131); assert.deepEqual(candidate("abcCd"),67); assert.deepEqual(candidate("helloE"),69); assert.deepEqual(candidate("woArBld"),131); assert.deepEqual(candidate("aAaaaXa"),153); assert.deepEqual(candidate(" How are yOu?"),151); assert.deepEqual(candidate("You arE Very Smart"),327); } test();
humaneval-HumanEval_49_modp.json-L14
py
def modp(n: int, p: int) -> int: """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """
raise ValueError("modp: invalid p") if n < 0: raise ValueError("modp: invalid n") return 1 if n == 0 else 2**(n % (p-1)) % p
if p <= 0:
def check(candidate): assert candidate(3, 5) == 3 assert candidate(1101, 101) == 2 assert candidate(0, 101) == 1 assert candidate(3, 11) == 8 assert candidate(100, 101) == 1 assert candidate(30, 5) == 4 assert candidate(31, 5) == 3 def test_check(): check(modp) test_check()
humaneval-HumanEval_99_closest_integer.json-L18
js
//Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closest_integer("10") // 10 // >>> closest_integer("15.3") // 15 // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){
}else{ return Math.ceil(value); } }else{ if(value - Math.floor(value) > -0.5){ return Math.floor(value); }else{ return Math.ceil(value); } } }
return Math.floor(value);
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L18
js
//Write a function that returns true if the given number is the multiplication of 3 prime numbers // and false otherwise. // Knowing that (a) is less then 100. // Example: // >>> is_multiply_prime(30) // true // 30 = 2 * 3 * 5 function is_multiply_prime(a){ a = Math.abs(a); const prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]; let i = 0; let check = []; while(a != 1){ if(a % prime[i] == 0){ a = a / prime[i]; check.push(prime[i]); }else{
} } if(check.length == 3){ return true; }else{ return false; } }
i++;
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_149_sorted_list_sum.json-L28
js
//Write a function that accepts an array of strings as a parameter, // deletes the strings that have odd lengths from it, // and returns the resulted array with a sorted order, // The array is always an array of strings and never an array of numbers, // and it may contain duplicates. // The order of the array should be ascending by length of each word, and you // should return the array sorted by that rule. // If two words have the same length, sort the array alphabetically. // The function should return an array of strings in sorted order. // You may assume that all words will have the same length. // For example: // >>> list_sort(["aa", "a", "aaa"]) // ["aa"] // >>> list_sort(["ab", "a", "aaa", "cd"]) // ["ab", "cd"] function sorted_list_sum(lst){ var result = []; for(var i = 0; i < lst.length; i++){ if(lst[i].length % 2 == 0){ result.push(lst[i]); } } return result.sort(function(a, b){ if(a.length < b.length){ return -1; } else if(a.length > b.length){
} else{ if(a < b){ return -1; } else if(a > b){ return 1; } else{ return 0; } } }); } var a = ["aa", "a", "aaa"]; var b = ["ab", "a", "aaa", "cd"];
return 1;
const assert = require('node:assert'); function test() { let candidate = sorted_list_sum; assert.deepEqual(candidate(["aa", "a", "aaa"]),["aa"]); assert.deepEqual(candidate(["school", "AI", "asdf", "b"]),["AI", "asdf", "school"]); assert.deepEqual(candidate(["d", "b", "c", "a"]),[]); assert.deepEqual(candidate(["d", "dcba", "abcd", "a"]),["abcd", "dcba"]); assert.deepEqual(candidate(["AI", "ai", "au"]),["AI", "ai", "au"]); assert.deepEqual(candidate(["a", "b", "b", "c", "c", "a"]),[]); assert.deepEqual(candidate(["aaaa", "bbbb", "dd", "cc"]),["cc", "dd", "aaaa", "bbbb"]); } test();
humaneval-HumanEval_94_skjkasdkd.json-L29
js
//You are given an array of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) // 10 // >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) // 25 // >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) // 13 // >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) // 11 // >>> skjkasdkd([0, 81, 12, 3, 1, 21]) // 3 // >>> skjkasdkd([0, 8, 1, 2, 1, 7]) // 7 function skjkasdkd(lst){ function prime(n){ if (n<2) return false; for (let i=2; i<=Math.sqrt(n); i++){ if (n%i==0) return false; } return true; } let max = Math.max(...lst.filter(x=>prime(x))); let digits = String(max).split(''); let sum = 0; for (let i=0; i<digits.length; i++){ sum += Number(digits[i]);
return sum; }
}
const assert = require('node:assert'); function test() { let candidate = skjkasdkd; assert.deepEqual(candidate([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]),10); assert.deepEqual(candidate([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]),25); assert.deepEqual(candidate([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]),13); assert.deepEqual(candidate([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]),11); assert.deepEqual(candidate([0, 81, 12, 3, 1, 21]),3); assert.deepEqual(candidate([0, 8, 1, 2, 1, 7]),7); assert.deepEqual(candidate([8191]),19); assert.deepEqual(candidate([8191, 123456, 127, 7]),19); assert.deepEqual(candidate([127, 97, 8192]),10); } test();
humaneval-HumanEval_31_is_prime.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return true if a given number is prime, and false otherwise. // >>> isPrime((6l)) // (false) // >>> isPrime((101l)) // (true) // >>> isPrime((11l)) // (true) // >>> isPrime((13441l)) // (true) // >>> isPrime((61l)) // (true) // >>> isPrime((4l)) // (false) // >>> isPrime((1l)) // (false) public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false;
while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; } return true; } }
long i = 5;
} public static void main(String[] args) { assert(isPrime((6l)) == (false)); assert(isPrime((101l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((13441l)) == (true)); assert(isPrime((61l)) == (true)); assert(isPrime((4l)) == (false)); assert(isPrime((1l)) == (false)); assert(isPrime((5l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((17l)) == (true)); assert(isPrime((85l)) == (false)); assert(isPrime((77l)) == (false)); assert(isPrime((255379l)) == (false)); } }
humaneval-HumanEval_54_same_chars.json-L26
js
//Check if two words have the same characters. // >>> same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") // true // >>> same_chars("abcd", "dddddddabc") // true // >>> same_chars("dddddddabc", "abcd") // true // >>> same_chars("eabcd", "dddddddabc") // false // >>> same_chars("abcd", "dddddddabce") // false // >>> same_chars("eabcdzzzz", "dddzzzzzzzddddabc") // false function same_chars(s0, s1){ let res = true; for(let i = 0; i < s0.length; i++){ if(s1.indexOf(s0[i]) === -1){ res = false; break; } } for(let i = 0; i < s1.length; i++){ if(s0.indexOf(s1[i]) === -1){ res = false; break;
} return res; }
}
const assert = require('node:assert'); function test() { let candidate = same_chars; assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddeddabc"),true); assert.deepEqual(candidate("abcd", "dddddddabc"),true); assert.deepEqual(candidate("dddddddabc", "abcd"),true); assert.deepEqual(candidate("eabcd", "dddddddabc"),false); assert.deepEqual(candidate("abcd", "dddddddabcf"),false); assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddddabc"),false); assert.deepEqual(candidate("aabb", "aaccc"),false); } test();
humaneval-HumanEval_95_check_dict_case.json-L20
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 """
return False if any(not isinstance(x, str) for x in dict.keys()): return False if any(not x.islower() for x in dict.keys()): if any(not x.isupper() for x in dict.keys()): return False return True
if len(dict) == 0:
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_129_minPath.json-L35
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; } }
let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
}
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_39_prime_fib.json-L22
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){
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); }
if(number % i == 0 || number % (i + 2) == 0){
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_140_fix_spaces.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string text, replace all spaces in it with underscores, // and if a string has more than 2 consecutive spaces, // then replace all consecutive spaces with - // >>> fixSpaces((" Example")) // ("Example") // >>> fixSpaces((" Example 1")) // ("Example_1") // >>> fixSpaces((" Example 2")) // ("_Example_2") // >>> fixSpaces((" Example 3")) // ("_Example-3") public static String fixSpaces(String text) { String result = text.replace(" ", "_"); int i = 0; while (i < result.length() - 2) { if (result.charAt(i) == '_' && result.charAt(i + 1) == '_' && result.charAt(i + 2) == '_') { result = result.substring(0, i) + "-" + result.substring(i + 3); } i++; } return result; }
}
} public static void main(String[] args) { assert(fixSpaces(("Example")).equals(("Example"))); assert(fixSpaces(("Mudasir Hanif ")).equals(("Mudasir_Hanif_"))); assert(fixSpaces(("Yellow Yellow Dirty Fellow")).equals(("Yellow_Yellow__Dirty__Fellow"))); assert(fixSpaces(("Exa mple")).equals(("Exa-mple"))); assert(fixSpaces((" Exa 1 2 2 mple")).equals(("-Exa_1_2_2_mple"))); } }
humaneval-HumanEval_31_is_prime.json-L17
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){
return false; } if (n==2) { return true; } if (n%2==0) { return false; } var limit = Math.sqrt(n); for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false; } } return true; }
if (n==1) {
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_37_sort_even.json-L16
py
from typing import List def sort_even(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 odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """ if l: temp: List[int] = [] for i in range(0, len(l), 2): temp.append(l[i])
for i in range(0, len(l), 2): l[i] = temp[i // 2] return l
temp.sort()
def check(candidate): assert candidate([1, 2, 3]) == [1, 2, 3] assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123] assert candidate([5, 8, -12, 4, 23, 2, 3, 11, 12, -10]) == [-12, 8, 3, 4, 5, 2, 12, 11, 23, -10] def test_check(): check(sort_even) test_check()
humaneval-HumanEval_105_by_length.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 of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array array list, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))) // (new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))) // If the array array list is empty, return an empty array array list: // >>> byLength((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<String>(Arrays.asList())) // If the array array list has any strange number ignore it: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))) // (new ArrayList<String>(Arrays.asList((String)"One"))) public static ArrayList<String> byLength(ArrayList<Long> arr) { String[] a = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; ArrayList<String> res = new ArrayList<String>(); ArrayList<Long> good = new ArrayList<Long>(); for (Long i : arr) { if (i >= 1 && i <= 9) { good.add(i); } } good.sort(new Comparator<Long>() { public int compare(Long i1, Long i2) { return i1.compareTo(i2); } }); Collections.reverse(good);
res.add(a[i.intValue() - 1]); } return res; } }
for (Long i : good) {
} public static void main(String[] args) { assert(byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))).equals((new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList())))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))).equals((new ArrayList<String>(Arrays.asList((String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)3l, (long)2l)))).equals((new ArrayList<String>(Arrays.asList((String)"Three", (String)"Two", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)9l, (long)4l, (long)8l)))).equals((new ArrayList<String>(Arrays.asList((String)"Nine", (String)"Eight", (String)"Four"))))); } }
humaneval-HumanEval_137_compare_one.json-L55
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else:
elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
return None
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_148_bf.json-L38
js
//There are eight planets in our solar system: the closerst to the Sun // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, // Uranus, Neptune. // Write a function that takes two planet names as strings planet1 and planet2. // The function should return an array containing all planets whose orbits are // located between the orbit of planet1 and the orbit of planet2, sorted by // the proximity to the sun. // The function should return an empty array if planet1 or planet2 // are not correct planet names. // Examples // >>> bf("Jupiter", "Neptune") // ["Saturn", "Uranus"] // >>> bf("Earth", "Mercury") // "Venus" // >>> bf("Mercury", "Uranus") // ["Venus", "Earth", "Mars", "Jupiter", "Saturn"] function bf(planet1, planet2){ var planets = { 'Mercury':1, 'Venus':2, 'Earth':3, 'Mars':4, 'Jupiter':5, 'Saturn':6, 'Uranus':7, 'Neptune':8 } if(!planets[planet1] || !planets[planet2]){ return []; } var keys = Object.keys(planets); var position1 = keys.indexOf(planet1); var position2 = keys.indexOf(planet2); if(position1 > position2){ var temp = position1; position1 = position2; position2 = temp;
var res = []; for(var i = position1 + 1; i < position2; i++){ res.push(keys[i]); } return res; }
}
const assert = require('node:assert'); function test() { let candidate = bf; assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]); assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]); assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Earth"),[]); assert.deepEqual(candidate("Mars", "Earth"),[]); assert.deepEqual(candidate("Jupiter", "Makemake"),[]); } test();
humaneval-HumanEval_57_monotonic.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 { // 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_147_get_max_triples.json-L17
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0
k = 2 count = 0 while (i < n - 2): while (j < n - 1): while (k < n): if (a[i] + a[j] + a[k]) % 3 == 0: count += 1 k += 1 j += 1 k = j + 1 i += 1 j = i + 1 k = j + 1 return count
j = 1
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_40_triples_sum_to_zero.json-L22
py
from typing import List def triples_sum_to_zero(l: List[int]) -> bool: """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """ assert len(l) > 0, "The input list cannot be empty" l.sort()
for j in range(i + 1, len(l)): for k in range(j + 1, len(l)): if l[i] + l[j] + l[k] == 0: return True return False
for i in range(len(l)):
def check(candidate): assert candidate([1, 3, 5, 0]) == False assert candidate([1, 3, 5, -1]) == False assert candidate([1, 3, -2, 1]) == True assert candidate([1, 2, 3, 7]) == False assert candidate([1, 2, 5, 7]) == False assert candidate([2, 4, -5, 3, 9, 7]) == True assert candidate([1]) == False assert candidate([1, 3, 5, -100]) == False assert candidate([100, 3, 5, -100]) == False def test_check(): check(triples_sum_to_zero) test_check()
humaneval-HumanEval_37_sort_even.json-L38
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 { res.add(num); } index++; } return res;
}
}
} 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_36_fizz_buzz.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. // >>> fizzBuzz((50l)) // (0l) // >>> fizzBuzz((78l)) // (2l) // >>> fizzBuzz((79l)) // (3l) public static long fizzBuzz(long n) { long res = 0; for (long i = 0; i < n; i++) { if (i % 11 == 0 || i % 13 == 0) { String s = String.valueOf(i); for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '7') { res++; } } }
return res; } }
}
} public static void main(String[] args) { assert(fizzBuzz((50l)) == (0l)); assert(fizzBuzz((78l)) == (2l)); assert(fizzBuzz((79l)) == (3l)); assert(fizzBuzz((100l)) == (3l)); assert(fizzBuzz((200l)) == (6l)); assert(fizzBuzz((4000l)) == (192l)); assert(fizzBuzz((10000l)) == (639l)); assert(fizzBuzz((100000l)) == (8026l)); } }
humaneval-HumanEval_115_max_fill.json-L32
py
from typing import List def max_fill(grid: List[List[int]], capacity: int) -> int: """ You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) 6 Example 2: >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) 5 Example 3: >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid[:,1].length <= 10^2 * grid[i][j] -> 0 | 1 * 1 <= capacity <= 10 """ times = 0
for i in range(0, len(row), capacity): if 1 in row[i:i+capacity]: times += 1 return times
for row in grid:
def check(candidate): assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) == 6 assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) == 5 assert candidate([[0, 0, 0], [0, 0, 0]], 5) == 0 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2) == 4 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9) == 2 def test_check(): check(max_fill) test_check()
humaneval-HumanEval_68_pluck.json-L33
js
//"Given an array 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, [ smalest_value, its index ], // If there are no even values or the given array is empty, return []. // Example 1: // >>> pluck([4, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck([1, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck([]) // [] // Example 4: // >>> pluck([5, 0, 3, 0, 4, 2]) // [0, 1] // 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 function pluck(arr){ let result = [], index = -1; for(let i = 0; i < arr.length; i++){ if(arr[i] % 2 === 0){ if(result.length === 0 || result[0] > arr[i]){ result = [arr[i], i];
} } return result; }
}
const assert = require('node:assert'); function test() { let candidate = pluck; assert.deepEqual(candidate([4, 2, 3]),[2, 1]); assert.deepEqual(candidate([1, 2, 3]),[2, 1]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5, 0, 3, 0, 4, 2]),[0, 1]); assert.deepEqual(candidate([1, 2, 3, 0, 5, 3]),[0, 3]); assert.deepEqual(candidate([5, 4, 8, 4, 8]),[4, 1]); assert.deepEqual(candidate([7, 6, 7, 1]),[6, 1]); assert.deepEqual(candidate([7, 9, 7, 1]),[]); } test();
humaneval-HumanEval_147_get_max_triples.json-L25
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0 j = 1 k = 2 count = 0 while (i < n - 2): while (j < n - 1): while (k < n): if (a[i] + a[j] + a[k]) % 3 == 0: count += 1
j += 1 k = j + 1 i += 1 j = i + 1 k = j + 1 return count
k += 1
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_69_search.json-L33
js
//You are given a non-empty array of positive integers. Return the greatest integer that is greater than // zero, and has a frequency greater than or equal to the value of the integer itself. // The frequency of an integer is the number of times it appears in the array. // If no such a value exist, return -1. // Examples: // >>> search([4, 1, 2, 2, 3, 1]) // 2 // >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) // 3 // >>> search([5, 5, 4, 4, 4]) // -1 function search(lst){ var h = {}; for (var i=0; i<lst.length; i++){ var x = lst[i]; if (x in h){ h[x] += 1; } else{ h[x] = 1; } } var keys = Object.keys(h); var max = 0; for (var i=0; i<keys.length; i++){ if (keys[i] > max && h[keys[i]] >= keys[i]){ max = keys[i]; } } if (max == 0){ return -1; }
}
return max;
const assert = require('node:assert'); function test() { let candidate = search; assert.deepEqual(candidate([5, 5, 5, 5, 1]),1); assert.deepEqual(candidate([4, 1, 4, 1, 4, 4]),4); assert.deepEqual(candidate([3, 3]),-1); assert.deepEqual(candidate([8, 8, 8, 8, 8, 8, 8, 8]),8); assert.deepEqual(candidate([2, 3, 3, 2, 2]),2); assert.deepEqual(candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]),1); assert.deepEqual(candidate([3, 2, 8, 2]),2); assert.deepEqual(candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]),1); assert.deepEqual(candidate([8, 8, 3, 6, 5, 6, 4]),-1); assert.deepEqual(candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]),1); assert.deepEqual(candidate([1, 9, 10, 1, 3]),1); assert.deepEqual(candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]),5); assert.deepEqual(candidate([1]),1); assert.deepEqual(candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]),4); assert.deepEqual(candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]),2); assert.deepEqual(candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]),1); assert.deepEqual(candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]),4); assert.deepEqual(candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]),4); assert.deepEqual(candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]),2); assert.deepEqual(candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]),-1); assert.deepEqual(candidate([10]),-1); assert.deepEqual(candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]),2); assert.deepEqual(candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]),1); assert.deepEqual(candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]),1); assert.deepEqual(candidate([3, 10, 10, 9, 2]),-1); } test();
humaneval-HumanEval_70_strange_sort_list.json-L33
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given array list of integers, return array list in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) { if (lst.size() <= 1) { return lst; } ArrayList<Long> result = new ArrayList<Long>(); ArrayList<Long> sorted = new ArrayList<Long>(lst); Collections.sort(sorted); int min = 0; int max = sorted.size() - 1; while (min <= max) { result.add(sorted.get(min)); min++; if (min <= max) { result.add(sorted.get(max));
} } return result; } }
max--;
} public static void main(String[] args) { assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l))))); } }
humaneval-HumanEval_98_count_upper.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 { // Given a string s, count the number of uppercase vowels in even indices. // For example: // >>> countUpper(("aBCdEf")) // (1l) // >>> countUpper(("abcdefg")) // (0l) // >>> countUpper(("dBBE")) // (0l) public static long countUpper(String s) { return (long) IntStream.range(0, s.length()) .filter(i -> i % 2 == 0) .filter(i -> s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I' || s.charAt(i) == 'O' || s.charAt(i) == 'U') .count();
}
}
} public static void main(String[] args) { assert(countUpper(("aBCdEf")) == (1l)); assert(countUpper(("abcdefg")) == (0l)); assert(countUpper(("dBBE")) == (0l)); assert(countUpper(("B")) == (0l)); assert(countUpper(("U")) == (1l)); assert(countUpper(("")) == (0l)); assert(countUpper(("EEEE")) == (2l)); } }
humaneval-HumanEval_143_words_in_sentence.json-L21
js
//You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> words_in_sentence("This is a test") // "is" // Example 2: // >>> words_in_sentence("lets go for swimming") // "go for" // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters function words_in_sentence(sentence){ return sentence.split(' ').filter(word => { var number = word.length; var isPrime = true; if(number === 1 || number === 0){ return false;
for(var i = 2; i < number; i++){ if(number % i === 0){ isPrime = false; break; } } return isPrime; }).join(' '); }
}
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_120_maximum.json-L41
py
from typing import List def maximum(arr: List[int], k: int) -> List[int]: """ Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. Example 1: >>> maximum([-3, -4, 5], 3) [-4, -3, 5] Example 2: >>> maximum([4, -4, 4], 2) [4, 4] Example 3: >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1) [2] Note: 1. The length of the array will be in the range of [1, 1000]. 2. The elements in the array will be in the range of [-1000, 1000]. 3. 0 <= k <= len(arr) """ def get_max(arr: List[int], k: int) -> List[int]: """ Returns the maximum k numbers in the given array """ if k == 0: return [] elif k == 1: return [max(arr)] else: max_num = max(arr) arr.remove(max_num) return [max_num] + get_max(arr, k - 1)
return sorted(get_max(arr, k))
def check(candidate): assert candidate([-3, -4, 5], 3) == [-4, -3, 5] assert candidate([4, -4, 4], 2) == [4, 4] assert candidate([-3, 2, 1, 2, -1, -2, 1], 1) == [2] assert candidate([123, -123, 20, 0, 1, 2, -3], 3) == [2, 20, 123] assert candidate([-123, 20, 0, 1, 2, -3], 4) == [0, 1, 2, 20] assert candidate([5, 15, 0, 3, -13, -8, 0], 7) == [-13, -8, 0, 0, 3, 5, 15] assert candidate([-1, 0, 2, 5, 3, -10], 2) == [3, 5] assert candidate([1, 0, 5, -7], 1) == [5] assert candidate([4, -4], 2) == [-4, 4] assert candidate([-10, 10], 2) == [-10, 10] assert candidate([1, 2, 3, -23, 243, -400, 0], 0) == [] def test_check(): check(maximum) test_check()
humaneval-HumanEval_16_count_distinct_characters.json-L11
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++){ if(result.indexOf(arr[i].toLowerCase()) < 0){
} } return result.length; }
result.push(arr[i].toLowerCase());
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_124_valid_date.json-L19
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){
if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){ return false; } }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; } return false; }
var date_arr = date.split("-");
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_22_filter_integers.json-L8
js
//Filter given array of any jsthon values only for integers // >>> filter_integers(["a", 3.14, 5]) // [5] // >>> filter_integers([1, 2, 3, "abc", {}, []]) // [1, 2, 3] function filter_integers(values){ var result = [];
if(typeof value === "number" && value % 1 === 0){ result.push(value); } }); return result; }
values.forEach(function(value){
const assert = require('node:assert'); function test() { let candidate = filter_integers; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([4, {}, [], 23.2, 9, "adasd"]),[4, 9]); assert.deepEqual(candidate([3, "c", 3, 3, "a", "b"]),[3, 3, 3]); } test();
humaneval-HumanEval_61_correct_bracketing.json-L28
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false; } } } if (opens.length == 0){ return true;
else { return false; } }
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_67_fruit_distribution.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // In this task, you will be given a string that represents a number of apples and oranges // that are distributed in a basket of fruit this basket contains // apples, oranges, and mango fruits. Given the string that represents the total number of // the oranges and apples and an integer that represent the total number of the fruits // in the basket return the number of the mango fruits in the basket. // for examble: // >>> fruitDistribution(("5 apples and 6 oranges"), (19l)) // (8l) // >>> fruitDistribution(("0 apples and 1 oranges"), (3l)) // (2l) // >>> fruitDistribution(("2 apples and 3 oranges"), (100l)) // (95l) // >>> fruitDistribution(("100 apples and 1 oranges"), (120l)) // (19l) public static long fruitDistribution(String s, long n) { String[] splitted = s.split(" "); long apples = Long.parseLong(splitted[0]);
return n - apples - oranges; } }
long oranges = Long.parseLong(splitted[3]);
} public static void main(String[] args) { assert(fruitDistribution(("5 apples and 6 oranges"), (19l)) == (8l)); assert(fruitDistribution(("5 apples and 6 oranges"), (21l)) == (10l)); assert(fruitDistribution(("0 apples and 1 oranges"), (3l)) == (2l)); assert(fruitDistribution(("1 apples and 0 oranges"), (3l)) == (2l)); assert(fruitDistribution(("2 apples and 3 oranges"), (100l)) == (95l)); assert(fruitDistribution(("2 apples and 3 oranges"), (5l)) == (0l)); assert(fruitDistribution(("1 apples and 100 oranges"), (120l)) == (19l)); } }
humaneval-HumanEval_139_special_factorial.json-L20
py
def special_factorial(n: int) -> int: """The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. """ def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) if n <= 1: return 1
return n * special_factorial(n-1) * factorial(n-1)
else:
def check(candidate): assert candidate(4) == 288 assert candidate(5) == 34560 assert candidate(7) == 125411328000 assert candidate(1) == 1 def test_check(): check(special_factorial) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L17
py
def int_to_mini_roman(number: int) -> str: """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) 'xix' >>> int_to_mini_roman(152) 'clii' >>> int_to_mini_roman(426) 'cdxxvi' """ roman_numerals = { 1000: 'm',
500: 'd', 400: 'cd', 100: 'c', 90: 'xc', 50: 'l', 40: 'xl', 10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i' } roman_numeral = '' for key in sorted(roman_numerals.keys(), reverse=True): roman_numeral += roman_numerals[key] * (number // key) number = number % key return roman_numeral
900: 'cm',
def check(candidate): assert candidate(19) == 'xix' assert candidate(152) == 'clii' assert candidate(251) == 'ccli' assert candidate(426) == 'cdxxvi' assert candidate(500) == 'd' assert candidate(1) == 'i' assert candidate(4) == 'iv' assert candidate(43) == 'xliii' assert candidate(90) == 'xc' assert candidate(94) == 'xciv' assert candidate(532) == 'dxxxii' assert candidate(900) == 'cm' assert candidate(994) == 'cmxciv' assert candidate(1000) == 'm' def test_check(): check(int_to_mini_roman) test_check()
humaneval-HumanEval_77_iscube.json-L18
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){
return true; }else{ return false; } }
if(Math.cbrt(a)%1==0){
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_72_will_it_fly.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); }
return false; } for (int i = 0; i < q.size() / 2; i++) { if (q.get(i) != q.get(q.size() - 1 - i)) { return false; } } return true; } }
if (sum > w) {
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_100_make_a_pile.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer n, you have to make a pile of n levels of stones. // The first level has n stones. // The number of stones in the next level is: // - the next odd number if n is odd. // - the next even number if n is even. // Return the number of stones in each level in an array array list, where element at index // i represents the number of stones in the level (i+1). // Examples: // >>> makeAPile((3l)) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)7l))) public static ArrayList<Long> makeAPile(long n) {
for (long i = 0; i < n; i++) { levels.add(n + 2 * i); } return levels; } }
ArrayList<Long> levels = new ArrayList<Long>();
} public static void main(String[] args) { assert(makeAPile((3l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)7l))))); assert(makeAPile((4l)).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)6l, (long)8l, (long)10l))))); assert(makeAPile((5l)).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)9l, (long)11l, (long)13l))))); assert(makeAPile((6l)).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)8l, (long)10l, (long)12l, (long)14l, (long)16l))))); assert(makeAPile((8l)).equals((new ArrayList<Long>(Arrays.asList((long)8l, (long)10l, (long)12l, (long)14l, (long)16l, (long)18l, (long)20l, (long)22l))))); } }
humaneval-HumanEval_20_find_closest_elements.json-L19
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_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
temp = abs(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_40_triples_sum_to_zero.json-L41
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) { return false; } ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList); for (int i = 0; i < sortedList.size() - 2; i++) { int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) { j++; } else { k--; } }
return false; } }
}
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_26_remove_duplicates.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 { // From an array array list of integers, remove all elements that occur more than once. // Keep order of elements left the same as in the input. // >>> removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)4l))) public static ArrayList<Long> removeDuplicates(ArrayList<Long> numbers) { HashMap<Long, Long> hashmap = new HashMap<Long, Long>(); for (int i = 0; i < numbers.size(); i++) { Long key = numbers.get(i); if (hashmap.containsKey(key)) { hashmap.put(key, hashmap.get(key) + 1); } else { hashmap.put(key, 1L); } } ArrayList<Long> out = new ArrayList<Long>(); for (int i = 0; i < numbers.size(); i++) { Long key = numbers.get(i);
out.add(key); } } return out; } }
if (hashmap.get(key) == 1) {
} public static void main(String[] args) { assert(removeDuplicates((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l, (long)3l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)5l))))); } }
humaneval-HumanEval_137_compare_one.json-L49
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None
if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
elif isinstance(a, float) and isinstance(b, int):
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_133_sum_squares.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given an array array list of numbers. // You need to return the sum of squared numbers in the given array list, // round each element in the array list to the upper int(Ceiling) first. // Examples: // >>> lst((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f)))) // (14l) // >>> lst((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)4.0f, (float)9.0f)))) // (98l) // >>> lst((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)3.0f, (float)5.0f, (float)7.0f)))) // (84l) // >>> lst((new ArrayList<Float>(Arrays.asList((float)1.4f, (float)4.2f, (float)0.0f)))) // (29l) // >>> lst((new ArrayList<Float>(Arrays.asList((float)-2.4f, (float)1.0f, (float)1.0f)))) // (6l) public static long sumSquares(ArrayList<Float> lst) { if (lst.size() == 0) { return 0; } long sum = 0; for (int i = 0; i < lst.size(); i++) { sum += (long)Math.ceil(lst.get(i)) * (long)Math.ceil(lst.get(i)); } return sum;
}
}
} public static void main(String[] args) { assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f)))) == (14l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f)))) == (14l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)3.0f, (float)5.0f, (float)7.0f)))) == (84l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)1.4f, (float)4.2f, (float)0.0f)))) == (29l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)-2.4f, (float)1.0f, (float)1.0f)))) == (6l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)100.0f, (float)1.0f, (float)15.0f, (float)2.0f)))) == (10230l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)10000.0f, (float)10000.0f)))) == (200000000l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)-1.4f, (float)4.6f, (float)6.3f)))) == (75l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)-1.4f, (float)17.9f, (float)18.9f, (float)19.9f)))) == (1086l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)0.0f)))) == (0l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)-1.0f)))) == (1l)); assert(sumSquares((new ArrayList<Float>(Arrays.asList((float)-1.0f, (float)1.0f, (float)0.0f)))) == (2l)); } }
humaneval-HumanEval_158_find_max.json-L16
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 = {};
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; }
var word = words[i];
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_12_longest.json-L15
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++) {
result = strings[i]; } } return result; }
if (!result || strings[i].length > result.length) {
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_31_is_prime.json-L19
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){ if (n==1) { return false;
if (n==2) { return true; } if (n%2==0) { return false; } var limit = Math.sqrt(n); for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false; } } return true; }
}
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_20_find_closest_elements.json-L14
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) {
a = numbers[i]; b = numbers[j]; } } } return a > b ? [b, a] : [a, b]; }
closest = Math.abs(numbers[i] - numbers[j]);
const assert = require('node:assert'); function test() { let candidate = find_closest_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]); } test();
humaneval-HumanEval_18_how_many_times.json-L17
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Find how many times a given substring can be found in the original string. Count overlaping cases. // >>> howManyTimes((""), ("a")) // (0l) // >>> howManyTimes(("aaa"), ("a")) // (3l) // >>> howManyTimes(("aaaa"), ("aa")) // (3l) public static long howManyTimes(String string, String substring) {
int index = 0; while (index != -1) { index = string.indexOf(substring, index); if (index != -1) { index++; count++; } } return count; } }
long count = 0;
} public static void main(String[] args) { assert(howManyTimes((""), ("x")) == (0l)); assert(howManyTimes(("xyxyxyx"), ("x")) == (4l)); assert(howManyTimes(("cacacacac"), ("cac")) == (4l)); assert(howManyTimes(("john doe"), ("john")) == (1l)); } }
humaneval-HumanEval_126_is_sorted.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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;
boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue(); } else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
int previous_number = 0;
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_126_is_sorted.json-L42
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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();
} 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; } } }
running_max = number.intValue();
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_54_same_chars.json-L28
js
//Check if two words have the same characters. // >>> same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") // true // >>> same_chars("abcd", "dddddddabc") // true // >>> same_chars("dddddddabc", "abcd") // true // >>> same_chars("eabcd", "dddddddabc") // false // >>> same_chars("abcd", "dddddddabce") // false // >>> same_chars("eabcdzzzz", "dddzzzzzzzddddabc") // false function same_chars(s0, s1){ let res = true; for(let i = 0; i < s0.length; i++){ if(s1.indexOf(s0[i]) === -1){ res = false; break; } } for(let i = 0; i < s1.length; i++){ if(s0.indexOf(s1[i]) === -1){ res = false; break; } }
}
return res;
const assert = require('node:assert'); function test() { let candidate = same_chars; assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddeddabc"),true); assert.deepEqual(candidate("abcd", "dddddddabc"),true); assert.deepEqual(candidate("dddddddabc", "abcd"),true); assert.deepEqual(candidate("eabcd", "dddddddabc"),false); assert.deepEqual(candidate("abcd", "dddddddabcf"),false); assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddddabc"),false); assert.deepEqual(candidate("aabb", "aaccc"),false); } test();
humaneval-HumanEval_65_circular_shift.json-L13
py
def circular_shift(x: int, shift: int) -> str: """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. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12' """ temp = list(str(x)) if shift > len(temp): return ''.join(reversed(temp))
return ''.join(temp[-shift:] + temp[:-shift])
else:
def check(candidate): assert candidate(100, 2) == '001' assert candidate(12, 2) == '12' assert candidate(97, 8) == '79' assert candidate(12, 1) == '21' assert candidate(11, 101) == '11' def test_check(): check(circular_shift) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L42
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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";
} if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
num -= 100;
} 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_96_count_up_to.json-L18
js
//Implement a function that takes an non-negative integer and returns an array of the first n // integers that are prime numbers and less than n. // for example: // >>> count_up_to(5) // [2, 3] // >>> count_up_to(11) // [2, 3, 5, 7] // >>> count_up_to(0) // [] // >>> count_up_to(20) // [2, 3, 5, 7, 11, 13, 17, 19] // >>> count_up_to(1) // [] // >>> count_up_to(18) // [2, 3, 5, 7, 11, 13, 17] function count_up_to(n){ if (n < 2) return [];
for (var i = 3; i < n; i += 2){ var prime = true; for (var j = 3; j < i; j += 2){ if (i % j === 0){ prime = false; break; } } if (prime) output.push(i); } return output; }
var output = [2];
const assert = require('node:assert'); function test() { let candidate = count_up_to; assert.deepEqual(candidate(5),[2, 3]); assert.deepEqual(candidate(6),[2, 3, 5]); assert.deepEqual(candidate(7),[2, 3, 5]); assert.deepEqual(candidate(10),[2, 3, 5, 7]); assert.deepEqual(candidate(0),[]); assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]); assert.deepEqual(candidate(1),[]); assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]); assert.deepEqual(candidate(101),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]); } test();
humaneval-HumanEval_52_below_threshold.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 { // Return true if all numbers in the array list l are below threshold t. // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) // (true) // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) // (false) public static boolean belowThreshold(ArrayList<Long> l, long t) { Long[] a = l.toArray(new Long[l.size()]); for (int i = 0; i < a.length; i++) { if (a[i] >= t) {
} } return true; } }
return false;
} public static void main(String[] args) { assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) == (false)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (21l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (22l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (11l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (10l)) == (false)); } }
humaneval-HumanEval_70_strange_sort_list.json-L13
js
//Given array of integers, return array in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strange_sort_list([1, 2, 3, 4]) // [1, 4, 2, 3] // >>> strange_sort_list([5, 5, 5, 5]) // [5, 5, 5, 5] // >>> strange_sort_list([]) // [] function strange_sort_list(lst){ if(lst.length === 0){
} var output = []; var tmp = lst.slice(); for(var i = 0; i < lst.length; i++){ if(i % 2 === 0){ output.push(Math.min.apply(null, tmp)); } else{ output.push(Math.max.apply(null, tmp)); } tmp.splice(tmp.indexOf(output[i]), 1); } return output; }
return [];
const assert = require('node:assert'); function test() { let candidate = strange_sort_list; assert.deepEqual(candidate([1, 2, 3, 4]),[1, 4, 2, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9]),[5, 9, 6, 8, 7]); assert.deepEqual(candidate([1, 2, 3, 4, 5]),[1, 5, 2, 4, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9, 1]),[1, 9, 5, 8, 6, 7]); assert.deepEqual(candidate([5, 5, 5, 5]),[5, 5, 5, 5]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7, 8]),[1, 8, 2, 7, 3, 6, 4, 5]); assert.deepEqual(candidate([0, 2, 2, 2, 5, 5, -5, -5]),[-5, 5, -5, 5, 0, 2, 2, 2]); assert.deepEqual(candidate([111111]),[111111]); } test();
humaneval-HumanEval_143_words_in_sentence.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> wordsInSentence(("This is a test")) // ("is") // Example 2: // >>> wordsInSentence(("lets go for swimming")) // ("go for") // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters public static String wordsInSentence(String sentence) { StringBuilder ans = new StringBuilder();
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; boolean isPrime; for (String word : words) { isPrime = false; for (int prime : primes) { if (word.length() == prime) { isPrime = true; break; } } if (isPrime) { ans.append(word + " "); } } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
String[] words = sentence.split(" ");
} public static void main(String[] args) { assert(wordsInSentence(("This is a test")).equals(("is"))); assert(wordsInSentence(("lets go for swimming")).equals(("go for"))); assert(wordsInSentence(("there is no place available here")).equals(("there is no place"))); assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein"))); assert(wordsInSentence(("go for it")).equals(("go for it"))); assert(wordsInSentence(("here")).equals((""))); assert(wordsInSentence(("here is")).equals(("is"))); } }
humaneval-HumanEval_115_max_fill.json-L32
js
//You are given a rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // Example 1: // >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) // 6 // Example 2: // >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) // 5 // Example 3: // >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) // 0 // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 function max_fill(grid, capacity){ var maxFill = 0; var sum = 0; var c = 1; var r = grid.length; var c = grid[0].length; for(var i = 0; i < r; i++){ sum = 0; for(var j = 0; j < c; j++){ sum += grid[i][j];
maxFill += Math.ceil(sum/capacity); } return maxFill; }
}
const assert = require('node:assert'); function test() { let candidate = max_fill; assert.deepEqual(candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1),6); assert.deepEqual(candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2),5); assert.deepEqual(candidate([[0, 0, 0], [0, 0, 0]], 5),0); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2),4); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9),2); } test();
humaneval-HumanEval_31_is_prime.json-L36
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){ if (n==1) { return false; } if (n==2) { return true; } if (n%2==0) { return false; } var limit = Math.sqrt(n); for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false; } }
}
return true;
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_17_parse_music.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 { // Input to this function is a string representing musical notes in a special ASCII format. // Your task is to parse this string and return array list of integers corresponding to how many beats does each // not last. // Here is a legend: // 'o' - whole note, lasts four beats // 'o|' - half note, lasts two beats // '.|' - quater note, lasts one beat // >>> parseMusic(("o o| .| o| o| .| .| .| .| o o")) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l))) public static ArrayList<Long> parseMusic(String music_string) { ArrayList<Long> res = new ArrayList<Long>(); char[] chars = music_string.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == 'o') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)2l); i += 1;
res.add((long)4l); } } else if (chars[i] == '.') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)1l); i += 1; } } } return res; } }
} else {
} public static void main(String[] args) { assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList())))); assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))); assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l))))); } }
humaneval-HumanEval_93_encode.json-L15
py
def encode(message: str) -> str: """ Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' """
if ch.isupper(): return ch.lower() else: return ch.upper() def encode_vowel(ch: str) -> str: if ch.lower() in 'aeiou': if ch.lower() in 'wxyz': return ch.lower() return chr(ord(ch) + 2) return ch return ''.join(map(lambda ch: encode_vowel(swap_case(ch)), message))
def swap_case(ch: str) -> str:
def check(candidate): assert candidate('TEST') == 'tgst' assert candidate('Mudasir') == 'mWDCSKR' assert candidate('YES') == 'ygs' assert candidate('This is a message') == 'tHKS KS C MGSSCGG' assert candidate('I DoNt KnOw WhAt tO WrItE') == 'k dQnT kNqW wHcT Tq wRkTg' def test_check(): check(encode) test_check()
humaneval-HumanEval_61_correct_bracketing.json-L20
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop();
else { return false; } } } if (opens.length == 0){ return true; } else { return false; } }
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_143_words_in_sentence.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 string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> wordsInSentence(("This is a test")) // ("is") // Example 2: // >>> wordsInSentence(("lets go for swimming")) // ("go for") // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters public static String wordsInSentence(String sentence) { StringBuilder ans = new StringBuilder(); String[] words = sentence.split(" ");
boolean isPrime; for (String word : words) { isPrime = false; for (int prime : primes) { if (word.length() == prime) { isPrime = true; break; } } if (isPrime) { ans.append(word + " "); } } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
} public static void main(String[] args) { assert(wordsInSentence(("This is a test")).equals(("is"))); assert(wordsInSentence(("lets go for swimming")).equals(("go for"))); assert(wordsInSentence(("there is no place available here")).equals(("there is no place"))); assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein"))); assert(wordsInSentence(("go for it")).equals(("go for it"))); assert(wordsInSentence(("here")).equals((""))); assert(wordsInSentence(("here is")).equals(("is"))); } }
humaneval-HumanEval_20_find_closest_elements.json-L19
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_154_cycpattern_check.json-L20
js
//You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word // >>> cycpattern_check("abcd", "abd") // false // >>> cycpattern_check("hello", "ell") // true // >>> cycpattern_check("whassup", "psus") // false // >>> cycpattern_check("abab", "baa") // true // >>> cycpattern_check("efef", "eeff") // false // >>> cycpattern_check("himenss", "simen") // true function cycpattern_check(a, b){ var result = false; for(var i = 0; i < b.length; i++){ result = result || a.includes(b); b = b.slice(1) + b[0]; }
}
return result;
const assert = require('node:assert'); function test() { let candidate = cycpattern_check; assert.deepEqual(candidate("xyzw", "xyw"),false); assert.deepEqual(candidate("yello", "ell"),true); assert.deepEqual(candidate("whattup", "ptut"),false); assert.deepEqual(candidate("efef", "fee"),true); assert.deepEqual(candidate("abab", "aabb"),false); assert.deepEqual(candidate("winemtt", "tinem"),true); } test();
humaneval-HumanEval_8_sum_product.json-L10
js
//For a given array of integers, return an array consisting of a sum and a product of all the integers in an array. // Empty sum should be equal to 0 and empty product should be equal to 1. // >>> sum_product([]) // [0, 1] // >>> sum_product([1, 2, 3, 4]) // [10, 24] function sum_product(numbers){ if(numbers.length == 0){ return [0, 1];
let sum = 0; let product = 1; for(let i = 0; i < numbers.length; i++){ sum += numbers[i]; product *= numbers[i]; } return [sum, product]; }
}
const assert = require('node:assert'); function test() { let candidate = sum_product; assert.deepEqual(candidate([]),[0, 1]); assert.deepEqual(candidate([1, 1, 1]),[3, 1]); assert.deepEqual(candidate([100, 0]),[100, 0]); assert.deepEqual(candidate([3, 5, 7]),[15, 105]); assert.deepEqual(candidate([10]),[10, 10]); } test();
humaneval-HumanEval_106_f.json-L24
js
//Implement the function f that takes n as a parameter, // and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f(5) // [1, 2, 6, 24, 15] function f(n){ var result = []; var sum = 0; var factorial = 1; for(var i = 1; i <= n; i++){ if(i % 2 == 0){ for(var j = 1; j <= i; j++){ factorial *= j; } result.push(factorial); factorial = 1; }else{ for(var k = 1; k <= i; k++){ sum += k; }
sum = 0; } } return result; }
result.push(sum);
const assert = require('node:assert'); function test() { let candidate = f; assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]); assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]); assert.deepEqual(candidate(1),[1]); assert.deepEqual(candidate(3),[1, 2, 6]); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L25
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1)
if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
}
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_93_encode.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 { // 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++) {
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); } }
if (Arrays.binarySearch(vowels, arr[i]) > -1) {
} 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_111_histogram.json-L49
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string representing a space separated lowercase letters, return a hash map // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram(("a b c")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) { HashMap<String,Long> s = new HashMap<String,Long>(); if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" "); for (String sss : ss) { if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; }
}
} public static void main(String[] args) { assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("")).equals((new HashMap<String,Long>()))); assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l))))); } }
humaneval-HumanEval_94_skjkasdkd.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 { // You are given an array array list of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) // (10l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) // (25l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) // (13l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) // (11l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) // (3l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) // (7l) public static long skjkasdkd(ArrayList<Long> lst) { long largestPrime = 0l; for (Long item : lst) { long number = item; int counter = 0; if (item == 1) { continue; } if (item == 2) { counter = 1; } else { int l = 1; while (l <= (int) number) { if (number % l == 0) { counter++; } l++; } } if (counter == 2) {
largestPrime = number; } } } if (largestPrime == 0) { return 0l; } else { long output = 0l; while (largestPrime > 0) { output += largestPrime % 10; largestPrime /= 10; } return output; } } }
if (number > largestPrime) {
} public static void main(String[] args) { assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) == (10l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) == (25l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) == (13l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) == (11l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) == (3l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) == (7l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l, (long)123456l, (long)127l, (long)7l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)127l, (long)97l, (long)8192l)))) == (10l)); } }
humaneval-HumanEval_80_is_happy.json-L23
py
def is_happy(s: str) -> bool: """You are given a string s. Your task is to check if the string is happy or not. A string is happy 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 """ n = len(s) if n < 3: return False else:
if s[i] == s[i + 1] or s[i] == s[i + 2] or s[i + 1] == s[i + 2]: return False return True
for i in range(n - 2):
def check(candidate): assert candidate('a') == False assert candidate('aa') == False assert candidate('abcd') == True assert candidate('aabb') == False assert candidate('adb') == True assert candidate('xyy') == False assert candidate('iopaxpoi') == True assert candidate('iopaxioi') == False def test_check(): check(is_happy) test_check()
humaneval-HumanEval_158_find_max.json-L30
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_47_median.json-L11
js
//Return median of elements in the array l. // >>> median([3, 1, 2, 4, 5]) // 3 // >>> median([-10, 4, 6, 1000, 10, 20]) // 15.0 function median(l){ let middle = Math.floor(l.length / 2); let sorted = l.sort((a, b) => a - b); if (l.length % 2 === 0) { return (sorted[middle - 1] + sorted[middle]) / 2;
return sorted[middle]; } }
} else {
const assert = require('node:assert'); function test() { let candidate = median; assert.deepEqual(candidate([3, 1, 2, 4, 5]),3); assert.deepEqual(candidate([-10, 4, 6, 1000, 10, 20]),8.0); assert.deepEqual(candidate([5]),5); assert.deepEqual(candidate([6, 5]),5.5); assert.deepEqual(candidate([8, 1, 3, 9, 9, 2, 7]),7); } test();
humaneval-HumanEval_102_choose_num.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 { // This function takes two positive numbers x and y and returns the // biggest even integer number that is in the range [x, y] inclusive. If // there's no such number, then the function should return -1. // For example: // >>> chooseNum((12l), (15l)) // (14l) // >>> chooseNum((13l), (12l)) // (-1l) public static long chooseNum(long x, long y) { long chosen = -1;
if (i % 2 == 0) { chosen = i; } } return chosen; } }
for (long i = x; i <= y; i++) {
} public static void main(String[] args) { assert(chooseNum((12l), (15l)) == (14l)); assert(chooseNum((13l), (12l)) == (-1l)); assert(chooseNum((33l), (12354l)) == (12354l)); assert(chooseNum((5234l), (5233l)) == (-1l)); assert(chooseNum((6l), (29l)) == (28l)); assert(chooseNum((27l), (10l)) == (-1l)); assert(chooseNum((7l), (7l)) == (-1l)); assert(chooseNum((546l), (546l)) == (546l)); } }
humaneval-HumanEval_144_simplify.json-L19
js
//Your task is to implement a function that will simplify the expression // x * n. The function returns true if x * n evaluates to a whole number and false // otherwise. Both x and n, are string representation of a fraction, and have the following format, // <numerator>/<denominator> where both numerator and denominator are positive whole numbers. // You can assume that x, and n are valid fractions, and do not have zero as denominator. // >>> simplify("1/5", "5/1") // true // >>> simplify("1/6", "2/1") // false // >>> simplify("7/10", "10/2") // false function simplify(x, n){ let xNumerator = parseInt(x.split('/')[0]); let xDenominator = parseInt(x.split('/')[1]); let nNumerator = parseInt(n.split('/')[0]); let nDenominator = parseInt(n.split('/')[1]); let xTimesN = xNumerator * nNumerator / (xDenominator * nDenominator); return Number.isInteger(xTimesN);
}
const assert = require('node:assert'); function test() { let candidate = simplify; assert.deepEqual(candidate("1/5", "5/1"),true); assert.deepEqual(candidate("1/6", "2/1"),false); assert.deepEqual(candidate("5/1", "3/1"),true); assert.deepEqual(candidate("7/10", "10/2"),false); assert.deepEqual(candidate("2/10", "50/10"),true); assert.deepEqual(candidate("7/2", "4/2"),true); assert.deepEqual(candidate("11/6", "6/1"),true); assert.deepEqual(candidate("2/3", "5/2"),false); assert.deepEqual(candidate("5/2", "3/5"),false); assert.deepEqual(candidate("2/4", "8/4"),true); assert.deepEqual(candidate("2/4", "4/2"),true); assert.deepEqual(candidate("1/5", "5/1"),true); assert.deepEqual(candidate("1/5", "1/5"),false); } test();
humaneval-HumanEval_86_anti_shuffle.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that 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.deleteCharAt(sb.length() - 1); return sb.toString(); } }
sb.append(" ");
} 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_39_prime_fib.json-L34
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;
b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
a = a + b;
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_24_largest_divisor.json-L12
js
//For a given number n, find the largest number that divides n evenly, smaller than n // >>> largest_divisor(15) // 5 function largest_divisor(n){ let ld = 0; for(i=1; i<n; i++){ if(n%i===0){ if(i>ld){ ld = i; } }
return ld; }
}
const assert = require('node:assert'); function test() { let candidate = largest_divisor; assert.deepEqual(candidate(3),1); assert.deepEqual(candidate(7),1); assert.deepEqual(candidate(10),5); assert.deepEqual(candidate(100),50); assert.deepEqual(candidate(49),7); } test();
humaneval-HumanEval_114_minSubArraySum.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of integers nums, find the minimum sum of any non-empty sub-array array list // of nums. // Example // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) // (1l) // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) // (-6l) public static long minSubArraySum(ArrayList<Long> nums) { long minSum = Long.MAX_VALUE; long prevMinSum = Long.MAX_VALUE; for (int i = 0; i < nums.size(); i++) { long currSum = nums.get(i); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum; } for (int j = i + 1; j < nums.size(); j++) { currSum += nums.get(j); if (currSum < prevMinSum) { prevMinSum = currSum;
if (currSum < minSum) { minSum = currSum; } } } return minSum; } }
}
} public static void main(String[] args) { assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) == (1l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)2l, (long)-10l)))) == (-14l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-9999999999999999l)))) == (-9999999999999999l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)0l, (long)10l, (long)20l, (long)1000000l)))) == (0l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)10l, (long)11l, (long)13l, (long)8l, (long)3l, (long)4l)))) == (3l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-33l, (long)32l, (long)-1l, (long)0l, (long)-2l)))) == (-33l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-10l)))) == (-10l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)7l)))) == (7l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l)))) == (-1l)); } }
humaneval-HumanEval_93_encode.json-L19
js
//Write a function that takes a message, and encodes in such a // way that it swaps case of all letters, replaces all vowels in // the message with the letter that appears 2 places ahead of that // vowel in the english alphabet. // Assume only letters. // Examples: // >>> encode("test") // "TGST" // >>> encode("This is a message") // "tHKS KS C MGSSCGG" function encode(message){ const vowels = "aeiou"; let result = ""; for(let i = 0; i < message.length; i++){ let letter = message[i]; if(vowels.includes(letter.toLowerCase())){ let newIndex = (letter.charCodeAt(0) + 2 - (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))) % 26; letter = String.fromCharCode(newIndex + (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0)));
result += letter.toUpperCase() === letter ? letter.toLowerCase() : letter.toUpperCase(); } return result; }
}
const assert = require('node:assert'); function test() { let candidate = encode; assert.deepEqual(candidate("TEST"),"tgst"); assert.deepEqual(candidate("Mudasir"),"mWDCSKR"); assert.deepEqual(candidate("YES"),"ygs"); assert.deepEqual(candidate("This is a message"),"tHKS KS C MGSSCGG"); assert.deepEqual(candidate("I DoNt KnOw WhAt tO WrItE"),"k dQnT kNqW wHcT Tq wRkTg"); } test();
humaneval-HumanEval_63_fibfib.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 { // The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib((1l)) // (0l) // >>> fibfib((5l)) // (4l) // >>> fibfib((8l)) // (24l) public static long fibfib(long n) { if (n == 0) { return 0; } if (n == 1) { return 0; } if (n == 2) {
} long[] memo = new long[(int) n + 1]; memo[0] = 0; memo[1] = 0; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 1] + memo[i - 2] + memo[i - 3]; } return memo[(int) n]; } }
return 1;
} public static void main(String[] args) { assert(fibfib((2l)) == (1l)); assert(fibfib((1l)) == (0l)); assert(fibfib((5l)) == (4l)); assert(fibfib((8l)) == (24l)); assert(fibfib((10l)) == (81l)); assert(fibfib((12l)) == (274l)); assert(fibfib((14l)) == (927l)); } }