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_114_minSubArraySum.json-L13 | js | //Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// >>> minSubArraySum([2, 3, 4, 1, 2, 4])
// 1
// >>> minSubArraySum([-1, -2, -3])
// -6
function minSubArraySum(nums){
let sum = 0;
let minSum = nums[0];
for(let i = 0; i < nums.length; i++){
sum += nums[i]; | minSum = sum;
}
if(sum > 0){
sum = 0;
}
}
return minSum;
}
| if(sum < minSum){ | const assert = require('node:assert');
function test() {
let candidate = minSubArraySum;
assert.deepEqual(candidate([2, 3, 4, 1, 2, 4]),1);
assert.deepEqual(candidate([-1, -2, -3]),-6);
assert.deepEqual(candidate([-1, -2, -3, 2, -10]),-14);
assert.deepEqual(candidate([-9999999999999999]),-9999999999999999);
assert.deepEqual(candidate([0, 10, 20, 1000000]),0);
assert.deepEqual(candidate([-1, -2, -3, 10, -5]),-6);
assert.deepEqual(candidate([100, -1, -2, -3, 10, -5]),-6);
assert.deepEqual(candidate([10, 11, 13, 8, 3, 4]),3);
assert.deepEqual(candidate([100, -33, 32, -1, 0, -2]),-33);
assert.deepEqual(candidate([-10]),-10);
assert.deepEqual(candidate([7]),7);
assert.deepEqual(candidate([1, -1]),-1);
}
test(); |
humaneval-HumanEval_93_encode.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 {
// 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[] vowels = "AEIOUaeiou".toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Arrays.binarySearch(vowels, arr[i]) > -1) {
arr[i] = (char) (arr[i] + 2);
}
if (Character.isUpperCase(arr[i])) {
arr[i] = Character.toLowerCase(arr[i]);
} else {
arr[i] = Character.toUpperCase(arr[i]);
}
}
return new String(arr);
}
} | char[] arr = message.toCharArray(); | }
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_41_car_race_collision.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 {
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
public static long carRaceCollision(long n) {
| BigInteger nSquared = nBigInteger.multiply(nBigInteger);
return nSquared.longValue();
}
} | BigInteger nBigInteger = BigInteger.valueOf(n); | }
public static void main(String[] args) {
assert(carRaceCollision((2l)) == (4l));
assert(carRaceCollision((3l)) == (9l));
assert(carRaceCollision((4l)) == (16l));
assert(carRaceCollision((8l)) == (64l));
assert(carRaceCollision((10l)) == (100l));
}
}
|
humaneval-HumanEval_119_match_parens.json-L42 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given an array array list of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")"))))
// ("Yes")
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")"))))
// ("No")
public static String matchParens(ArrayList<String> lst) {
String s1 = lst.get(0);
String s2 = lst.get(1);
String s3 = s1+s2;
String s4 = s2+s1;
int c1 = 0;
int c2 = 0;
for (int i = 0; i < s3.length(); i++) {
if (s3.charAt(i) == '(') c1 += 1;
else c1 -= 1;
if (c1 < 0) break;
}
for (int i = 0; i < s4.length(); i++) {
if (s4.charAt(i) == '(') c2 += 1;
else c2 -= 1;
if (c2 < 0) break;
}
if (c1 == 0 || c2 == 0) return "Yes";
else return "No";
} | } | }
public static void main(String[] args) {
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes")));
}
}
|
|
humaneval-HumanEval_61_correct_bracketing.json-L18 | py | def correct_bracketing(brackets: str) -> bool:
""" brackets is a string of "(" and ")".
return True if every opening bracket has a corresponding closing bracket.
>>> correct_bracketing('(')
False
>>> correct_bracketing('()')
True
>>> correct_bracketing('(()())')
True
>>> correct_bracketing(')(()')
False
"""
count = 0
for char in brackets:
if char == '(':
count += 1 | count -= 1
if count < 0:
return False
return count == 0
| elif char == ')': | def check(candidate):
assert candidate('()') == True
assert candidate('(()())') == True
assert candidate('()()(()())()') == True
assert candidate('()()((()()())())(()()(()))') == True
assert candidate('((()())))') == False
assert candidate(')(()') == False
assert candidate('(') == False
assert candidate('((((') == False
assert candidate(')') == False
assert candidate('(()') == False
assert candidate('()()(()())())(()') == False
assert candidate('()()(()())()))()') == False
def test_check():
check(correct_bracketing)
test_check()
|
humaneval-HumanEval_107_even_odd_palindrome.json-L18 | 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 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];
} | var isPalindrome = function(x){ | 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_118_get_closest_vowel.json-L34 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// >>> getClosestVowel(("yogurt"))
// ("u")
// >>> getClosestVowel(("FULL"))
// ("U")
// >>> getClosestVowel(("quick"))
// ("")
// >>> getClosestVowel(("ab"))
// ("")
public static String getClosestVowel(String word) {
final String vowels = "aeiou";
final String consonants = "bcdfghjklmnpqrstvwxyz";
List<Integer> idx = new ArrayList<>();
word = word.toLowerCase();
for (int i = 0; i < word.length(); i++) {
if (vowels.indexOf(word.charAt(i)) != -1) {
idx.add(i);
}
}
for (int i = idx.size() - 1; i >= 0; i--) { | if (j == 0 || j == word.length() - 1) continue;
char left = word.charAt(j - 1);
char right = word.charAt(j + 1);
if (consonants.indexOf(left) != -1 && consonants.indexOf(right) != -1) {
return String.valueOf(word.charAt(j));
}
}
return "";
}
} | int j = idx.get(i); | }
public static void main(String[] args) {
assert(getClosestVowel(("yogurt")).equals(("u")));
assert(getClosestVowel(("full")).equals(("u")));
assert(getClosestVowel(("easy")).equals(("")));
assert(getClosestVowel(("eAsy")).equals(("")));
assert(getClosestVowel(("ali")).equals(("")));
assert(getClosestVowel(("bad")).equals(("a")));
assert(getClosestVowel(("most")).equals(("o")));
assert(getClosestVowel(("ab")).equals(("")));
assert(getClosestVowel(("ba")).equals(("")));
assert(getClosestVowel(("quick")).equals(("")));
assert(getClosestVowel(("anime")).equals(("i")));
assert(getClosestVowel(("Asia")).equals(("")));
assert(getClosestVowel(("Above")).equals(("o")));
}
}
|
humaneval-HumanEval_113_odd_count.json-L27 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given an array array list of strings, where each string consists of only digits, return an array array list.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// >>> oddCount((new ArrayList<String>(Arrays.asList((String)"1234567"))))
// (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput.")))
// >>> oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111"))))
// (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput.")))
public static ArrayList<String> oddCount(ArrayList<String> lst) {
ArrayList<String> res = new ArrayList<String>();
for (int i = 0; i < lst.size(); i++) {
int count = 0;
for (int j = 0; j < lst.get(i).length(); j++) {
if (Integer.parseInt(lst.get(i).substring(j, j + 1)) % 2 == 1) {
count++;
}
}
res.add("the number of odd elements " + count + "n the str" + count + "ng " + count + " of the " + count + "nput."); | return res;
}
} | } | }
public static void main(String[] args) {
assert(oddCount((new ArrayList<String>(Arrays.asList((String)"1234567")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput.")))));
assert(oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput.")))));
assert(oddCount((new ArrayList<String>(Arrays.asList((String)"271", (String)"137", (String)"314")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 2n the str2ng 2 of the 2nput.", (String)"the number of odd elements 3n the str3ng 3 of the 3nput.", (String)"the number of odd elements 2n the str2ng 2 of the 2nput.")))));
}
}
|
humaneval-HumanEval_158_find_max.json-L28 | 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 = 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;
} | max_unique_word = 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_70_strange_sort_list.json-L22 | py | from typing import List
def strange_sort_list(lst: List[int]) -> List[int]:
"""
Given list of integers, return 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:
>>> 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([])
[]
"""
lst = sorted(lst)
out = []
while lst:
out.append(lst.pop(0))
if not lst: | out.append(lst.pop())
return out | break | def check(candidate):
assert candidate([1, 2, 3, 4]) == [1, 4, 2, 3]
assert candidate([5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]
assert candidate([1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]
assert candidate([5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]
assert candidate([5, 5, 5, 5]) == [5, 5, 5, 5]
assert candidate([]) == []
assert candidate([1, 2, 3, 4, 5, 6, 7, 8]) == [1, 8, 2, 7, 3, 6, 4, 5]
assert candidate([0, 2, 2, 2, 5, 5, -5, -5]) == [-5, 5, -5, 5, 0, 2, 2, 2]
assert candidate([111111]) == [111111]
def test_check():
check(strange_sort_list)
test_check()
|
humaneval-HumanEval_47_median.json-L24 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Return median of elements in the array list l.
// >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l))))
// (float)3l
// >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l))))
// (15.0f)
public static float median(ArrayList<Long> l) {
float ret = 0;
Collections.sort(l);
int size = l.size();
if (size % 2 == 0) {
ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f;
} else {
ret = l.get(size / 2);
}
return ret; | } | } | }
public static void main(String[] args) {
assert(median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) == (float)3l);
assert(median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) == (8.0f));
assert(median((new ArrayList<Long>(Arrays.asList((long)5l)))) == (float)5l);
assert(median((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l)))) == (5.5f));
assert(median((new ArrayList<Long>(Arrays.asList((long)8l, (long)1l, (long)3l, (long)9l, (long)9l, (long)2l, (long)7l)))) == (float)7l);
}
}
|
humaneval-HumanEval_82_prime_length.json-L15 | js | //Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// >>> prime_length("Hello")
// true
// >>> prime_length("abcdcba")
// true
// >>> prime_length("kittens")
// true
// >>> prime_length("orange")
// false
function prime_length(string){
let length = string.length;
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]; | return true;
} else {
return false;
}
} | if (primes.includes(length)){ | const assert = require('node:assert');
function test() {
let candidate = prime_length;
assert.deepEqual(candidate("Hello"),true);
assert.deepEqual(candidate("abcdcba"),true);
assert.deepEqual(candidate("kittens"),true);
assert.deepEqual(candidate("orange"),false);
assert.deepEqual(candidate("wow"),true);
assert.deepEqual(candidate("world"),true);
assert.deepEqual(candidate("MadaM"),true);
assert.deepEqual(candidate("Wow"),true);
assert.deepEqual(candidate(""),false);
assert.deepEqual(candidate("HI"),true);
assert.deepEqual(candidate("go"),true);
assert.deepEqual(candidate("gogo"),false);
assert.deepEqual(candidate("aaaaaaaaaaaaaaa"),false);
assert.deepEqual(candidate("Madam"),true);
assert.deepEqual(candidate("M"),false);
assert.deepEqual(candidate("0"),false);
}
test(); |
humaneval-HumanEval_154_cycpattern_check.json-L31 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// >>> cycpatternCheck(("abcd"), ("abd"))
// (false)
// >>> cycpatternCheck(("hello"), ("ell"))
// (true)
// >>> cycpatternCheck(("whassup"), ("psus"))
// (false)
// >>> cycpatternCheck(("abab"), ("baa"))
// (true)
// >>> cycpatternCheck(("efef"), ("eeff"))
// (false)
// >>> cycpatternCheck(("himenss"), ("simen"))
// (true)
public static boolean cycpatternCheck(String a, String b) {
int len = b.length();
boolean found = false;
for (int i = 0; i < len; i++) {
b = b.substring(1) + b.charAt(0);
found = a.contains(b);
if (found) break;
}
return found; | } | } | }
public static void main(String[] args) {
assert(cycpatternCheck(("xyzw"), ("xyw")) == (false));
assert(cycpatternCheck(("yello"), ("ell")) == (true));
assert(cycpatternCheck(("whattup"), ("ptut")) == (false));
assert(cycpatternCheck(("efef"), ("fee")) == (true));
assert(cycpatternCheck(("abab"), ("aabb")) == (false));
assert(cycpatternCheck(("winemtt"), ("tinem")) == (true));
}
}
|
humaneval-HumanEval_161_solve.json-L40 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// >>> solve(("1234"))
// ("4321")
// >>> solve(("ab"))
// ("AB")
// >>> solve(("#a@C"))
// ("#A@c")
public static String solve(String s) {
boolean letterNotFound = true;
StringBuilder sb = new StringBuilder();
if (s.length() == 0) return s;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i))) {
letterNotFound = false;
if (Character.isUpperCase(s.charAt(i))) {
sb.append(Character.toLowerCase(s.charAt(i)));
} else {
sb.append(Character.toUpperCase(s.charAt(i)));
}
} else {
sb.append(s.charAt(i));
}
}
if (letterNotFound) {
return sb.reverse().toString();
} | }
} | return sb.toString(); | }
public static void main(String[] args) {
assert(solve(("AsDf")).equals(("aSdF")));
assert(solve(("1234")).equals(("4321")));
assert(solve(("ab")).equals(("AB")));
assert(solve(("#a@C")).equals(("#A@c")));
assert(solve(("#AsdfW^45")).equals(("#aSDFw^45")));
assert(solve(("#6@2")).equals(("2@6#")));
assert(solve(("#$a^D")).equals(("#$A^d")));
assert(solve(("#ccc")).equals(("#CCC")));
}
}
|
humaneval-HumanEval_150_x_or_y.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 {
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// >>> xOrY((7l), (34l), (12l))
// (34l)
// >>> xOrY((15l), (8l), (5l))
// (5l)
public static long xOrY(long n, long x, long y) {
BigInteger nBig = BigInteger.valueOf(n);
if (nBig.isProbablePrime(100)) {
return x;
} else {
return y; | }
} | } | }
public static void main(String[] args) {
assert(xOrY((7l), (34l), (12l)) == (34l));
assert(xOrY((15l), (8l), (5l)) == (5l));
assert(xOrY((3l), (33l), (5212l)) == (33l));
assert(xOrY((1259l), (3l), (52l)) == (3l));
assert(xOrY((7919l), (-1l), (12l)) == (-1l));
assert(xOrY((3609l), (1245l), (583l)) == (583l));
assert(xOrY((91l), (56l), (129l)) == (129l));
assert(xOrY((6l), (34l), (1234l)) == (1234l));
assert(xOrY((1l), (2l), (0l)) == (0l));
assert(xOrY((2l), (2l), (0l)) == (2l));
}
}
|
humaneval-HumanEval_11_string_xor.json-L24 | js | //Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// >>> string_xor("010", "110")
// "100"
function string_xor(a, b){
var arrayA = [];
var arrayB = [];
var arrayXOR = [];
var result = '';
for (var i = 0; i < a.length; i++) {
arrayA.push(parseInt(a[i]));
}
for (var j = 0; j < b.length; j++) {
arrayB.push(parseInt(b[j]));
}
for (var k = 0; k < arrayA.length; k++) {
if (arrayA[k] !== arrayB[k]) {
arrayXOR.push(1);
}
else {
arrayXOR.push(0);
}
} | return result;
} | result = arrayXOR.join(''); | const assert = require('node:assert');
function test() {
let candidate = string_xor;
assert.deepEqual(candidate("111000", "101010"),"010010");
assert.deepEqual(candidate("1", "1"),"0");
assert.deepEqual(candidate("0101", "0000"),"0101");
}
test(); |
humaneval-HumanEval_19_sort_numbers.json-L7 | js | //Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// >>> sort_numbers("three one five")
// "one three five"
function sort_numbers(numbers){
| var numMap = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9
};
numString.sort(function(a, b){
return numMap[a] - numMap[b];
});
numString = numString.join(" ");
return numString;
} | var numString = numbers.split(" "); | const assert = require('node:assert');
function test() {
let candidate = sort_numbers;
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("three"),"three");
assert.deepEqual(candidate("three five nine"),"three five nine");
assert.deepEqual(candidate("five zero four seven nine eight"),"zero four five seven eight nine");
assert.deepEqual(candidate("six five four three two one zero"),"zero one two three four five six");
}
test(); |
humaneval-HumanEval_156_int_to_mini_roman.json-L15 | 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'
"""
| 1000: 'm',
900: 'cm',
500: 'd',
400: 'cd',
100: 'c',
90: 'xc',
50: 'l',
40: 'xl',
10: 'x',
9: 'ix',
5: 'v',
4: 'iv',
1: 'i'
}
roman_numeral = ''
for key in sorted(roman_numerals.keys(), reverse=True):
roman_numeral += roman_numerals[key] * (number // key)
number = number % key
return roman_numeral
| roman_numerals = { | 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_87_get_row.json-L22 | py | from typing import List, Tuple
def get_row(lst: List[List[int]], x: int) -> List[Tuple[int, int]]:
"""
You are given a 2 dimensional data, as a nested lists,
which is similar to matrix, however, unlike matrices,
each row may contain a different number of columns.
Given lst, and integer x, find integers x in the list,
and return list of tuples, [(x1, y1), (x2, y2) ...] such that
each tuple is a coordinate - (row, columns), starting with 0.
Sort coordinates initially by rows in ascending order.
Also, sort coordinates of the row by columns in descending order.
Examples:
>>> get_row([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1)
[(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
>>> get_row([], 1)
[]
>>> get_row([[], [1], [1, 2, 3]], 3)
[(2, 2)]
"""
| res.sort(key=lambda t: (t[0], -t[1]))
return res
| res = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x] | def check(candidate):
assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 2) == [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
assert candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 1, 3, 4, 5, 6], [1, 2, 1, 4, 5, 6], [1, 2, 3, 1, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) == [(0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0)]
assert candidate([], 1) == []
assert candidate([[1]], 2) == []
assert candidate([[], [1], [1, 2, 3]], 3) == [(2, 2)]
def test_check():
check(get_row)
test_check()
|
humaneval-HumanEval_39_prime_fib.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 {
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// >>> primeFib((1l))
// (2l)
// >>> primeFib((2l))
// (3l)
// >>> primeFib((3l))
// (5l)
// >>> primeFib((4l))
// (13l)
// >>> primeFib((5l))
// (89l)
public static long primeFib(long n) {
long fib = 1;
long prev = 0;
long count = 0;
while (count != n) {
long tmp = fib;
fib += prev;
prev = tmp;
if (BigInteger.valueOf(fib).isProbablePrime(1)) {
count++;
}
}
return fib; | } | } | }
public static void main(String[] args) {
assert(primeFib((1l)) == (2l));
assert(primeFib((2l)) == (3l));
assert(primeFib((3l)) == (5l));
assert(primeFib((4l)) == (13l));
assert(primeFib((5l)) == (89l));
assert(primeFib((6l)) == (233l));
assert(primeFib((7l)) == (1597l));
assert(primeFib((8l)) == (28657l));
assert(primeFib((9l)) == (514229l));
assert(primeFib((10l)) == (433494437l));
}
}
|
humaneval-HumanEval_59_largest_prime_factor.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 the largest prime factor of n. Assume n > 1 and is not a prime.
// >>> largestPrimeFactor((13195l))
// (29l)
// >>> largestPrimeFactor((2048l))
// (2l)
public static long largestPrimeFactor(long n) {
List<Long> primes = new ArrayList<>(); | for (long i = 2; i * i <= x; i++) {
if (x % i == 0) {
primes.add(i);
x /= i;
i--;
}
}
if (x > 1) {
primes.add(x);
}
return primes.get(primes.size() - 1);
}
} | long x = n; | }
public static void main(String[] args) {
assert(largestPrimeFactor((15l)) == (5l));
assert(largestPrimeFactor((27l)) == (3l));
assert(largestPrimeFactor((63l)) == (7l));
assert(largestPrimeFactor((330l)) == (11l));
assert(largestPrimeFactor((13195l)) == (29l));
}
}
|
humaneval-HumanEval_39_prime_fib.json-L24 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// >>> primeFib((1l))
// (2l)
// >>> primeFib((2l))
// (3l)
// >>> primeFib((3l))
// (5l)
// >>> primeFib((4l))
// (13l)
// >>> primeFib((5l))
// (89l)
public static long primeFib(long n) {
long fib = 1;
long prev = 0;
long count = 0; | long tmp = fib;
fib += prev;
prev = tmp;
if (BigInteger.valueOf(fib).isProbablePrime(1)) {
count++;
}
}
return fib;
}
} | while (count != n) { | }
public static void main(String[] args) {
assert(primeFib((1l)) == (2l));
assert(primeFib((2l)) == (3l));
assert(primeFib((3l)) == (5l));
assert(primeFib((4l)) == (13l));
assert(primeFib((5l)) == (89l));
assert(primeFib((6l)) == (233l));
assert(primeFib((7l)) == (1597l));
assert(primeFib((8l)) == (28657l));
assert(primeFib((9l)) == (514229l));
assert(primeFib((10l)) == (433494437l));
}
}
|
humaneval-HumanEval_128_prod_signs.json-L28 | js | //You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return undefined for empty arr.
// Example:
// >>> prod_signs([1, 2, 2, -4])
// 9
// >>> prod_signs([0, 1])
// 0
// >>> prod_signs([])
// undefined
function prod_signs(arr){
var total = 0;
var len = arr.length;
var pro = 1;
if(len == 0){
return undefined;
}
else{
for(var i = 0; i < len; i++){
total += Math.abs(arr[i]);
if(arr[i] < 0){
pro *= -1;
}
else if(arr[i] == 0){
pro *= 0;
} | total *= pro;
return total;
}
}
| } | const assert = require('node:assert');
function test() {
let candidate = prod_signs;
assert.deepEqual(candidate([1, 2, 2, -4]),-9);
assert.deepEqual(candidate([0, 1]),0);
assert.deepEqual(candidate([1, 1, 1, 2, 3, -1, 1]),-10);
assert.deepEqual(candidate([]),undefined);
assert.deepEqual(candidate([2, 4, 1, 2, -1, -1, 9]),20);
assert.deepEqual(candidate([-1, 1, -1, 1]),4);
assert.deepEqual(candidate([-1, 1, 1, 1]),-4);
assert.deepEqual(candidate([-1, 1, 1, 0]),0);
}
test(); |
humaneval-HumanEval_154_cycpattern_check.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 {
// 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
// >>> cycpatternCheck(("abcd"), ("abd"))
// (false)
// >>> cycpatternCheck(("hello"), ("ell"))
// (true)
// >>> cycpatternCheck(("whassup"), ("psus"))
// (false)
// >>> cycpatternCheck(("abab"), ("baa"))
// (true)
// >>> cycpatternCheck(("efef"), ("eeff"))
// (false)
// >>> cycpatternCheck(("himenss"), ("simen"))
// (true)
public static boolean cycpatternCheck(String a, String b) {
int len = b.length();
boolean found = false;
for (int i = 0; i < len; i++) {
b = b.substring(1) + b.charAt(0); | if (found) break;
}
return found;
}
} | found = a.contains(b); | }
public static void main(String[] args) {
assert(cycpatternCheck(("xyzw"), ("xyw")) == (false));
assert(cycpatternCheck(("yello"), ("ell")) == (true));
assert(cycpatternCheck(("whattup"), ("ptut")) == (false));
assert(cycpatternCheck(("efef"), ("fee")) == (true));
assert(cycpatternCheck(("abab"), ("aabb")) == (false));
assert(cycpatternCheck(("winemtt"), ("tinem")) == (true));
}
}
|
humaneval-HumanEval_118_get_closest_vowel.json-L25 | js | //You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// >>> get_closest_vowel("yogurt")
// "u"
// >>> get_closest_vowel("FULL")
// "U"
// >>> get_closest_vowel("quick")
// ""
// >>> get_closest_vowel("ab")
// ""
function get_closest_vowel(word){
let vowels = ["a", "e", "i", "o", "u"];
let i = word.length - 1;
let result = [];
if (word.length === 1) {
return ""
} else {
while (i >= 0) {
if (vowels.includes(word[i])) {
if (i > 0 && i < word.length - 1) { | result.push(word[i]);
}
}
}
i--;
}
if (result.length === 0) {
return ""
} else {
return result[0];
}
}
} | if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) { | const assert = require('node:assert');
function test() {
let candidate = get_closest_vowel;
assert.deepEqual(candidate("yogurt"),"u");
assert.deepEqual(candidate("full"),"u");
assert.deepEqual(candidate("easy"),"");
assert.deepEqual(candidate("eAsy"),"");
assert.deepEqual(candidate("ali"),"");
assert.deepEqual(candidate("bad"),"a");
assert.deepEqual(candidate("most"),"o");
assert.deepEqual(candidate("ab"),"");
assert.deepEqual(candidate("ba"),"");
assert.deepEqual(candidate("quick"),"");
assert.deepEqual(candidate("anime"),"i");
assert.deepEqual(candidate("Asia"),"");
assert.deepEqual(candidate("Above"),"o");
}
test(); |
humaneval-HumanEval_86_anti_shuffle.json-L17 | js | //Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// >>> anti_shuffle("Hi")
// "Hi"
// >>> anti_shuffle("hello")
// "ehllo"
// >>> anti_shuffle("Hello World!!!")
// "Hello !!!Wdlor"
function anti_shuffle(s){
var result = [];
var strings = s.split(" ");
strings.forEach(function(str){ | temp.sort();
result.push(temp.join(""));
});
return result.join(" ");
} | var temp = str.split(""); | const assert = require('node:assert');
function test() {
let candidate = anti_shuffle;
assert.deepEqual(candidate("Hi"),"Hi");
assert.deepEqual(candidate("hello"),"ehllo");
assert.deepEqual(candidate("number"),"bemnru");
assert.deepEqual(candidate("abcd"),"abcd");
assert.deepEqual(candidate("Hello World!!!"),"Hello !!!Wdlor");
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("Hi. My name is Mister Robot. How are you?"),".Hi My aemn is Meirst .Rboot How aer ?ouy");
}
test(); |
humaneval-HumanEval_123_get_odd_collatz.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array list sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// >>> getOddCollatz((5l))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l)))
public static ArrayList<Long> getOddCollatz(long n) {
if (n <= 0) return new ArrayList<Long>();
HashSet<Long> odds = new HashSet<Long>();
long n1 = n;
while (n1 > 1) {
if (n1 % 2 == 1) odds.add(n1);
n1 = n1 % 2 == 0 ? n1 / 2 : 3 * n1 + 1;
} | Long[] odds_arr = odds.toArray(new Long[odds.size()]);
ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr));
Collections.sort(ans);
return ans;
}
} | odds.add(1l); | }
public static void main(String[] args) {
assert(getOddCollatz((14l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l)))));
assert(getOddCollatz((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l)))));
assert(getOddCollatz((12l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l)))));
assert(getOddCollatz((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l)))));
}
}
|
humaneval-HumanEval_14_all_prefixes.json-L10 | py | from typing import List
def all_prefixes(string: str) -> List[str]:
""" Return list of all prefixes from shortest to longest of the input string
>>> all_prefixes('abc')
['a', 'ab', 'abc']
"""
prefixes = []
for i in range(len(string)): | return prefixes
| prefixes.append(string[:i+1]) | def check(candidate):
assert candidate('') == []
assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh']
assert candidate('WWW') == ['W', 'WW', 'WWW']
def test_check():
check(all_prefixes)
test_check()
|
humaneval-HumanEval_149_sorted_list_sum.json-L27 | 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;
} | return 1;
}
else{
if(a < b){
return -1;
}
else if(a > b){
return 1;
}
else{
return 0;
}
}
});
}
var a = ["aa", "a", "aaa"];
var b = ["ab", "a", "aaa", "cd"]; | else if(a.length > b.length){ | 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_83_starts_one_ends.json-L21 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
public static long startsOneEnds(long n) {
long lower = (long) Math.pow(10, n - 1);
long upper = (long) Math.pow(10, n) - 1;
long count = 0;
for (long i = lower; i <= upper; i++) {
String s = "" + i;
if (s.startsWith("1") || s.endsWith("1"))
count++;
}
return count; | } | } | }
public static void main(String[] args) {
assert(startsOneEnds((1l)) == (1l));
assert(startsOneEnds((2l)) == (18l));
assert(startsOneEnds((3l)) == (180l));
assert(startsOneEnds((4l)) == (1800l));
assert(startsOneEnds((5l)) == (18000l));
}
}
|
humaneval-HumanEval_39_prime_fib.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 {
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// >>> primeFib((1l))
// (2l)
// >>> primeFib((2l))
// (3l)
// >>> primeFib((3l))
// (5l)
// >>> primeFib((4l))
// (13l)
// >>> primeFib((5l))
// (89l)
public static long primeFib(long n) {
long fib = 1;
long prev = 0;
long count = 0;
while (count != n) {
long tmp = fib;
fib += prev;
prev = tmp;
if (BigInteger.valueOf(fib).isProbablePrime(1)) { | }
}
return fib;
}
} | count++; | }
public static void main(String[] args) {
assert(primeFib((1l)) == (2l));
assert(primeFib((2l)) == (3l));
assert(primeFib((3l)) == (5l));
assert(primeFib((4l)) == (13l));
assert(primeFib((5l)) == (89l));
assert(primeFib((6l)) == (233l));
assert(primeFib((7l)) == (1597l));
assert(primeFib((8l)) == (28657l));
assert(primeFib((9l)) == (514229l));
assert(primeFib((10l)) == (433494437l));
}
}
|
humaneval-HumanEval_150_x_or_y.json-L17 | py | def x_or_y(n: int, x: int, y: int) -> int:
"""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
"""
if n < 2:
return y
for i in range(2, n):
if n % i == 0:
return y | return x | def check(candidate):
assert candidate(7, 34, 12) == 34
assert candidate(15, 8, 5) == 5
assert candidate(3, 33, 5212) == 33
assert candidate(1259, 3, 52) == 3
assert candidate(7919, -1, 12) == -1
assert candidate(3609, 1245, 583) == 583
assert candidate(91, 56, 129) == 129
assert candidate(6, 34, 1234) == 1234
assert candidate(1, 2, 0) == 0
assert candidate(2, 2, 0) == 2
def test_check():
check(x_or_y)
test_check()
|
|
humaneval-HumanEval_158_find_max.json-L36 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that accepts an array array list of strings.
// The array list contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string"))))
// ("string")
// >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game"))))
// ("enam")
// >>> findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc"))))
// ("aaaaaaa")
public static String findMax(ArrayList<String> words) {
Map<String, Integer> wordsToUniqueCharacters = new HashMap<String, Integer>();
for (String word : words) {
Set<Character> uniqueCharacters = new HashSet<Character>();
for (char c : word.toCharArray()) {
uniqueCharacters.add(c);
}
wordsToUniqueCharacters.put(word, uniqueCharacters.size());
}
words.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int compareResult = wordsToUniqueCharacters.get(o2).compareTo(wordsToUniqueCharacters.get(o1));
if (compareResult == 0) {
return o1.compareTo(o2);
}
return compareResult; | });
return words.get(0);
}
} | } | }
public static void main(String[] args) {
assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))).equals(("string")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))).equals(("enam")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))).equals(("aaaaaaa")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"abc", (String)"cba")))).equals(("abc")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"this", (String)"game", (String)"of", (String)"footbott")))).equals(("footbott")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"gonna", (String)"rock")))).equals(("gonna")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"a", (String)"mad", (String)"nation")))).equals(("nation")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"this", (String)"is", (String)"a", (String)"prrk")))).equals(("this")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"b")))).equals(("b")));
assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"play", (String)"play")))).equals(("play")));
}
}
|
humaneval-HumanEval_33_sort_third.json-L46 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// This function takes an array array list l and returns an array array list l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))
// >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l)))
public static ArrayList<Long> sortThird(ArrayList<Long> l) {
ArrayList<Long> l_r = new ArrayList<Long>();
ArrayList<Long> l_e = new ArrayList<Long>();
ArrayList<Long> l_s = new ArrayList<Long>();
for (int i = 0; i < l.size(); i++) {
if (i % 3 == 0) {
l_e.add(l.get(i));
} else {
l_r.add(l.get(i));
}
}
for (int i = 0; i < l_e.size(); i++) {
long min = l_e.get(i);
for (int j = i; j < l_e.size(); j++) {
if (l_e.get(j) < min) {
min = l_e.get(j);
l_e.set(j, l_e.get(i));
l_e.set(i, min);
}
}
}
int j = 0;
for (int i = 0; i < l.size(); i++) {
if (i % 3 == 0) {
l_s.add(l_e.get(j));
j++;
} else {
l_s.add(l_r.get(i - j));
}
} | }
} | return l_s; | }
public static void main(String[] args) {
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l)))));
}
}
|
humaneval-HumanEval_126_is_sorted.json-L23 | js | //Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// >>> is_sorted([5])
// true
// >>> is_sorted([1, 2, 3, 4, 5])
// true
// >>> is_sorted([1, 3, 2, 4, 5])
// false
// >>> is_sorted([1, 2, 3, 4, 5, 6])
// true
// >>> is_sorted([1, 2, 3, 4, 5, 6, 7])
// true
// >>> is_sorted([1, 3, 2, 4, 5, 6, 7])
// false
// >>> is_sorted([1, 2, 2, 3, 3, 4])
// true
// >>> is_sorted([1, 2, 2, 2, 3, 4])
// false
function is_sorted(lst){
var last = null; | for (var x of lst){
if (last == null){
last = x;
} else if (x < last){
return false;
} else if (x == last){
if (dupe_found){
return false;
} else {
dupe_found = true;
}
} else {
last = x;
dupe_found = false;
}
}
return true;
}
| var dupe_found = false; | const assert = require('node:assert');
function test() {
let candidate = is_sorted;
assert.deepEqual(candidate([5]),true);
assert.deepEqual(candidate([1, 2, 3, 4, 5]),true);
assert.deepEqual(candidate([1, 3, 2, 4, 5]),false);
assert.deepEqual(candidate([1, 2, 3, 4, 5, 6]),true);
assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7]),true);
assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, 7]),false);
assert.deepEqual(candidate([]),true);
assert.deepEqual(candidate([1]),true);
assert.deepEqual(candidate([3, 2, 1]),false);
assert.deepEqual(candidate([1, 2, 2, 2, 3, 4]),false);
assert.deepEqual(candidate([1, 2, 3, 3, 3, 4]),false);
assert.deepEqual(candidate([1, 2, 2, 3, 3, 4]),true);
assert.deepEqual(candidate([1, 2, 3, 4]),true);
}
test(); |
humaneval-HumanEval_1_separate_paren_groups.json-L18 | py | from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separate_paren_groups('( ) (( )) (( )( ))')
['()', '(())', '(()())']
"""
paren_string = paren_string.replace(' ', '')
groups = []
group = ''
open_count = 0
for c in paren_string:
if c == '(':
open_count += 1 | open_count -= 1
group += c
if open_count == 0:
groups.append(group)
group = ''
return groups
| elif c == ')': | def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())']
assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))']
assert candidate('(()(())((())))') == ['(()(())((())))']
assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())']
def test_check():
check(separate_paren_groups)
test_check()
|
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L22 | py | def check_if_last_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the last character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_last_char_is_a_letter('apple pie')
False
>>> check_if_last_char_is_a_letter('apple pi e')
True
>>> check_if_last_char_is_a_letter('apple pi e ')
False
>>> check_if_last_char_is_a_letter('')
False
"""
if len(txt) == 0:
return False
elif txt[-1].isalpha() and (len(txt) == 1 or not txt[-2].isalpha()):
return True | return False
| else: | def check(candidate):
assert candidate('apple') == False
assert candidate('apple pi e') == True
assert candidate('eeeee') == False
assert candidate('A') == True
assert candidate('Pumpkin pie ') == False
assert candidate('Pumpkin pie 1') == False
assert candidate('') == False
assert candidate('eeeee e ') == False
assert candidate('apple pie') == False
assert candidate('apple pi e ') == False
def test_check():
check(check_if_last_char_is_a_letter)
test_check()
|
humaneval-HumanEval_123_get_odd_collatz.json-L36 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array list sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// >>> getOddCollatz((5l))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l)))
public static ArrayList<Long> getOddCollatz(long n) {
if (n <= 0) return new ArrayList<Long>();
HashSet<Long> odds = new HashSet<Long>();
long n1 = n;
while (n1 > 1) {
if (n1 % 2 == 1) odds.add(n1);
n1 = n1 % 2 == 0 ? n1 / 2 : 3 * n1 + 1;
}
odds.add(1l);
Long[] odds_arr = odds.toArray(new Long[odds.size()]);
ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr));
Collections.sort(ans);
return ans;
} | } | }
public static void main(String[] args) {
assert(getOddCollatz((14l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l)))));
assert(getOddCollatz((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l)))));
assert(getOddCollatz((12l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l)))));
assert(getOddCollatz((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l)))));
}
}
|
|
humaneval-HumanEval_143_words_in_sentence.json-L34 | py | def words_in_sentence(sentence: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> words_in_sentence('This is a test')
'is'
Example 2:
>>> words_in_sentence('lets go for swimming')
'go for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
def is_prime(n: int) -> bool:
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
words = sentence.split()
prime_words = []
for word in words:
if is_prime(len(word)):
prime_words.append(word) | return ' '.join(prime_words) | def check(candidate):
assert candidate('This is a test') == 'is'
assert candidate('lets go for swimming') == 'go for'
assert candidate('there is no place available here') == 'there is no place'
assert candidate('Hi I am Hussein') == 'Hi am Hussein'
assert candidate('go for it') == 'go for it'
assert candidate('here') == ''
assert candidate('here is') == 'is'
def test_check():
check(words_in_sentence)
test_check()
|
|
humaneval-HumanEval_105_by_length.json-L29 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given an array array list of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array array list, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// >>> byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l))))
// (new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One")))
// If the array array list is empty, return an empty array array list:
// >>> byLength((new ArrayList<Long>(Arrays.asList())))
// (new ArrayList<String>(Arrays.asList()))
// If the array array list has any strange number ignore it:
// >>> byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l))))
// (new ArrayList<String>(Arrays.asList((String)"One")))
public static ArrayList<String> byLength(ArrayList<Long> arr) {
String[] a = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
ArrayList<String> res = new ArrayList<String>();
ArrayList<Long> good = new ArrayList<Long>();
for (Long i : arr) {
if (i >= 1 && i <= 9) {
good.add(i);
} | good.sort(new Comparator<Long>() {
public int compare(Long i1, Long i2) {
return i1.compareTo(i2);
}
});
Collections.reverse(good);
for (Long i : good) {
res.add(a[i.intValue() - 1]);
}
return res;
}
} | } | }
public static void main(String[] args) {
assert(byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))).equals((new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One")))));
assert(byLength((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList()))));
assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))).equals((new ArrayList<String>(Arrays.asList((String)"One")))));
assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)3l, (long)2l)))).equals((new ArrayList<String>(Arrays.asList((String)"Three", (String)"Two", (String)"One")))));
assert(byLength((new ArrayList<Long>(Arrays.asList((long)9l, (long)4l, (long)8l)))).equals((new ArrayList<String>(Arrays.asList((String)"Nine", (String)"Eight", (String)"Four")))));
}
}
|
humaneval-HumanEval_0_has_close_elements.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 {
// Check if in given array list of numbers, are any two numbers closer to each other than
// given threshold.
// >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f))), (0.5f))
// (false)
// >>> hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.8f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.3f))
// (true)
public static boolean hasCloseElements(ArrayList<Float> numbers, float threshold) {
Collections.sort(numbers);
for (int i = 0; i < numbers.size() - 1; i++) {
if (numbers.get(i+1) - numbers.get(i) < threshold) {
return true;
}
}
return false; | } | } | }
public static void main(String[] args) {
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.3f)) == (true));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.9f, (float)4.0f, (float)5.0f, (float)2.2f))), (0.05f)) == (false));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.95f)) == (true));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)5.9f, (float)4.0f, (float)5.0f))), (0.8f)) == (false));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f, (float)2.0f))), (0.1f)) == (true));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (1.0f)) == (true));
assert(hasCloseElements((new ArrayList<Float>(Arrays.asList((float)1.1f, (float)2.2f, (float)3.1f, (float)4.1f, (float)5.1f))), (0.5f)) == (false));
}
}
|
humaneval-HumanEval_91_is_bored.json-L17 | py | def is_bored(S: str) -> int:
"""
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:
>>> is_bored('Hello world')
0
>>> is_bored('The sky is blue. The sun is shining. I love this weather')
1
"""
boredoms = 0
sentences = S.split('.')
for sentence in sentences:
words = sentence.split() | boredoms += 1
return boredoms
| if words and words[0] == 'I': | def check(candidate):
assert candidate('Hello world') == 0
assert candidate('Is the sky blue?') == 0
assert candidate('I love It !') == 1
assert candidate('bIt') == 0
assert candidate('I feel good today. I will be productive. will kill It') == 2
assert candidate('You and I are going for a walk') == 0
def test_check():
check(is_bored)
test_check()
|
humaneval-HumanEval_143_words_in_sentence.json-L27 | py | def words_in_sentence(sentence: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> words_in_sentence('This is a test')
'is'
Example 2:
>>> words_in_sentence('lets go for swimming')
'go for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
def is_prime(n: int) -> bool:
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False |
words = sentence.split()
prime_words = []
for word in words:
if is_prime(len(word)):
prime_words.append(word)
return ' '.join(prime_words) | return True | def check(candidate):
assert candidate('This is a test') == 'is'
assert candidate('lets go for swimming') == 'go for'
assert candidate('there is no place available here') == 'there is no place'
assert candidate('Hi I am Hussein') == 'Hi am Hussein'
assert candidate('go for it') == 'go for it'
assert candidate('here') == ''
assert candidate('here is') == 'is'
def test_check():
check(words_in_sentence)
test_check()
|
humaneval-HumanEval_155_even_odd_count.json-L13 | 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)) | odd_count = 0
for ch in num_str:
digit = int(ch)
if digit % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
| even_count = 0 | 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_105_by_length.json-L33 | js | //Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// >>> by_length([2, 1, 1, 4, 5, 8, 2, 3])
// ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// If the array is empty, return an empty array:
// >>> by_length([])
// []
// If the array has any strange number ignore it:
// >>> by_length([1, -1, 55])
// ["One"]
function by_length(arr){
var arr2 = [];
for(var i = 0; i < arr.length; i++){
var num = arr[i];
if(num > 0 && num < 10){
arr2.push(num);
}
}
arr2.sort();
arr2.reverse();
var arr3 = [];
for(var i = 0; i < arr2.length; i++){
var num = arr2[i];
if(num == 1){
arr3.push("One");
}
else if(num == 2){
arr3.push("Two");
}
else if(num == 3){ | }
else if(num == 4){
arr3.push("Four");
}
else if(num == 5){
arr3.push("Five");
}
else if(num == 6){
arr3.push("Six");
}
else if(num == 7){
arr3.push("Seven");
}
else if(num == 8){
arr3.push("Eight");
}
else if(num == 9){
arr3.push("Nine");
}
}
return arr3;
} | arr3.push("Three"); | const assert = require('node:assert');
function test() {
let candidate = by_length;
assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]);
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([1, -1, 55]),["One"]);
assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]);
assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]);
}
test(); |
humaneval-HumanEval_131_digits.json-L29 | js | //Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// >>> digits(1)
// 1
// >>> digits(4)
// 0
// >>> digits(235)
// 15
function digits(n){
if(!n){
return "error";
}
if(n < 0){
return "error";
}
var temp = 0;
var prod = 1;
var odd = true;
for(n; n > 0; n = Math.floor(n/10)){
temp = n % 10;
if(temp % 2 != 0){
prod *= temp;
odd = false;
}
}
if(odd){
return 0; | return prod;
}
| } | const assert = require('node:assert');
function test() {
let candidate = digits;
assert.deepEqual(candidate(5),5);
assert.deepEqual(candidate(54),5);
assert.deepEqual(candidate(120),1);
assert.deepEqual(candidate(5014),5);
assert.deepEqual(candidate(98765),315);
assert.deepEqual(candidate(5576543),2625);
assert.deepEqual(candidate(2468),0);
}
test(); |
humaneval-HumanEval_33_sort_third.json-L48 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// This function takes an array array list l and returns an array array list l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))
// >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l)))
public static ArrayList<Long> sortThird(ArrayList<Long> l) {
ArrayList<Long> l_r = new ArrayList<Long>();
ArrayList<Long> l_e = new ArrayList<Long>();
ArrayList<Long> l_s = new ArrayList<Long>();
for (int i = 0; i < l.size(); i++) {
if (i % 3 == 0) {
l_e.add(l.get(i));
} else {
l_r.add(l.get(i));
}
}
for (int i = 0; i < l_e.size(); i++) {
long min = l_e.get(i);
for (int j = i; j < l_e.size(); j++) {
if (l_e.get(j) < min) {
min = l_e.get(j);
l_e.set(j, l_e.get(i));
l_e.set(i, min);
}
}
}
int j = 0;
for (int i = 0; i < l.size(); i++) {
if (i % 3 == 0) {
l_s.add(l_e.get(j));
j++;
} else {
l_s.add(l_r.get(i - j));
}
}
return l_s;
} | } | }
public static void main(String[] args) {
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l)))));
assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l)))));
}
}
|
|
humaneval-HumanEval_95_check_dict_case.json-L23 | js | //Given an object, return true if all keys are strings in lower
// case or all keys are strings in upper case, else return false.
// The function should return false is the given object is empty.
// Examples:
// >>> check_dict_case({"a": "apple", "b": "banana"})
// true
// >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"})
// false
// >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"})
// false
// >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"})
// false
// >>> check_dict_case({"STATE": "NC", "ZIP": "12345"})
// true
function check_dict_case(dict){
if (Object.keys(dict).length == 0){
return false;
}
var case_type = -1;
for (let key in dict){
if (typeof key == "string"){
if (case_type == -1){ | case_type = 1;
}
else if (key == key.toLowerCase()){
case_type = 0;
}
else{
return false;
}
}
else if (case_type == 1){
if (key != key.toUpperCase()){
return false;
}
}
else if (case_type == 0){
if (key != key.toLowerCase()){
return false;
}
}
}
else{
return false;
}
}
return true;
} | if (key == key.toUpperCase()){ | const assert = require('node:assert');
function test() {
let candidate = check_dict_case;
assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true);
assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false);
assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false);
assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false);
assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true);
assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true);
assert.deepEqual(candidate({}),false);
}
test(); |
humaneval-HumanEval_6_parse_nested_parens.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 {
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// >>> parseNestedParens(("(()()) ((())) () ((())()())"))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l)))
public static ArrayList<Long> parseNestedParens(String paren_string) {
ArrayList<Long> result = new ArrayList<Long>();
String[] paren_strings = paren_string.split(" ");
for (String paren : paren_strings) {
long max_depth = 0;
long current_depth = 0;
for (char c : paren.toCharArray()) {
if (c == '(') {
current_depth += 1;
max_depth = Math.max(max_depth, current_depth);
} else if (c == ')') {
current_depth -= 1;
} | result.add(max_depth);
}
return result;
}
} | } | }
public static void main(String[] args) {
assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l)))));
assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))));
assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l)))));
}
}
|
humaneval-HumanEval_36_fizz_buzz.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 {
// 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_39_prime_fib.json-L14 | 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){ | return number > 1;
}
else if(number % 2 == 0 || number % 3 == 0){
return false;
}
else{
for(var i = 5; i * i <= number; i += 6){
if(number % i == 0 || number % (i + 2) == 0){
return false;
}
}
return true;
}
}
function fib(num){
var a = 1, b = 0, temp;
while (num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
var res = 0;
var fibNum = 0;
while(res < n){
if(isPrime(fib(fibNum))){
res++;
}
fibNum++;
}
return fib(fibNum - 1);
} | if(number <= 3){ | 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_35_max_element.json-L13 | py | from typing import List
def max_element(l: List[int]) -> int:
"""Return maximum element in the list.
>>> max_element([1, 2, 3])
3
>>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
123
"""
max_elem = l[0]
for i in range(1, len(l)):
if l[i] > max_elem: | return max_elem
| max_elem = l[i] | def check(candidate):
assert candidate([1, 2, 3]) == 3
assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124
def test_check():
check(max_element)
test_check()
|
humaneval-HumanEval_116_sort_array.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// In this Kata, you have to sort an array array list of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))
// >>> sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l))))
// (new ArrayList<Long>(Arrays.asList((long)-6l, (long)-5l, (long)-4l, (long)-3l, (long)-2l)))
// >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l)))
public static ArrayList<Long> sortArray(ArrayList<Long> arr) {
Collections.sort(arr, (a, b) -> {
long a1 = a, b1 = b;
if (a1 < 0) {
a1 = -a1;
}
if (b1 < 0) {
b1 = -b1;
}
return Long.bitCount(a1) == Long.bitCount(b1) ? Long.compare(a, b) : Integer.compare(Long.bitCount(a1), Long.bitCount(b1));
}); | }
} | return arr; | }
public static void main(String[] args) {
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-2l, (long)-6l, (long)-5l, (long)-3l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)4l, (long)3l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)77l, (long)4l, (long)5l, (long)3l, (long)5l, (long)7l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)4l, (long)4l, (long)3l, (long)3l, (long)5l, (long)5l, (long)5l, (long)7l, (long)77l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)44l, (long)12l, (long)32l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)32l, (long)3l, (long)5l, (long)6l, (long)12l, (long)44l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))));
assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))));
}
}
|
humaneval-HumanEval_114_minSubArraySum.json-L25 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given an array array list of 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) { | }
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;
}
} | minSum = currSum; | }
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_154_cycpattern_check.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 {
// 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
// >>> cycpatternCheck(("abcd"), ("abd"))
// (false)
// >>> cycpatternCheck(("hello"), ("ell"))
// (true)
// >>> cycpatternCheck(("whassup"), ("psus"))
// (false)
// >>> cycpatternCheck(("abab"), ("baa"))
// (true)
// >>> cycpatternCheck(("efef"), ("eeff"))
// (false)
// >>> cycpatternCheck(("himenss"), ("simen"))
// (true)
public static boolean cycpatternCheck(String a, String b) {
int len = b.length();
boolean found = false;
for (int i = 0; i < len; i++) {
b = b.substring(1) + b.charAt(0);
found = a.contains(b);
if (found) break; | return found;
}
} | } | }
public static void main(String[] args) {
assert(cycpatternCheck(("xyzw"), ("xyw")) == (false));
assert(cycpatternCheck(("yello"), ("ell")) == (true));
assert(cycpatternCheck(("whattup"), ("ptut")) == (false));
assert(cycpatternCheck(("efef"), ("fee")) == (true));
assert(cycpatternCheck(("abab"), ("aabb")) == (false));
assert(cycpatternCheck(("winemtt"), ("tinem")) == (true));
}
}
|
humaneval-HumanEval_55_fib.json-L12 | py | def fib(n: int) -> int:
"""Return n-th Fibonacci number.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
"""
assert n >= 1
f0, f1 = 0, 1 | f0, f1 = f1, f0 + f1
return f1
| for i in range(n - 1): | def check(candidate):
assert candidate(10) == 55
assert candidate(1) == 1
assert candidate(8) == 21
assert candidate(11) == 89
assert candidate(12) == 144
def test_check():
check(fib)
test_check()
|
humaneval-HumanEval_40_triples_sum_to_zero.json-L17 | js | //triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// >>> triples_sum_to_zero([1, 3, 5, 0])
// false
// >>> triples_sum_to_zero([1, 3, -2, 1])
// true
// >>> triples_sum_to_zero([1, 2, 3, 7])
// false
// >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])
// true
// >>> triples_sum_to_zero([1])
// false
function triples_sum_to_zero(l){
for (var i = 0; i < l.length; i++) {
for (var j = 0; j < l.length; j++) { | if (i !== j && i !== k && j !== k) {
if (l[i] + l[j] + l[k] === 0) {
return true;
}
}
}
}
}
return false;
}
| for (var k = 0; k < l.length; k++) { | const assert = require('node:assert');
function test() {
let candidate = triples_sum_to_zero;
assert.deepEqual(candidate([1, 3, 5, 0]),false);
assert.deepEqual(candidate([1, 3, 5, -1]),false);
assert.deepEqual(candidate([1, 3, -2, 1]),true);
assert.deepEqual(candidate([1, 2, 3, 7]),false);
assert.deepEqual(candidate([1, 2, 5, 7]),false);
assert.deepEqual(candidate([2, 4, -5, 3, 9, 7]),true);
assert.deepEqual(candidate([1]),false);
assert.deepEqual(candidate([1, 3, 5, -100]),false);
assert.deepEqual(candidate([100, 3, 5, -100]),false);
}
test(); |
humaneval-HumanEval_123_get_odd_collatz.json-L29 | 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_160_do_algebra.json-L60 | js | //Given two arrays operator, and operand. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
function do_algebra(operator, operand){
let do_again;
let count = 0;
let temp;
let answer;
while(count < operator.length){
switch(operator[count]){
case '*':
operand[count] = operand[count] * operand[count + 1];
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '//':
operand[count] = Math.floor(operand[count] / operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '**':
operand[count] = Math.pow(operand[count], operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
default:
count++;
do_again = false;
}
}
answer = operand[0];
operand.splice(0, 1);
while(operand.length > 0){
switch(operator[0]){
case '+':
answer += operand[0];
break;
case '-': | break;
}
operand.splice(0, 1);
operator.splice(0, 1);
}
return answer;
}
| answer -= operand[0]; | const assert = require('node:assert');
function test() {
let candidate = do_algebra;
assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37);
assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9);
assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8);
}
test(); |
humaneval-HumanEval_68_pluck.json-L27 | 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){
| 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;
}
| let 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_61_correct_bracketing.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 {
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// >>> correctBracketing(("("))
// (false)
// >>> correctBracketing(("()"))
// (true)
// >>> correctBracketing(("(()())"))
// (true)
// >>> correctBracketing((")(()"))
// (false)
public static boolean correctBracketing(String brackets) {
int balance = 0;
for (int i = 0; i < brackets.length(); i++) {
if (brackets.charAt(i) == '(') { | } else {
balance--;
}
if (balance < 0) {
return false;
}
}
return balance == 0;
}
} | balance++; | }
public static void main(String[] args) {
assert(correctBracketing(("()")) == (true));
assert(correctBracketing(("(()())")) == (true));
assert(correctBracketing(("()()(()())()")) == (true));
assert(correctBracketing(("()()((()()())())(()()(()))")) == (true));
assert(correctBracketing(("((()())))")) == (false));
assert(correctBracketing((")(()")) == (false));
assert(correctBracketing(("(")) == (false));
assert(correctBracketing(("((((")) == (false));
assert(correctBracketing((")")) == (false));
assert(correctBracketing(("(()")) == (false));
assert(correctBracketing(("()()(()())())(()")) == (false));
assert(correctBracketing(("()()(()())()))()")) == (false));
}
}
|
humaneval-HumanEval_74_total_match.json-L25 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that accepts two array lists of strings and returns the array list that has
// total number of chars in the all strings of the array list less than the other array list.
// if the two array lists have the same number of chars, return the first array list.
// Examples
// >>> totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList())))
// (new ArrayList<String>(Arrays.asList()))
// >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi"))))
// (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi")))
// >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi", (String)"admin", (String)"project"))))
// (new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin")))
// >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi"))))
// (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi")))
// >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"4"))), (new ArrayList<String>(Arrays.asList((String)"1", (String)"2", (String)"3", (String)"4", (String)"5"))))
// (new ArrayList<String>(Arrays.asList((String)"4")))
public static ArrayList<String> totalMatch(ArrayList<String> lst1, ArrayList<String> lst2) {
int sum1 = 0; | for (String s : lst1) {
sum1 += s.length();
}
for (String s : lst2) {
sum2 += s.length();
}
if (sum1 <= sum2) {
return lst1;
} else {
return lst2;
}
}
} | int sum2 = 0; | }
public static void main(String[] args) {
assert(totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList()))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi", (String)"admin", (String)"project")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"4"))), (new ArrayList<String>(Arrays.asList((String)"1", (String)"2", (String)"3", (String)"4", (String)"5")))).equals((new ArrayList<String>(Arrays.asList((String)"4")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hii")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin")))));
assert(totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList((String)"this")))).equals((new ArrayList<String>(Arrays.asList()))));
assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"this"))), (new ArrayList<String>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_1_separate_paren_groups.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 {
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array list of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> separateParenGroups(("( ) (( )) (( )( ))"))
// (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())")))
public static ArrayList<String> separateParenGroups(String paren_string) {
| StringBuffer temp = new StringBuffer();
int open_paren = 0;
for (int i = 0; i < paren_string.length(); i++) {
char c = paren_string.charAt(i);
if (c == '(') {
if (open_paren == 0) {
temp = new StringBuffer();
}
open_paren++;
temp.append(c);
} else if (c == ')') {
open_paren--;
temp.append(c);
if (open_paren == 0) {
output.add(temp.toString());
}
}
}
return output;
}
} | ArrayList<String> output = new ArrayList<String>(); | }
public static void main(String[] args) {
assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())")))));
assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))")))));
assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))")))));
assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())")))));
}
}
|
humaneval-HumanEval_156_int_to_mini_roman.json-L46 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// >>> intToMiniRoman((19l))
// ("xix")
// >>> intToMiniRoman((152l))
// ("clii")
// >>> intToMiniRoman((426l))
// ("cdxxvi")
public static String intToMiniRoman(long number) {
int num = (int) number;
String res = "";
if (num == 0)
return "";
while (num >= 1000) {
res += "m";
num -= 1000;
}
if (num >= 900) {
res += "cm";
num -= 900;
}
if (num >= 500) {
res += "d";
num -= 500;
}
if (num >= 400) {
res += "cd";
num -= 400;
}
while (num >= 100) {
res += "c";
num -= 100;
}
if (num >= 90) {
res += "xc"; | }
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 -= 90; | }
public static void main(String[] args) {
assert(intToMiniRoman((19l)).equals(("xix")));
assert(intToMiniRoman((152l)).equals(("clii")));
assert(intToMiniRoman((251l)).equals(("ccli")));
assert(intToMiniRoman((426l)).equals(("cdxxvi")));
assert(intToMiniRoman((500l)).equals(("d")));
assert(intToMiniRoman((1l)).equals(("i")));
assert(intToMiniRoman((4l)).equals(("iv")));
assert(intToMiniRoman((43l)).equals(("xliii")));
assert(intToMiniRoman((90l)).equals(("xc")));
assert(intToMiniRoman((94l)).equals(("xciv")));
assert(intToMiniRoman((532l)).equals(("dxxxii")));
assert(intToMiniRoman((900l)).equals(("cm")));
assert(intToMiniRoman((994l)).equals(("cmxciv")));
assert(intToMiniRoman((1000l)).equals(("m")));
}
}
|
humaneval-HumanEval_39_prime_fib.json-L30 | 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){ |
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);
} | var a = 1, b = 0, temp; | 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_156_int_to_mini_roman.json-L28 | js | //Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// >>> int_to_mini_roman(19)
// "xix"
// >>> int_to_mini_roman(152)
// "clii"
// >>> int_to_mini_roman(426)
// "cdxxvi"
function int_to_mini_roman(number){
var roman_conversion = {
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
};
var output = ""; | var key_list = Object.keys(roman_conversion).map(Number);
key_list.sort(function(a, b){return b-a});
for (var i = 0; i < key_list.length; i++){
if (key_list[i] <= number){
output += roman_conversion[key_list[i]];
number -= key_list[i];
break;
}
}
}
return output;
}
| while (number > 0){ | const assert = require('node:assert');
function test() {
let candidate = int_to_mini_roman;
assert.deepEqual(candidate(19),"xix");
assert.deepEqual(candidate(152),"clii");
assert.deepEqual(candidate(251),"ccli");
assert.deepEqual(candidate(426),"cdxxvi");
assert.deepEqual(candidate(500),"d");
assert.deepEqual(candidate(1),"i");
assert.deepEqual(candidate(4),"iv");
assert.deepEqual(candidate(43),"xliii");
assert.deepEqual(candidate(90),"xc");
assert.deepEqual(candidate(94),"xciv");
assert.deepEqual(candidate(532),"dxxxii");
assert.deepEqual(candidate(900),"cm");
assert.deepEqual(candidate(994),"cmxciv");
assert.deepEqual(candidate(1000),"m");
}
test(); |
humaneval-HumanEval_81_numerical_letter_grade.json-L34 | js | //It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// >>> grade_equation([4.0, 3, 1.7, 2, 3.5])
// ["A+", "B", "C-", "C", "A-"]
function numerical_letter_grade(grades){
var grades_array = [];
for (var i = 0; i < grades.length; i++){
if (grades[i] >= 4.0){
grades_array.push("A+");
}
else if (grades[i] > 3.7){
grades_array.push("A");
}
else if (grades[i] > 3.3){
grades_array.push("A-"); | else if (grades[i] > 3.0){
grades_array.push("B+");
}
else if (grades[i] > 2.7){
grades_array.push("B");
}
else if (grades[i] > 2.3){
grades_array.push("B-");
}
else if (grades[i] > 2.0){
grades_array.push("C+");
}
else if (grades[i] > 1.7){
grades_array.push("C");
}
else if (grades[i] > 1.3){
grades_array.push("C-");
}
else if (grades[i] > 1.0){
grades_array.push("D+");
}
else if (grades[i] > 0.7){
grades_array.push("D");
}
else if (grades[i] > 0.0){
grades_array.push("D-");
}
else if (grades[i] == 0.0){
grades_array.push("E");
}
}
return grades_array;
} | } | const assert = require('node:assert');
function test() {
let candidate = numerical_letter_grade;
assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]);
assert.deepEqual(candidate([1.2]),["D+"]);
assert.deepEqual(candidate([0.5]),["D-"]);
assert.deepEqual(candidate([0.0]),["E"]);
assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]);
assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]);
}
test(); |
humaneval-HumanEval_11_string_xor.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 {
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// >>> stringXor(("010"), ("110"))
// ("100")
public static String stringXor(String a, String b) {
StringBuilder c = new StringBuilder();
for (int i = 0; i < a.length(); i++) {
c.append(a.charAt(i) ^ b.charAt(i));
} | }
} | return c.toString(); | }
public static void main(String[] args) {
assert(stringXor(("111000"), ("101010")).equals(("010010")));
assert(stringXor(("1"), ("1")).equals(("0")));
assert(stringXor(("0101"), ("0000")).equals(("0101")));
}
}
|
humaneval-HumanEval_70_strange_sort_list.json-L23 | py | from typing import List
def strange_sort_list(lst: List[int]) -> List[int]:
"""
Given list of integers, return 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:
>>> 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([])
[]
"""
lst = sorted(lst)
out = []
while lst:
out.append(lst.pop(0))
if not lst:
break | return out | out.append(lst.pop()) | def check(candidate):
assert candidate([1, 2, 3, 4]) == [1, 4, 2, 3]
assert candidate([5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]
assert candidate([1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]
assert candidate([5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]
assert candidate([5, 5, 5, 5]) == [5, 5, 5, 5]
assert candidate([]) == []
assert candidate([1, 2, 3, 4, 5, 6, 7, 8]) == [1, 8, 2, 7, 3, 6, 4, 5]
assert candidate([0, 2, 2, 2, 5, 5, -5, -5]) == [-5, 5, -5, 5, 0, 2, 2, 2]
assert candidate([111111]) == [111111]
def test_check():
check(strange_sort_list)
test_check()
|
humaneval-HumanEval_135_can_arrange.json-L11 | js | //Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// >>> can_arrange([1, 2, 4, 3, 5])
// 3
// >>> can_arrange([1, 2, 3])
// -1
function can_arrange(arr){
| var res = -1;
for(var i = 1; i < arr.length; i++){
if(arr[i] < max){
res = i;
}else{
max = arr[i];
}
}
return res;
}
| var max = arr[0]; | const assert = require('node:assert');
function test() {
let candidate = can_arrange;
assert.deepEqual(candidate([1, 2, 4, 3, 5]),3);
assert.deepEqual(candidate([1, 2, 4, 5]),-1);
assert.deepEqual(candidate([1, 4, 2, 5, 6, 7, 8, 9, 10]),2);
assert.deepEqual(candidate([4, 8, 5, 7, 3]),4);
assert.deepEqual(candidate([]),-1);
}
test(); |
humaneval-HumanEval_19_sort_numbers.json-L9 | py | def sort_numbers(numbers: str) -> str:
""" Input is a space-delimited string of numberals from 'zero' to 'nine'.
Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
Return the string with numbers sorted from smallest to largest
>>> sort_numbers('three one five')
'one three five'
"""
words = numbers.split() | mapper = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
for word in sorted(words, key=lambda x: mapper[x]):
res += ' ' + word
return res.strip()
| res = '' | def check(candidate):
assert candidate('') == ''
assert candidate('three') == 'three'
assert candidate('three five nine') == 'three five nine'
assert candidate('five zero four seven nine eight') == 'zero four five seven eight nine'
assert candidate('six five four three two one zero') == 'zero one two three four five six'
def test_check():
check(sort_numbers)
test_check()
|
humaneval-HumanEval_27_flip_case.json-L11 | js | //For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// >>> flip_case("Hello")
// "hELLO"
function flip_case(string){
var result = "";
for(var i = 0; i < string.length; i++){
if(string[i] == string[i].toUpperCase()){
result += string[i].toLowerCase();
}else{
result += string[i].toUpperCase(); | }
return result;
}
| } | const assert = require('node:assert');
function test() {
let candidate = flip_case;
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("Hello!"),"hELLO!");
assert.deepEqual(candidate("These violent delights have violent ends"),"tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS");
}
test(); |
humaneval-HumanEval_138_is_equal_to_sum_even.json-L21 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// >>> isEqualToSumEven((4l))
// (false)
// >>> isEqualToSumEven((6l))
// (false)
// >>> isEqualToSumEven((8l))
// (true)
public static boolean isEqualToSumEven(long n) {
if (n < 4) {
return false;
} | if (n % 2 == 1) {
d = 1;
}
long minX = d;
long maxX = n / 4;
while (minX <= maxX) {
long x = (minX + maxX) / 2;
long y = n - 2 * x;
if (y % 2 == 1) {
y--;
}
if (2 * x + y < n) {
minX = x + 1;
} else if (2 * x + y > n) {
maxX = x - 1;
} else {
return true;
}
}
return false;
}
} | long d = 2; | }
public static void main(String[] args) {
assert(isEqualToSumEven((4l)) == (false));
assert(isEqualToSumEven((6l)) == (false));
assert(isEqualToSumEven((8l)) == (true));
assert(isEqualToSumEven((10l)) == (true));
assert(isEqualToSumEven((11l)) == (false));
assert(isEqualToSumEven((12l)) == (true));
assert(isEqualToSumEven((13l)) == (false));
assert(isEqualToSumEven((16l)) == (true));
}
}
|
humaneval-HumanEval_26_remove_duplicates.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 {
// 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);
if (hashmap.get(key) == 1) {
out.add(key);
} | return out;
}
} | } | }
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_74_total_match.json-L26 | js | //Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// >>> total_match([], [])
// []
// >>> total_match(["hi", "admin"], ["hI", "Hi"])
// ["hI", "Hi"]
// >>> total_match(["hi", "admin"], ["hi", "hi", "admin", "project"])
// ["hi", "admin"]
// >>> total_match(["hi", "admin"], ["hI", "hi", "hi"])
// ["hI", "hi", "hi"]
// >>> total_match(["4"], ["1", "2", "3", "4", "5"])
// ["4"]
function total_match(lst1, lst2){
let sum_lst1 = 0;
let sum_lst2 = 0;
for(let item of lst1){
sum_lst1 += item.length;
}
for(let item of lst2){
sum_lst2 += item.length;
}
if(sum_lst1 > sum_lst2){
return lst2; | else{
return lst1;
}
}
| } | const assert = require('node:assert');
function test() {
let candidate = total_match;
assert.deepEqual(candidate([], []),[]);
assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi"]),["hi", "hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi", "admin", "project"]),["hi", "admin"]);
assert.deepEqual(candidate(["4"], ["1", "2", "3", "4", "5"]),["4"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "Hi"]),["hI", "Hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hi"]),["hI", "hi", "hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hii"]),["hi", "admin"]);
assert.deepEqual(candidate([], ["this"]),[]);
assert.deepEqual(candidate(["this"], []),[]);
}
test(); |
humaneval-HumanEval_111_histogram.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 {
// 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);
}
} | if (hm.get(key) == max) {
s.put(key, hm.get(key));
}
}
}
return s;
}
} | for (String key : hm.keySet()) { | }
public static void main(String[] args) {
assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))));
assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))));
assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l)))));
assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l)))));
assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l)))));
assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l)))));
assert(histogram(("")).equals((new HashMap<String,Long>())));
assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l)))));
}
}
|
humaneval-HumanEval_147_get_max_triples.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a positive integer n. You have to create an integer array array list a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// >>> getMaxTriples((5l))
// (1l)
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
public static long getMaxTriples(long n) {
int count = 0;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
arrayList.add(i * i - i + 1);
}
for (int i = 0; i < arrayList.size(); i++) {
for (int j = i + 1; j < arrayList.size(); j++) {
for (int k = j + 1; k < arrayList.size(); k++) {
if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) {
count++; | }
}
}
return count;
}
} | } | }
public static void main(String[] args) {
assert(getMaxTriples((5l)) == (1l));
assert(getMaxTriples((6l)) == (4l));
assert(getMaxTriples((10l)) == (36l));
assert(getMaxTriples((100l)) == (53361l));
}
}
|
humaneval-HumanEval_13_greatest_common_divisor.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 {
// Return a greatest common divisor of two integers a and b
// >>> greatestCommonDivisor((3l), (5l))
// (1l)
// >>> greatestCommonDivisor((25l), (15l))
// (5l)
public static long greatestCommonDivisor(long a, long b) {
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
return greatestCommonDivisor(b, a % b); | } | } | }
public static void main(String[] args) {
assert(greatestCommonDivisor((3l), (7l)) == (1l));
assert(greatestCommonDivisor((10l), (15l)) == (5l));
assert(greatestCommonDivisor((49l), (14l)) == (7l));
assert(greatestCommonDivisor((144l), (60l)) == (12l));
}
}
|
humaneval-HumanEval_142_sum_squares.json-L18 | js | //"
// This function will take an array of integers. For all entries in the array, the function shall square the integer entry if its index is a
// multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
// change the entries in the array whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
// Examples:
// >>> lst
// [1, 2, 3]
// >>> lst
// []
// >>> lst
// [-1, -5, 2, -1, -5]
function sum_squares(lst){
var sum = 0;
var len = lst.length;
for (var i = 0; i < len; i++){
if (i % 3 == 0){
sum += lst[i]*lst[i]; | sum += lst[i]*lst[i]*lst[i];
} else {
sum += lst[i];
}
}
return sum;
} | } else if (i % 4 == 0){ | const assert = require('node:assert');
function test() {
let candidate = sum_squares;
assert.deepEqual(candidate([1, 2, 3]),6);
assert.deepEqual(candidate([1, 4, 9]),14);
assert.deepEqual(candidate([]),0);
assert.deepEqual(candidate([1, 1, 1, 1, 1, 1, 1, 1, 1]),9);
assert.deepEqual(candidate([-1, -1, -1, -1, -1, -1, -1, -1, -1]),-3);
assert.deepEqual(candidate([0]),0);
assert.deepEqual(candidate([-1, -5, 2, -1, -5]),-126);
assert.deepEqual(candidate([-56, -99, 1, 0, -2]),3030);
assert.deepEqual(candidate([-1, 0, 0, 0, 0, 0, 0, 0, -1]),0);
assert.deepEqual(candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]),-14196);
assert.deepEqual(candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]),-1448);
}
test(); |
humaneval-HumanEval_111_histogram.json-L29 | js | //Given a string representing a space separated lowercase letters, return an object
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// >>> histogram("a b c")
// {"a": 1, "b": 1, "c": 1}
// >>> histogram("a b b a")
// {"a": 2, "b": 2}
// >>> histogram("a b c a b")
// {"a": 2, "b": 2}
// >>> histogram("b b b b a")
// {"b": 4}
// >>> histogram("")
// {}
function histogram(test){
if (test.length === 0){
return {};
}
var lst = test.split(" ");
var count = {};
for (var i = 0; i < lst.length; i++){
if (count[lst[i]]){
count[lst[i]] += 1;
}
else{
count[lst[i]] = 1;
}
} | var max = 0;
var result = {};
for (var key in count){
if (count[key] > max){
max = count[key];
result = {};
result[key] = max;
}
else if (count[key] === max){
result[key] = max;
}
}
return result;
}
| console.log(count); | const assert = require('node:assert');
function test() {
let candidate = histogram;
assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2});
assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2});
assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1});
assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1});
assert.deepEqual(candidate("b b b b a"),{"b": 4});
assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1});
assert.deepEqual(candidate(""),{});
assert.deepEqual(candidate("a"),{"a": 1});
}
test(); |
humaneval-HumanEval_156_int_to_mini_roman.json-L24 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a 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 ""; | res += "m";
num -= 1000;
}
if (num >= 900) {
res += "cm";
num -= 900;
}
if (num >= 500) {
res += "d";
num -= 500;
}
if (num >= 400) {
res += "cd";
num -= 400;
}
while (num >= 100) {
res += "c";
num -= 100;
}
if (num >= 90) {
res += "xc";
num -= 90;
}
if (num >= 50) {
res += "l";
num -= 50;
}
if (num >= 40) {
res += "xl";
num -= 40;
}
while (num >= 10) {
res += "x";
num -= 10;
}
if (num >= 9) {
res += "ix";
num -= 9;
}
if (num >= 5) {
res += "v";
num -= 5;
}
if (num >= 4) {
res += "iv";
num -= 4;
}
while (num >= 1) {
res += "i";
num -= 1;
}
return res;
}
} | while (num >= 1000) { | }
public static void main(String[] args) {
assert(intToMiniRoman((19l)).equals(("xix")));
assert(intToMiniRoman((152l)).equals(("clii")));
assert(intToMiniRoman((251l)).equals(("ccli")));
assert(intToMiniRoman((426l)).equals(("cdxxvi")));
assert(intToMiniRoman((500l)).equals(("d")));
assert(intToMiniRoman((1l)).equals(("i")));
assert(intToMiniRoman((4l)).equals(("iv")));
assert(intToMiniRoman((43l)).equals(("xliii")));
assert(intToMiniRoman((90l)).equals(("xc")));
assert(intToMiniRoman((94l)).equals(("xciv")));
assert(intToMiniRoman((532l)).equals(("dxxxii")));
assert(intToMiniRoman((900l)).equals(("cm")));
assert(intToMiniRoman((994l)).equals(("cmxciv")));
assert(intToMiniRoman((1000l)).equals(("m")));
}
}
|
humaneval-HumanEval_129_minPath.json-L48 | py | from typing import List
def minPath(grid: List[List[int]], k: int) -> List[int]:
"""
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 lists 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 list 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]
"""
min_val = float('inf')
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] < min_val:
min_val = grid[i][j]
row = i
col = j
path = [min_val]
while len(path) < k:
min_val = float('inf')
for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val:
min_val = grid[i][j]
row = i
col = j
path.append(min_val) | return path | def check(candidate):
assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1]
assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1]
assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2]
assert 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 candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1]
assert 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 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 candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3]
assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5]
assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3]
def test_check():
check(minPath)
test_check()
|
|
humaneval-HumanEval_141_file_name_check.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// >>> fileNameCheck(("example.txt"))
// ("Yes")
// >>> fileNameCheck(("1example.dll"))
// ("No")
public static String fileNameCheck(String file_name) {
String result = "No";
String[] tokens = file_name.split("\\.");
if (tokens.length != 2) {
return result;
}
String extension = tokens[1]; | return result;
}
String name = tokens[0];
int count = 0;
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
count++;
}
}
if (count > 3) {
return result;
}
if (name.length() == 0) {
return result;
}
if (!Character.isLetter(name.charAt(0))) {
return result;
}
return "Yes";
}
} | if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { | }
public static void main(String[] args) {
assert(fileNameCheck(("example.txt")).equals(("Yes")));
assert(fileNameCheck(("1example.dll")).equals(("No")));
assert(fileNameCheck(("s1sdf3.asd")).equals(("No")));
assert(fileNameCheck(("K.dll")).equals(("Yes")));
assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes")));
assert(fileNameCheck(("His12FILE94.exe")).equals(("No")));
assert(fileNameCheck(("_Y.txt")).equals(("No")));
assert(fileNameCheck(("?aREYA.exe")).equals(("No")));
assert(fileNameCheck(("/this_is_valid.dll")).equals(("No")));
assert(fileNameCheck(("this_is_valid.wow")).equals(("No")));
assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes")));
assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No")));
assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No")));
assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No")));
assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No")));
assert(fileNameCheck(("all.exe.txt")).equals(("No")));
assert(fileNameCheck(("I563_No.exe")).equals(("Yes")));
assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes")));
assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes")));
assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No")));
assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No")));
assert(fileNameCheck(("final..txt")).equals(("No")));
assert(fileNameCheck(("final132")).equals(("No")));
assert(fileNameCheck(("_f4indsartal132.")).equals(("No")));
assert(fileNameCheck((".txt")).equals(("No")));
assert(fileNameCheck(("s.")).equals(("No")));
}
}
|
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L19 | py | def check_if_last_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the last character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_last_char_is_a_letter('apple pie')
False
>>> check_if_last_char_is_a_letter('apple pi e')
True
>>> check_if_last_char_is_a_letter('apple pi e ')
False
>>> check_if_last_char_is_a_letter('')
False
"""
if len(txt) == 0: | elif txt[-1].isalpha() and (len(txt) == 1 or not txt[-2].isalpha()):
return True
else:
return False
| return False | def check(candidate):
assert candidate('apple') == False
assert candidate('apple pi e') == True
assert candidate('eeeee') == False
assert candidate('A') == True
assert candidate('Pumpkin pie ') == False
assert candidate('Pumpkin pie 1') == False
assert candidate('') == False
assert candidate('eeeee e ') == False
assert candidate('apple pie') == False
assert candidate('apple pi e ') == False
def test_check():
check(check_if_last_char_is_a_letter)
test_check()
|
humaneval-HumanEval_9_rolling_max.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 {
// From a given array list of integers, generate an array array list of rolling maximum element found until given moment
// in the sequence.
// >>> rollingMax((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)3l, (long)4l, (long)2l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l, (long)4l)))
public static ArrayList<Long> rollingMax(ArrayList<Long> numbers) {
ArrayList<Long> results = new ArrayList<Long>();
for (int i = 0; i < numbers.size(); i++) { | }
return results;
}
} | results.add(numbers.subList(0, i + 1).stream().max(Long::compare).get()); | }
public static void main(String[] args) {
assert(rollingMax((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
assert(rollingMax((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(rollingMax((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l)))));
assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l, (long)100l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)100l, (long)100l)))));
}
}
|
humaneval-HumanEval_86_anti_shuffle.json-L29 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// >>> antiShuffle(("Hi"))
// ("Hi")
// >>> antiShuffle(("hello"))
// ("ehllo")
// >>> antiShuffle(("Hello World!!!"))
// ("Hello !!!Wdlor")
public static String antiShuffle(String s) {
StringBuilder sb = new StringBuilder();
String[] words = s.split(" ");
for (String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
sb.append(new String(chars));
sb.append(" "); | sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
} | } | }
public static void main(String[] args) {
assert(antiShuffle(("Hi")).equals(("Hi")));
assert(antiShuffle(("hello")).equals(("ehllo")));
assert(antiShuffle(("number")).equals(("bemnru")));
assert(antiShuffle(("abcd")).equals(("abcd")));
assert(antiShuffle(("Hello World!!!")).equals(("Hello !!!Wdlor")));
assert(antiShuffle(("")).equals(("")));
assert(antiShuffle(("Hi. My name is Mister Robot. How are you?")).equals((".Hi My aemn is Meirst .Rboot How aer ?ouy")));
}
}
|
humaneval-HumanEval_124_valid_date.json-L33 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// >>> validDate(("03-11-2000"))
// (true)
// >>> validDate(("15-01-2012"))
// (false)
// >>> validDate(("04-0-2040"))
// (false)
// >>> validDate(("06-04-2020"))
// (true)
// >>> validDate(("06/04/2020"))
// (false)
public static boolean validDate(String date) {
boolean valid_date = false;
if (date.equals("")) return valid_date;
String[] parts = date.split("-");
if (parts.length != 3) return valid_date;
try {
int month = Integer.parseInt(parts[0]); | int year = Integer.parseInt(parts[2]);
if (month < 1 || month > 12) return valid_date;
if (month == 2) {
if (day < 1 || day > 29) return valid_date;
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day < 1 || day > 31) return valid_date;
} else {
if (day < 1 || day > 30) return valid_date;
}
valid_date = true;
} catch (Exception e) {
valid_date = false;
}
return valid_date;
}
} | int day = Integer.parseInt(parts[1]); | }
public static void main(String[] args) {
assert(validDate(("03-11-2000")) == (true));
assert(validDate(("15-01-2012")) == (false));
assert(validDate(("04-0-2040")) == (false));
assert(validDate(("06-04-2020")) == (true));
assert(validDate(("01-01-2007")) == (true));
assert(validDate(("03-32-2011")) == (false));
assert(validDate(("")) == (false));
assert(validDate(("04-31-3000")) == (false));
assert(validDate(("06-06-2005")) == (true));
assert(validDate(("21-31-2000")) == (false));
assert(validDate(("04-12-2003")) == (true));
assert(validDate(("04122003")) == (false));
assert(validDate(("20030412")) == (false));
assert(validDate(("2003-04")) == (false));
assert(validDate(("2003-04-12")) == (false));
assert(validDate(("04-2003")) == (false));
}
}
|
humaneval-HumanEval_105_by_length.json-L26 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given 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) { | good.add(i);
}
}
good.sort(new Comparator<Long>() {
public int compare(Long i1, Long i2) {
return i1.compareTo(i2);
}
});
Collections.reverse(good);
for (Long i : good) {
res.add(a[i.intValue() - 1]);
}
return res;
}
} | if (i >= 1 && i <= 9) { | }
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_43_pairs_sum_to_zero.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 {
// pairs_sum_to_zero takes an array array list of integers as an input.
// it returns true if there are two distinct elements in the array list that
// sum to zero, and false otherwise.
// >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l))))
// (false)
// >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l))))
// (false)
// >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l))))
// (false)
// >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l))))
// (true)
// >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l))))
// (false)
public static boolean pairsSumToZero(ArrayList<Long> l) {
for (int i = 0; i < l.size(); i++) {
for (int j = i + 1; j < l.size(); j++) {
if (l.get(i) + l.get(j) == 0) {
return true; | }
}
return false;
}
} | } | }
public static void main(String[] args) {
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (false));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l)))) == (true));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)30l)))) == (true));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)31l)))) == (true));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)30l)))) == (false));
assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)31l)))) == (false));
}
}
|
humaneval-HumanEval_119_match_parens.json-L38 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given an array array list of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")"))))
// ("Yes")
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")"))))
// ("No")
public static String matchParens(ArrayList<String> lst) {
String s1 = lst.get(0);
String s2 = lst.get(1);
String s3 = s1+s2;
String s4 = s2+s1;
int c1 = 0;
int c2 = 0;
for (int i = 0; i < s3.length(); i++) {
if (s3.charAt(i) == '(') c1 += 1;
else c1 -= 1;
if (c1 < 0) break;
}
for (int i = 0; i < s4.length(); i++) {
if (s4.charAt(i) == '(') c2 += 1;
else c2 -= 1;
if (c2 < 0) break; | if (c1 == 0 || c2 == 0) return "Yes";
else return "No";
}
} | } | }
public static void main(String[] args) {
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes")));
}
}
|
humaneval-HumanEval_88_sort_array.json-L17 | js | //Given an array of non-negative integers, return a cojs of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// >>> sort_array([])
// []
// >>> sort_array([5])
// [5]
// >>> sort_array([2, 4, 3, 0, 1, 5])
// [0, 1, 2, 3, 4, 5]
// >>> sort_array([2, 4, 3, 0, 1, 5, 6])
// [6, 5, 4, 3, 2, 1, 0]
function sort_array(array){
let sum = array[0] + array[array.length - 1]; | if(sum % 2 === 0){
newArr = array.sort(function(a, b){return b - a;});
}else{
newArr = array.sort(function(a, b){return a - b;});
}
return newArr;
} | let newArr = []; | const assert = require('node:assert');
function test() {
let candidate = sort_array;
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([5]),[5]);
assert.deepEqual(candidate([2, 4, 3, 0, 1, 5]),[0, 1, 2, 3, 4, 5]);
assert.deepEqual(candidate([2, 4, 3, 0, 1, 5, 6]),[6, 5, 4, 3, 2, 1, 0]);
assert.deepEqual(candidate([2, 1]),[1, 2]);
assert.deepEqual(candidate([15, 42, 87, 32, 11, 0]),[0, 11, 15, 32, 42, 87]);
assert.deepEqual(candidate([21, 14, 23, 11]),[23, 21, 14, 11]);
}
test(); |
humaneval-HumanEval_111_histogram.json-L31 | py | from typing import Dict
def histogram(test: str) -> Dict[str, int]:
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return all of them.
Example:
>>> histogram('a b c')
{ 'a': 1, 'b': 1, 'c': 1 }
>>> histogram('a b b a')
{ 'a': 2, 'b': 2 }
>>> histogram('a b c a b')
{ 'a': 2, 'b': 2 }
>>> histogram('b b b b a')
{ 'b': 4 }
>>> histogram('')
{ }
"""
letters = {}
most_count = 0
result = {}
for letter in test.split():
letters[letter] = letters.get(letter, 0) + 1
if letters[letter] >= most_count:
most_count = letters[letter]
for letter in letters:
if letters[letter] == most_count:
result[letter] = most_count | return result | def check(candidate):
assert candidate('a b b a') == { 'a': 2, 'b': 2 }
assert candidate('a b c a b') == { 'a': 2, 'b': 2 }
assert candidate('a b c d g') == { 'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1 }
assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 }
assert candidate('b b b b a') == { 'b': 4 }
assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 }
assert candidate('') == { }
assert candidate('a') == { 'a': 1 }
def test_check():
check(histogram)
test_check()
|
|
humaneval-HumanEval_56_correct_bracketing.json-L12 | 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){
| for (var i = 0; i < brackets.length; i++) {
if (brackets[i] === "<") {
opens++;
}
else if (brackets[i] === ">") {
opens--;
}
if (opens < 0) {
return false;
}
}
return opens === 0;
}
| var opens = 0; | 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_153_Strongest_Extension.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 will be given the name of a class (a string) and an array array list of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array list.
// For example, if you are given "Slices" as the class and an array array list of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC"))))
// ("my_class.AA")
public static String StrongestExtension(String class_name, ArrayList<String> extensions) {
if (extensions.size() == 0) {
return class_name;
}
int strength = Integer.MIN_VALUE;
String strongest = "";
for (String s : extensions) { | int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count();
int diff = cap - sm;
if (diff > strength) {
strength = diff;
strongest = s;
}
}
return class_name + "." + strongest;
}
} | int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count(); | }
public static void main(String[] args) {
assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe")));
assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe")));
assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__")));
assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR")));
assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123")));
assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123")));
assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW")));
assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb")));
assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235")));
}
}
|
humaneval-HumanEval_160_do_algebra.json-L32 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given two array lists operator, and operand. The first array list has basic algebra operations, and
// the second array list is an array array list of integers. Use the two given array lists to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array array list = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array list is equal to the length of operand array list minus one.
// Operand is an array array list of of non-negative integers.
// Operator array list has at least one operator, and operand array list has at least two operands.
public static long doAlgebra(ArrayList<String> op, ArrayList<Long> operand) {
ArrayList<Long> list = new ArrayList<>();
list.add(operand.get(0));
for (int i = 0; i < op.size(); i++) {
if (op.get(i).equals("+")) | else if (op.get(i).equals("-"))
list.add(-operand.get(i + 1));
else if (op.get(i).equals("*"))
list.set(list.size() - 1, list.get(list.size() - 1) * operand.get(i + 1));
else if (op.get(i).equals("//"))
list.set(list.size() - 1, list.get(list.size() - 1) / operand.get(i + 1));
else if (op.get(i).equals("**"))
list.set(list.size() - 1, (long) Math.pow(list.get(list.size() - 1), operand.get(i + 1)));
}
return list.stream().mapToLong(x -> x).sum();
}
} | list.add(operand.get(i + 1)); | }
public static void main(String[] args) {
assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"**", (String)"*", (String)"+"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (37l));
assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"+", (String)"*", (String)"-"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (9l));
assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"//", (String)"*"))), (new ArrayList<Long>(Arrays.asList((long)7l, (long)3l, (long)4l)))) == (8l));
}
}
|
humaneval-HumanEval_68_pluck.json-L39 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// "Given an array array list representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array array list, [ smalest_value, its index ],
// If there are no even values or the given array array list is empty, return [].
// Example 1:
// >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l)))
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l)))
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// >>> pluck((new ArrayList<Long>(Arrays.asList())))
// (new ArrayList<Long>(Arrays.asList()))
// Example 4:
// >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l))))
// (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
public static ArrayList<Long> pluck(ArrayList<Long> arr) {
int minIndex = -1;
long minValue = -1;
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) % 2 == 0) { | minIndex = i;
minValue = arr.get(i);
}
}
}
ArrayList<Long> newArr = new ArrayList<Long>();
if (minIndex == -1) {
return newArr;
}
newArr.add(minValue);
newArr.add((long)minIndex);
return newArr;
}
} | if (minIndex == -1 || arr.get(i) < minValue) { | }
public static void main(String[] args) {
assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l)))));
assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_110_exchange.json-L21 | py | from typing import List
def exchange(lst1: List[int], lst2: List[int]) -> str:
"""In this problem, you will implement a function that takes two lists of numbers,
and determines whether it is possible to perform an exchange of elements
between them to make lst1 a list 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 lists will be non-empty.
"""
count = 0
for x in lst1:
if x % 2 == 1: | for y in lst2:
if y % 2 == 0:
count -= 1
if count > 0:
return "NO"
else:
return "YES" | count += 1 | def check(candidate):
assert candidate([1, 2, 3, 4], [1, 2, 3, 4]) == 'YES'
assert candidate([1, 2, 3, 4], [1, 5, 3, 4]) == 'NO'
assert candidate([1, 2, 3, 4], [2, 1, 4, 3]) == 'YES'
assert candidate([5, 7, 3], [2, 6, 4]) == 'YES'
assert candidate([5, 7, 3], [2, 6, 3]) == 'NO'
assert candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]) == 'NO'
assert candidate([100, 200], [200, 200]) == 'YES'
def test_check():
check(exchange)
test_check()
|
humaneval-HumanEval_94_skjkasdkd.json-L53 | 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) {
if (number > largestPrime) {
largestPrime = number;
}
}
}
if (largestPrime == 0) {
return 0l;
} | long output = 0l;
while (largestPrime > 0) {
output += largestPrime % 10;
largestPrime /= 10;
}
return output;
}
}
} | else { | }
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_83_starts_one_ends.json-L7 | py | def starts_one_ends(n: int) -> int:
"""
Given a positive integer n, return the count of the numbers of n-digit
positive integers that start or end with 1.
"""
count = 0 | if i // 10**(n-1) == 1 or i % 10 == 1:
count += 1
return count
| for i in range(10**(n-1), 10**n): | def check(candidate):
assert candidate(1) == 1
assert candidate(2) == 18
assert candidate(3) == 180
assert candidate(4) == 1800
assert candidate(5) == 18000
def test_check():
check(starts_one_ends)
test_check()
|
humaneval-HumanEval_108_count_nums.json-L29 | js | //Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// >>> count_nums([])
// 0
// >>> count_nums([-1, 11, -11])
// 1
// >>> count_nums([1, 1, 2])
// 3
function count_nums(arr){
if(!arr.length) {
return 0;
}
var count = 0;
for(var i = 0; i < arr.length; i++) {
var sum = 0;
var str = arr[i].toString();
if(str[0] === '-') {
sum += Number(str[0] + str[1]);
for(var j = 2; j < str.length; j++) {
sum += Number(str[j]);
}
} else {
for(var k = 0; k < str.length; k++) {
sum += Number(str[k]);
}
} | count++;
}
}
return count;
} | if(sum > 0) { | const assert = require('node:assert');
function test() {
let candidate = count_nums;
assert.deepEqual(candidate([]),0);
assert.deepEqual(candidate([-1, -2, 0]),0);
assert.deepEqual(candidate([1, 1, 2, -2, 3, 4, 5]),6);
assert.deepEqual(candidate([1, 6, 9, -6, 0, 1, 5]),5);
assert.deepEqual(candidate([1, 100, 98, -7, 1, -1]),4);
assert.deepEqual(candidate([12, 23, 34, -45, -56, 0]),5);
assert.deepEqual(candidate([0, 1]),1);
assert.deepEqual(candidate([1]),1);
}
test(); |