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-L19 | 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];
if(sum < minSum){
minSum = sum;
}
if(sum > 0){
sum = 0;
} | return 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_131_digits.json-L14 | py | def digits(n: int) -> int:
"""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
"""
if n < 10:
return n if n % 2 == 1 else 0 | return digits(d) * (m if m % 2 == 1 else 1)
| d, m = divmod(n, 10) | def check(candidate):
assert candidate(5) == 5
assert candidate(54) == 5
assert candidate(120) == 1
assert candidate(5014) == 5
assert candidate(98765) == 315
assert candidate(5576543) == 2625
assert candidate(2468) == 0
def test_check():
check(digits)
test_check()
|
humaneval-HumanEval_9_rolling_max.json-L19 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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++) {
results.add(numbers.subList(0, i + 1).stream().max(Long::compare).get());
}
return results; | } | } | }
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_129_minPath.json-L30 | js | //Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)
// [1, 2, 1]
// >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)
// [1]
function minPath(grid, k){
let n = grid.length;
let path = [];
let startCell = grid[0][0];
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){ | if(curr < startCell){
startCell = curr;
}
}
}
let currCell = startCell;
for(let l = 0; l < k; l++){
path.push(currCell);
let neighbours = [];
let x = null;
let y = null;
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
if(grid[i][j] === currCell){
x = i;
y = j;
}
}
}
if(x > 0){
neighbours.push(grid[x - 1][y]);
}
if(x < n - 1){
neighbours.push(grid[x + 1][y]);
}
if(y > 0){
neighbours.push(grid[x][y - 1]);
}
if(y < n - 1){
neighbours.push(grid[x][y + 1]);
}
let nextCell = neighbours[0];
for(let i = 0; i < neighbours.length; i++){
let curr = neighbours[i];
if(curr < nextCell){
nextCell = curr;
}
}
currCell = nextCell;
}
return path;
} | let curr = grid[i][j]; | const assert = require('node:assert');
function test() {
let candidate = minPath;
assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]);
assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]);
assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]);
assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]);
assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]);
assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]);
assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]);
assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]);
assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]);
assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]);
assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]);
}
test(); |
humaneval-HumanEval_33_sort_third.json-L17 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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_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;
}
} | ArrayList<Long> l_r = new ArrayList<Long>(); | }
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_19_sort_numbers.json-L26 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Input 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
// >>> sortNumbers(("three one five"))
// ("one three five")
public static String sortNumbers(String numbers) {
String [] nums = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
HashMap<String, Integer> indexMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
indexMap.put(nums[i], i);
}
String [] split = numbers.split(" ");
Arrays.sort(split, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return indexMap.get(s1) - indexMap.get(s2);
} | return String.join(" ", split);
}
} | }); | }
public static void main(String[] args) {
assert(sortNumbers(("")).equals(("")));
assert(sortNumbers(("three")).equals(("three")));
assert(sortNumbers(("three five nine")).equals(("three five nine")));
assert(sortNumbers(("five zero four seven nine eight")).equals(("zero four five seven eight nine")));
assert(sortNumbers(("six five four three two one zero")).equals(("zero one two three four five six")));
}
}
|
humaneval-HumanEval_3_below_zero.json-L15 | js | //You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// >>> below_zero([1, 2, 3])
// false
// >>> below_zero([1, 2, -4, 5])
// true
function below_zero(operations){
var sum = 0;
for (var i = 0; i < operations.length; i++) {
sum += operations[i];
if (sum < 0) {
return true;
} | return false;
}
| } | const assert = require('node:assert');
function test() {
let candidate = below_zero;
assert.deepEqual(candidate([]),false);
assert.deepEqual(candidate([1, 2, -3, 1, 2, -3]),false);
assert.deepEqual(candidate([1, 2, -4, 5, 6]),true);
assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -4]),false);
assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -5]),true);
assert.deepEqual(candidate([1, -2, 2, -2, 5, -5, 4, -4]),true);
}
test(); |
humaneval-HumanEval_117_select_words.json-L28 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array array list of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array list.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// >>> selectWords(("Mary had a little lamb"), (4l))
// (new ArrayList<String>(Arrays.asList((String)"little")))
// >>> selectWords(("Mary had a little lamb"), (3l))
// (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb")))
// >>> selectWords(("simple white space"), (2l))
// (new ArrayList<String>(Arrays.asList()))
// >>> selectWords(("Hello world"), (4l))
// (new ArrayList<String>(Arrays.asList((String)"world")))
// >>> selectWords(("Uncle sam"), (3l))
// (new ArrayList<String>(Arrays.asList((String)"Uncle")))
public static ArrayList<String> selectWords(String s, long n) {
ArrayList<String> ret = new ArrayList<String>();
String[] words = s.split(" "); | String wordInLowerCase = word.toLowerCase();
long consonants = 0l;
for (char c : wordInLowerCase.toCharArray()) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
consonants++;
break;
}
}
if (consonants == n) {
ret.add(word);
}
}
return ret;
}
} | for (String word : words) { | }
public static void main(String[] args) {
assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little")))));
assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb")))));
assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList()))));
assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world")))));
assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle")))));
assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList()))));
assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f")))));
}
}
|
humaneval-HumanEval_149_sorted_list_sum.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 {
// Write a function that accepts an array array list of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array list with a sorted order,
// The array list is always an array array list of strings and never an array array list of numbers,
// and it may contain duplicates.
// The order of the array list should be ascending by length of each word, and you
// should return the array list sorted by that rule.
// If two words have the same length, sort the array list alphabetically.
// The function should return an array array list of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// >>> listSort((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa"))))
// (new ArrayList<String>(Arrays.asList((String)"aa")))
// >>> listSort((new ArrayList<String>(Arrays.asList((String)"ab", (String)"a", (String)"aaa", (String)"cd"))))
// (new ArrayList<String>(Arrays.asList((String)"ab", (String)"cd")))
public static ArrayList<String> sortedListSum(ArrayList<String> lst) {
ArrayList<String> result = new ArrayList<String>(); | if (s.length() % 2 == 0) {
result.add(s);
}
}
Collections.sort(result, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
}
return s1.length() - s2.length();
}
});
return result;
}
} | for (String s : lst) { | }
public static void main(String[] args) {
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa")))).equals((new ArrayList<String>(Arrays.asList((String)"aa")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"school", (String)"AI", (String)"asdf", (String)"b")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"asdf", (String)"school")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"b", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList()))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"dcba", (String)"abcd", (String)"a")))).equals((new ArrayList<String>(Arrays.asList((String)"abcd", (String)"dcba")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"a", (String)"b", (String)"b", (String)"c", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList()))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aaaa", (String)"bbbb", (String)"dd", (String)"cc")))).equals((new ArrayList<String>(Arrays.asList((String)"cc", (String)"dd", (String)"aaaa", (String)"bbbb")))));
}
}
|
humaneval-HumanEval_119_match_parens.json-L22 | js | //You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> match_parens(["()(", ")"])
// "Yes"
// >>> match_parens([")", ")"])
// "No"
function match_parens(lst){
const open = '(';
const close = ')';
const is_good = (s) => {
let stack = [];
for (let p of s){
if (p === open){
stack.push(p); | if (stack.length === 0){
return false;
}
stack.pop();
}
}
return stack.length === 0;
};
const str1 = lst[0];
const str2 = lst[1];
if (is_good(str1 + str2)){
return 'Yes';
}
if (is_good(str2 + str1)){
return 'Yes';
}
return 'No';
} | } else if (p === close){ | const assert = require('node:assert');
function test() {
let candidate = match_parens;
assert.deepEqual(candidate(["()(", ")"]),"Yes");
assert.deepEqual(candidate([")", ")"]),"No");
assert.deepEqual(candidate(["(()(())", "())())"]),"No");
assert.deepEqual(candidate([")())", "(()()("]),"Yes");
assert.deepEqual(candidate(["(())))", "(()())(("]),"Yes");
assert.deepEqual(candidate(["()", "())"]),"No");
assert.deepEqual(candidate(["(()(", "()))()"]),"Yes");
assert.deepEqual(candidate(["((((", "((())"]),"No");
assert.deepEqual(candidate([")(()", "(()("]),"No");
assert.deepEqual(candidate([")(", ")("]),"No");
assert.deepEqual(candidate(["(", ")"]),"Yes");
assert.deepEqual(candidate([")", "("]),"Yes");
}
test(); |
humaneval-HumanEval_140_fix_spaces.json-L14 | js | //Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// >>> fix_spaces(" Example")
// "Example"
// >>> fix_spaces(" Example 1")
// "Example_1"
// >>> fix_spaces(" Example 2")
// "_Example_2"
// >>> fix_spaces(" Example 3")
// "_Example-3"
function fix_spaces(text){
var n = text.replace(/\s/g, "_"); | return k;
}
| var k = n.replace(/___/g, "-"); | const assert = require('node:assert');
function test() {
let candidate = fix_spaces;
assert.deepEqual(candidate("Example"),"Example");
assert.deepEqual(candidate("Mudasir Hanif "),"Mudasir_Hanif_");
assert.deepEqual(candidate("Yellow Yellow Dirty Fellow"),"Yellow_Yellow__Dirty__Fellow");
assert.deepEqual(candidate("Exa mple"),"Exa-mple");
assert.deepEqual(candidate(" Exa 1 2 2 mple"),"-Exa_1_2_2_mple");
}
test(); |
humaneval-HumanEval_147_get_max_triples.json-L35 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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_95_check_dict_case.json-L37 | js | //Given an object, return true if all keys are strings in lower
// case or all keys are strings in upper case, else return false.
// The function should return false is the given object is empty.
// Examples:
// >>> check_dict_case({"a": "apple", "b": "banana"})
// true
// >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"})
// false
// >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"})
// false
// >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"})
// false
// >>> check_dict_case({"STATE": "NC", "ZIP": "12345"})
// true
function check_dict_case(dict){
if (Object.keys(dict).length == 0){
return false;
}
var case_type = -1;
for (let key in dict){
if (typeof key == "string"){
if (case_type == -1){
if (key == key.toUpperCase()){
case_type = 1;
}
else if (key == key.toLowerCase()){
case_type = 0;
}
else{
return false;
}
}
else if (case_type == 1){
if (key != key.toUpperCase()){
return false;
} | else if (case_type == 0){
if (key != key.toLowerCase()){
return false;
}
}
}
else{
return false;
}
}
return true;
} | } | 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_100_make_a_pile.json-L16 | js | //Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// >>> make_a_pile(3)
// [3, 5, 7]
function make_a_pile(n){
let arr = [];
for(let i = 0; i < n; i++){
arr.push(n + (i * 2));
} | } | return arr; | const assert = require('node:assert');
function test() {
let candidate = make_a_pile;
assert.deepEqual(candidate(3),[3, 5, 7]);
assert.deepEqual(candidate(4),[4, 6, 8, 10]);
assert.deepEqual(candidate(5),[5, 7, 9, 11, 13]);
assert.deepEqual(candidate(6),[6, 8, 10, 12, 14, 16]);
assert.deepEqual(candidate(8),[8, 10, 12, 14, 16, 18, 20, 22]);
}
test(); |
humaneval-HumanEval_40_triples_sum_to_zero.json-L23 | py | from typing import List
def triples_sum_to_zero(l: List[int]) -> bool:
"""
triples_sum_to_zero takes a list of integers as an input.
it returns True if there are three distinct elements in the list that
sum to zero, and False otherwise.
>>> triples_sum_to_zero([1, 3, 5, 0])
False
>>> triples_sum_to_zero([1, 3, -2, 1])
True
>>> triples_sum_to_zero([1, 2, 3, 7])
False
>>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])
True
>>> triples_sum_to_zero([1])
False
"""
assert len(l) > 0, "The input list cannot be empty"
l.sort()
for i in range(len(l)): | for k in range(j + 1, len(l)):
if l[i] + l[j] + l[k] == 0:
return True
return False
| for j in range(i + 1, len(l)): | def check(candidate):
assert candidate([1, 3, 5, 0]) == False
assert candidate([1, 3, 5, -1]) == False
assert candidate([1, 3, -2, 1]) == True
assert candidate([1, 2, 3, 7]) == False
assert candidate([1, 2, 5, 7]) == False
assert candidate([2, 4, -5, 3, 9, 7]) == True
assert candidate([1]) == False
assert candidate([1, 3, 5, -100]) == False
assert candidate([100, 3, 5, -100]) == False
def test_check():
check(triples_sum_to_zero)
test_check()
|
humaneval-HumanEval_52_below_threshold.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 true if all numbers in the array list l are below threshold t.
// >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l))
// (true)
// >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l))
// (false)
public static boolean belowThreshold(ArrayList<Long> l, long t) {
Long[] a = l.toArray(new Long[l.size()]); | if (a[i] >= t) {
return false;
}
}
return true;
}
} | for (int i = 0; i < a.length; i++) { | }
public static void main(String[] args) {
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) == (true));
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) == (false));
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (21l)) == (true));
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (22l)) == (true));
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (11l)) == (true));
assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (10l)) == (false));
}
}
|
humaneval-HumanEval_80_is_happy.json-L19 | py | def is_happy(s: str) -> bool:
"""You are given a string s.
Your task is to check if the string is happy or not.
A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
For example:
>>> is_happy(a)
False
>>> is_happy(aa)
False
>>> is_happy(abcd)
True
>>> is_happy(aabb)
False
>>> is_happy(adb)
True
>>> is_happy(xyy)
False
"""
| if n < 3:
return False
else:
for i in range(n - 2):
if s[i] == s[i + 1] or s[i] == s[i + 2] or s[i + 1] == s[i + 2]:
return False
return True
| n = len(s) | def check(candidate):
assert candidate('a') == False
assert candidate('aa') == False
assert candidate('abcd') == True
assert candidate('aabb') == False
assert candidate('adb') == True
assert candidate('xyy') == False
assert candidate('iopaxpoi') == True
assert candidate('iopaxioi') == False
def test_check():
check(is_happy)
test_check()
|
humaneval-HumanEval_116_sort_array.json-L13 | js | //In this Kata, you have to sort an array 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:
// >>> sort_array([1, 5, 2, 3, 4])
// [1, 2, 3, 4, 5]
// >>> sort_array([-2, -3, -4, -5, -6])
// [-6, -5, -4, -3, -2]
// >>> sort_array([1, 0, 2, 3, 4])
// [0, 1, 2, 3, 4]
function sort_array(arr){
return arr.sort((a, b) => { | let bBinary = b.toString(2).split('').filter(el => el === '1').length;
if (aBinary === bBinary) {
return a - b;
} else {
return aBinary - bBinary;
}
});
} | let aBinary = a.toString(2).split('').filter(el => el === '1').length; | const assert = require('node:assert');
function test() {
let candidate = sort_array;
assert.deepEqual(candidate([1, 5, 2, 3, 4]),[1, 2, 4, 3, 5]);
assert.deepEqual(candidate([-2, -3, -4, -5, -6]),[-4, -2, -6, -5, -3]);
assert.deepEqual(candidate([1, 0, 2, 3, 4]),[0, 1, 2, 4, 3]);
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]),[2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77]);
assert.deepEqual(candidate([3, 6, 44, 12, 32, 5]),[32, 3, 5, 6, 12, 44]);
assert.deepEqual(candidate([2, 4, 8, 16, 32]),[2, 4, 8, 16, 32]);
assert.deepEqual(candidate([2, 4, 8, 16, 32]),[2, 4, 8, 16, 32]);
}
test(); |
humaneval-HumanEval_33_sort_third.json-L29 | js | //This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> sort_third([1, 2, 3])
// [1, 2, 3]
// >>> sort_third([5, 6, 3, 4, 8, 9, 2])
// [2, 6, 3, 4, 8, 9, 5]
function sort_third(l){
let x=[];
let y=[];
let k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
y[k]=l[i];
k=k+1;
}
else{
x[i]=l[i];
}
}
y.sort();
k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
x[i]=y[k];
k=k+1;
}
} | } | return x; | const assert = require('node:assert');
function test() {
let candidate = sort_third;
assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2]),[2, 6, 3, 4, 8, 9, 5]);
assert.deepEqual(candidate([5, 8, 3, 4, 6, 9, 2]),[2, 8, 3, 4, 6, 9, 5]);
assert.deepEqual(candidate([5, 6, 9, 4, 8, 3, 2]),[2, 6, 9, 4, 8, 3, 5]);
assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2, 1]),[2, 6, 3, 4, 8, 9, 5, 1]);
}
test(); |
humaneval-HumanEval_125_split_words.json-L17 | js | //Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// >>> split_words("Hello world!")
// ["Hello", "world!"]
// >>> split_words("Hello,world!")
// ["Hello", "world!"]
// >>> split_words("abcdef")
// 3
function split_words(txt){
if(txt.includes(' ')){
return txt.split(' ');
}
else if(txt.includes(',')){
return txt.split(','); | else{
let count = 0;
for(let i = 0; i < txt.length; i++){
if(i % 2 != 0){
if(txt[i] == txt[i].toLowerCase()){
count++;
}
}
}
return count;
}
} | } | const assert = require('node:assert');
function test() {
let candidate = split_words;
assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]);
assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]);
assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]);
assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]);
assert.deepEqual(candidate("abcdef"),3);
assert.deepEqual(candidate("aaabb"),2);
assert.deepEqual(candidate("aaaBb"),1);
assert.deepEqual(candidate(""),0);
}
test(); |
humaneval-HumanEval_86_anti_shuffle.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 {
// 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_57_monotonic.json-L25 | js | //Return true is array elements are monotonically increasing or decreasing.
// >>> monotonic([1, 2, 4, 20])
// true
// >>> monotonic([1, 20, 4, 10])
// false
// >>> monotonic([4, 1, 0, -10])
// true
function monotonic(l){
if(l.length <= 1){
return true;
}
if(l[0] < l[1]){
for(var i = 1; i < l.length - 1; i++){
if(l[i] > l[i + 1]){
return false;
}
}
}
else{
for(var i = 1; i < l.length - 1; i++){
if(l[i] < l[i + 1]){
return false;
}
} | return true;
}
| } | const assert = require('node:assert');
function test() {
let candidate = monotonic;
assert.deepEqual(candidate([1, 2, 4, 10]),true);
assert.deepEqual(candidate([1, 2, 4, 20]),true);
assert.deepEqual(candidate([1, 20, 4, 10]),false);
assert.deepEqual(candidate([4, 1, 0, -10]),true);
assert.deepEqual(candidate([4, 1, 1, 0]),true);
assert.deepEqual(candidate([1, 2, 3, 2, 5, 60]),false);
assert.deepEqual(candidate([1, 2, 3, 4, 5, 60]),true);
assert.deepEqual(candidate([9, 9, 9, 9]),true);
}
test(); |
humaneval-HumanEval_128_prod_signs.json-L31 | 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_70_strange_sort_list.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 array list of integers, return array list in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l)))
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))
// (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList())))
// (new ArrayList<Long>(Arrays.asList()))
public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) {
if (lst.size() <= 1) {
return lst;
}
ArrayList<Long> result = new ArrayList<Long>(); | Collections.sort(sorted);
int min = 0;
int max = sorted.size() - 1;
while (min <= max) {
result.add(sorted.get(min));
min++;
if (min <= max) {
result.add(sorted.get(max));
max--;
}
}
return result;
}
} | ArrayList<Long> sorted = new ArrayList<Long>(lst); | }
public static void main(String[] args) {
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l)))));
}
}
|
humaneval-HumanEval_25_factorize.json-L18 | py | from typing import List
def factorize(n: int) -> List[int]:
""" Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the product of all factors
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
"""
factors = []
i = 2
while i <= n:
while n % i == 0: | n = n / i
i += 1
return factors
| factors.append(i) | def check(candidate):
assert candidate(2) == [2]
assert candidate(4) == [2, 2]
assert candidate(8) == [2, 2, 2]
assert candidate(57) == [3, 19]
assert candidate(3249) == [3, 3, 19, 19]
assert candidate(185193) == [3, 3, 3, 19, 19, 19]
assert candidate(20577) == [3, 19, 19, 19]
assert candidate(18) == [2, 3, 3]
def test_check():
check(factorize)
test_check()
|
humaneval-HumanEval_28_concatenate.json-L11 | js | //Concatenate array of strings into a single string
// >>> concatenate([])
// ""
// >>> concatenate(["a", "b", "c"])
// "abc"
function concatenate(strings){
if(strings.length === 0){
return "";
}
var string = strings.join(""); | }
| return string; | const assert = require('node:assert');
function test() {
let candidate = concatenate;
assert.deepEqual(candidate([]),"");
assert.deepEqual(candidate(["x", "y", "z"]),"xyz");
assert.deepEqual(candidate(["x", "y", "z", "w", "k"]),"xyzwk");
}
test(); |
humaneval-HumanEval_48_is_palindrome.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 {
// Checks if given string is a palindrome
// >>> isPalindrome((""))
// (true)
// >>> isPalindrome(("aba"))
// (true)
// >>> isPalindrome(("aaaaa"))
// (true)
// >>> isPalindrome(("zbcd"))
// (false)
public static boolean isPalindrome(String text) {
boolean isPalindrome = true;
int left = 0; | while (left < right) {
if (text.charAt(left) != text.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
return isPalindrome;
}
} | int right = text.length() - 1; | }
public static void main(String[] args) {
assert(isPalindrome(("")) == (true));
assert(isPalindrome(("aba")) == (true));
assert(isPalindrome(("aaaaa")) == (true));
assert(isPalindrome(("zbcd")) == (false));
assert(isPalindrome(("xywyx")) == (true));
assert(isPalindrome(("xywyz")) == (false));
assert(isPalindrome(("xywzx")) == (false));
}
}
|
humaneval-HumanEval_108_count_nums.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 count_nums which takes an array array list of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// >>> countNums((new ArrayList<Long>(Arrays.asList())))
// (0l)
// >>> countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)11l, (long)-11l))))
// (1l)
// >>> countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l))))
// (3l)
public static long countNums(ArrayList<Long> arr) {
long result = 0l;
for (long i : arr) {
String str = String.valueOf(i);
int sum = 0;
if (str.startsWith("-")) { | for (int j = 2; j < str.length(); j++) {
sum = sum + (int) Character.getNumericValue(str.charAt(j));
}
} else {
for (int j = 0; j < str.length(); j++) {
sum = sum + (int) Character.getNumericValue(str.charAt(j));
}
}
if (sum > 0) {
result++;
}
}
return result;
}
} | sum = sum - (int) Character.getNumericValue(str.charAt(1)); | }
public static void main(String[] args) {
assert(countNums((new ArrayList<Long>(Arrays.asList()))) == (0l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)0l)))) == (0l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l, (long)-2l, (long)3l, (long)4l, (long)5l)))) == (6l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)6l, (long)9l, (long)-6l, (long)0l, (long)1l, (long)5l)))) == (5l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)100l, (long)98l, (long)-7l, (long)1l, (long)-1l)))) == (4l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)12l, (long)23l, (long)34l, (long)-45l, (long)-56l, (long)0l)))) == (5l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l));
assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l)))) == (1l));
}
}
|
humaneval-HumanEval_78_hex_key.json-L37 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// >>> hexKey(("AB"))
// (1l)
// >>> hexKey(("1077E"))
// (2l)
// >>> hexKey(("ABED1A33"))
// (4l)
// >>> hexKey(("123456789ABCDEF0"))
// (6l)
// >>> hexKey(("2020"))
// (2l)
public static long hexKey(String num) {
long result = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == '2' || num.charAt(i) == '3' || num.charAt(i) == '5' || num.charAt(i) == '7' || num.charAt(i) == 'B' || num.charAt(i) == 'D') {
result++;
}
} | }
} | return result; | }
public static void main(String[] args) {
assert(hexKey(("AB")) == (1l));
assert(hexKey(("1077E")) == (2l));
assert(hexKey(("ABED1A33")) == (4l));
assert(hexKey(("2020")) == (2l));
assert(hexKey(("123456789ABCDEF0")) == (6l));
assert(hexKey(("112233445566778899AABBCCDDEEFF00")) == (12l));
}
}
|
humaneval-HumanEval_48_is_palindrome.json-L28 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Checks if given string is a palindrome
// >>> isPalindrome((""))
// (true)
// >>> isPalindrome(("aba"))
// (true)
// >>> isPalindrome(("aaaaa"))
// (true)
// >>> isPalindrome(("zbcd"))
// (false)
public static boolean isPalindrome(String text) {
boolean isPalindrome = true;
int left = 0;
int right = text.length() - 1;
while (left < right) {
if (text.charAt(left) != text.charAt(right)) {
isPalindrome = false;
break;
}
left++; | }
return isPalindrome;
}
} | right--; | }
public static void main(String[] args) {
assert(isPalindrome(("")) == (true));
assert(isPalindrome(("aba")) == (true));
assert(isPalindrome(("aaaaa")) == (true));
assert(isPalindrome(("zbcd")) == (false));
assert(isPalindrome(("xywyx")) == (true));
assert(isPalindrome(("xywyz")) == (false));
assert(isPalindrome(("xywzx")) == (false));
}
}
|
humaneval-HumanEval_75_is_multiply_prime.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 returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// >>> isMultiplyPrime((30l))
// (true)
// 30 = 2 * 3 * 5
public static boolean isMultiplyPrime(long a) {
if (a == 1) {
return false;
}
if (a == 2) {
return true;
}
long copyOfInput = a;
ArrayList<Long> arr = new ArrayList<Long>();
while (a % 2 == 0) {
arr.add(2l);
a /= 2;
} | while (a % i == 0) {
arr.add(i);
a /= i;
}
}
if (a > 2) {
arr.add(a);
}
return arr.size() == 3;
}
} | for (long i = 3; i <= Math.sqrt(a); i += 2) { | }
public static void main(String[] args) {
assert(isMultiplyPrime((5l)) == (false));
assert(isMultiplyPrime((30l)) == (true));
assert(isMultiplyPrime((8l)) == (true));
assert(isMultiplyPrime((10l)) == (false));
assert(isMultiplyPrime((125l)) == (true));
assert(isMultiplyPrime((105l)) == (true));
assert(isMultiplyPrime((126l)) == (false));
assert(isMultiplyPrime((729l)) == (false));
assert(isMultiplyPrime((891l)) == (false));
assert(isMultiplyPrime((1001l)) == (true));
}
}
|
humaneval-HumanEval_44_change_base.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 {
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// >>> changeBase((8l), (3l))
// ("22")
// >>> changeBase((8l), (2l))
// ("1000")
// >>> changeBase((7l), (2l))
// ("111")
public static String changeBase(long x, long base) {
if (x<0 || base<2 || base>9) {
throw new IllegalArgumentException("bad input");
}
if (x==0) {
return "0";
} | while (x>0) {
sb.append(x%base);
x = x/base;
}
return sb.reverse().toString();
}
} | StringBuilder sb = new StringBuilder(); | }
public static void main(String[] args) {
assert(changeBase((8l), (3l)).equals(("22")));
assert(changeBase((9l), (3l)).equals(("100")));
assert(changeBase((234l), (2l)).equals(("11101010")));
assert(changeBase((16l), (2l)).equals(("10000")));
assert(changeBase((8l), (2l)).equals(("1000")));
assert(changeBase((7l), (2l)).equals(("111")));
assert(changeBase((2l), (3l)).equals(("2")));
assert(changeBase((3l), (4l)).equals(("3")));
assert(changeBase((4l), (5l)).equals(("4")));
assert(changeBase((5l), (6l)).equals(("5")));
assert(changeBase((6l), (7l)).equals(("6")));
assert(changeBase((7l), (8l)).equals(("7")));
}
}
|
humaneval-HumanEval_93_encode.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 {
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// >>> encode(("test"))
// ("TGST")
// >>> encode(("This is a message"))
// ("tHKS KS C MGSSCGG")
public static String encode(String message) {
char[] arr = message.toCharArray();
char[] vowels = "AEIOUaeiou".toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Arrays.binarySearch(vowels, arr[i]) > -1) {
arr[i] = (char) (arr[i] + 2);
} | arr[i] = Character.toLowerCase(arr[i]);
} else {
arr[i] = Character.toUpperCase(arr[i]);
}
}
return new String(arr);
}
} | if (Character.isUpperCase(arr[i])) { | }
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_91_is_bored.json-L13 | 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
"""
| sentences = S.split('.')
for sentence in sentences:
words = sentence.split()
if words and words[0] == 'I':
boredoms += 1
return boredoms
| boredoms = 0 | 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_25_factorize.json-L19 | py | from typing import List
def factorize(n: int) -> List[int]:
""" Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the product of all factors
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
"""
factors = []
i = 2
while i <= n:
while n % i == 0:
factors.append(i) | i += 1
return factors
| n = n / i | def check(candidate):
assert candidate(2) == [2]
assert candidate(4) == [2, 2]
assert candidate(8) == [2, 2, 2]
assert candidate(57) == [3, 19]
assert candidate(3249) == [3, 3, 19, 19]
assert candidate(185193) == [3, 3, 3, 19, 19, 19]
assert candidate(20577) == [3, 19, 19, 19]
assert candidate(18) == [2, 3, 3]
def test_check():
check(factorize)
test_check()
|
humaneval-HumanEval_98_count_upper.json-L10 | js | //Given a string s, count the number of uppercase vowels in even indices.
// For example:
// >>> count_upper("aBCdEf")
// 1
// >>> count_upper("abcdefg")
// 0
// >>> count_upper("dBBE")
// 0
function count_upper(s){
| var result = 0;
var vowel = ['A', 'E', 'I', 'O', 'U'];
for (index = 0; index < s.length; index += 2){
if (vowel.indexOf(s[index]) > -1){
result += 1;
}
}
return result;
} | var index; | const assert = require('node:assert');
function test() {
let candidate = count_upper;
assert.deepEqual(candidate("aBCdEf"),1);
assert.deepEqual(candidate("abcdefg"),0);
assert.deepEqual(candidate("dBBE"),0);
assert.deepEqual(candidate("B"),0);
assert.deepEqual(candidate("U"),1);
assert.deepEqual(candidate(""),0);
assert.deepEqual(candidate("EEEE"),2);
}
test(); |
humaneval-HumanEval_67_fruit_distribution.json-L20 | py | def fruit_distribution(s: str, n: int) -> int:
"""
In this task, you will be given a string that represents a number of apples and oranges
that are distributed in a basket of fruit this basket contains
apples, oranges, and mango fruits. Given the string that represents the total number of
the oranges and apples and an integer that represent the total number of the fruits
in the basket return the number of the mango fruits in the basket.
for examble:
>>> fruit_distribution('5 apples and 6 oranges', 19)
8
>>> fruit_distribution('0 apples and 1 oranges', 3)
2
>>> fruit_distribution('2 apples and 3 oranges', 100)
95
>>> fruit_distribution('100 apples and 1 oranges', 120)
19
"""
fruits = []
for fruit in s.split(' '): | fruits.append(int(fruit))
except:
pass
return n - sum(fruits)
| try: | def check(candidate):
assert candidate('5 apples and 6 oranges', 19) == 8
assert candidate('5 apples and 6 oranges', 21) == 10
assert candidate('0 apples and 1 oranges', 3) == 2
assert candidate('1 apples and 0 oranges', 3) == 2
assert candidate('2 apples and 3 oranges', 100) == 95
assert candidate('2 apples and 3 oranges', 5) == 0
assert candidate('1 apples and 100 oranges', 120) == 19
def test_check():
check(fruit_distribution)
test_check()
|
humaneval-HumanEval_72_will_it_fly.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 {
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l))
// (false)
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l))
// (false)
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l))
// (true)
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l))
// (true)
// # 3 is less than the maximum possible weight, and it's balanced.
public static boolean willItFly(ArrayList<Long> q, long w) {
if (q.size() == 0) {
return false;
}
if (q.size() == 1) {
return true;
}
Long sum = 0l;
for (int i = 0; i < q.size(); i++) {
sum += q.get(i);
}
if (sum > w) {
return false;
}
for (int i = 0; i < q.size() / 2; i++) {
if (q.get(i) != q.get(q.size() - 1 - i)) {
return false;
} | return true;
}
} | } | }
public static void main(String[] args) {
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true));
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false));
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true));
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false));
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false));
assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true));
}
}
|
humaneval-HumanEval_93_encode.json-L18 | js | //Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// >>> encode("test")
// "TGST"
// >>> encode("This is a message")
// "tHKS KS C MGSSCGG"
function encode(message){
const vowels = "aeiou";
let result = "";
for(let i = 0; i < message.length; i++){
let letter = message[i];
if(vowels.includes(letter.toLowerCase())){
let newIndex = (letter.charCodeAt(0) + 2 - (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))) % 26; | }
result += letter.toUpperCase() === letter ? letter.toLowerCase() : letter.toUpperCase();
}
return result;
} | letter = String.fromCharCode(newIndex + (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))); | const assert = require('node:assert');
function test() {
let candidate = encode;
assert.deepEqual(candidate("TEST"),"tgst");
assert.deepEqual(candidate("Mudasir"),"mWDCSKR");
assert.deepEqual(candidate("YES"),"ygs");
assert.deepEqual(candidate("This is a message"),"tHKS KS C MGSSCGG");
assert.deepEqual(candidate("I DoNt KnOw WhAt tO WrItE"),"k dQnT kNqW wHcT Tq wRkTg");
}
test(); |
humaneval-HumanEval_75_is_multiply_prime.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 {
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// >>> isMultiplyPrime((30l))
// (true)
// 30 = 2 * 3 * 5
public static boolean isMultiplyPrime(long a) {
if (a == 1) {
return false;
}
if (a == 2) {
return true;
}
long copyOfInput = a;
ArrayList<Long> arr = new ArrayList<Long>();
while (a % 2 == 0) {
arr.add(2l);
a /= 2;
}
for (long i = 3; i <= Math.sqrt(a); i += 2) {
while (a % i == 0) {
arr.add(i);
a /= i;
} | if (a > 2) {
arr.add(a);
}
return arr.size() == 3;
}
} | } | }
public static void main(String[] args) {
assert(isMultiplyPrime((5l)) == (false));
assert(isMultiplyPrime((30l)) == (true));
assert(isMultiplyPrime((8l)) == (true));
assert(isMultiplyPrime((10l)) == (false));
assert(isMultiplyPrime((125l)) == (true));
assert(isMultiplyPrime((105l)) == (true));
assert(isMultiplyPrime((126l)) == (false));
assert(isMultiplyPrime((729l)) == (false));
assert(isMultiplyPrime((891l)) == (false));
assert(isMultiplyPrime((1001l)) == (true));
}
}
|
humaneval-HumanEval_37_sort_even.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 {
// This function takes an array array list l and returns an array array list l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// >>> sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))
// >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l)))
public static ArrayList<Long> sortEven(ArrayList<Long> l) {
ArrayList<Long> res = new ArrayList<Long>();
ArrayList<Long> evenIndexed = new ArrayList<Long>();
int index = 0;
for (Long num : l) {
if (index % 2 == 0) {
evenIndexed.add(num);
}
index++;
}
Collections.sort(evenIndexed);
index = 0;
for (Long num : l) {
if (index % 2 == 0) {
res.add(evenIndexed.get(0));
evenIndexed.remove(0);
} else {
res.add(num); | index++;
}
return res;
}
} | } | }
public static void main(String[] args) {
assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))));
assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l)))));
assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l)))));
}
}
|
humaneval-HumanEval_111_histogram.json-L31 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a string 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); | hm.put(sss, 1l);
}
}
long max = 0;
for (String key : hm.keySet()) {
if (hm.get(key) > max) {
max = hm.get(key);
}
}
for (String key : hm.keySet()) {
if (hm.get(key) == max) {
s.put(key, hm.get(key));
}
}
}
return s;
}
} | } else { | }
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_84_solve.json-L21 | js | //Given a positive integer N, return the total sum of its digits in binary.
// Example
// >>> solve(1000)
// "1"
// >>> solve(150)
// "110"
// >>> solve(147)
// "1100"
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
function solve(N){
let newN = N.toString();
let total = 0;
for(let i = 0; i < newN.length; i++){
let digit = newN[i];
total += parseInt(digit);
} | } | return total.toString(2); | const assert = require('node:assert');
function test() {
let candidate = solve;
assert.deepEqual(candidate(1000),"1");
assert.deepEqual(candidate(150),"110");
assert.deepEqual(candidate(147),"1100");
assert.deepEqual(candidate(333),"1001");
assert.deepEqual(candidate(963),"10010");
}
test(); |
humaneval-HumanEval_141_file_name_check.json-L28 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// >>> fileNameCheck(("example.txt"))
// ("Yes")
// >>> fileNameCheck(("1example.dll"))
// ("No")
public static String fileNameCheck(String file_name) {
String result = "No";
String[] tokens = file_name.split("\\.");
if (tokens.length != 2) {
return result; | String extension = tokens[1];
if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) {
return result;
}
String name = tokens[0];
int count = 0;
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
count++;
}
}
if (count > 3) {
return result;
}
if (name.length() == 0) {
return result;
}
if (!Character.isLetter(name.charAt(0))) {
return result;
}
return "Yes";
}
} | } | }
public static void main(String[] args) {
assert(fileNameCheck(("example.txt")).equals(("Yes")));
assert(fileNameCheck(("1example.dll")).equals(("No")));
assert(fileNameCheck(("s1sdf3.asd")).equals(("No")));
assert(fileNameCheck(("K.dll")).equals(("Yes")));
assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes")));
assert(fileNameCheck(("His12FILE94.exe")).equals(("No")));
assert(fileNameCheck(("_Y.txt")).equals(("No")));
assert(fileNameCheck(("?aREYA.exe")).equals(("No")));
assert(fileNameCheck(("/this_is_valid.dll")).equals(("No")));
assert(fileNameCheck(("this_is_valid.wow")).equals(("No")));
assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes")));
assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No")));
assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No")));
assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No")));
assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No")));
assert(fileNameCheck(("all.exe.txt")).equals(("No")));
assert(fileNameCheck(("I563_No.exe")).equals(("Yes")));
assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes")));
assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes")));
assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No")));
assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No")));
assert(fileNameCheck(("final..txt")).equals(("No")));
assert(fileNameCheck(("final132")).equals(("No")));
assert(fileNameCheck(("_f4indsartal132.")).equals(("No")));
assert(fileNameCheck((".txt")).equals(("No")));
assert(fileNameCheck(("s.")).equals(("No")));
}
}
|
humaneval-HumanEval_122_add_elements.json-L10 | js | //Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// >>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)
// 24
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
function add_elements(arr, k){
| for(var i = 0; i < k; i++){
if(arr[i] < 100){
sum += arr[i];
}
}
return sum;
}
| var sum = 0; | const assert = require('node:assert');
function test() {
let candidate = add_elements;
assert.deepEqual(candidate([1, -2, -3, 41, 57, 76, 87, 88, 99], 3),-4);
assert.deepEqual(candidate([111, 121, 3, 4000, 5, 6], 2),0);
assert.deepEqual(candidate([11, 21, 3, 90, 5, 6, 7, 8, 9], 4),125);
assert.deepEqual(candidate([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4),24);
assert.deepEqual(candidate([1], 1),1);
}
test(); |
humaneval-HumanEval_106_f.json-L20 | js | //Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// >>> f(5)
// [1, 2, 6, 24, 15]
function f(n){
var result = [];
var sum = 0;
var factorial = 1;
for(var i = 1; i <= n; i++){
if(i % 2 == 0){
for(var j = 1; j <= i; j++){
factorial *= j;
}
result.push(factorial);
factorial = 1; | for(var k = 1; k <= i; k++){
sum += k;
}
result.push(sum);
sum = 0;
}
}
return result;
} | }else{ | const assert = require('node:assert');
function test() {
let candidate = f;
assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]);
assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]);
assert.deepEqual(candidate(1),[1]);
assert.deepEqual(candidate(3),[1, 2, 6]);
}
test(); |
humaneval-HumanEval_148_bf.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 {
// There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return a pair containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty pair if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf(("Jupiter"), ("Neptune"))
// (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))
// >>> bf(("Earth"), ("Mercury"))
// (ArrayList<String>("Venus"))
// >>> bf(("Mercury"), ("Uranus"))
// (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))
public static ArrayList<String> bf(String planet1, String planet2) {
ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune"));
int indexPlanet1 = planets.indexOf(planet1);
int indexPlanet2 = planets.indexOf(planet2);
int indexMin = 0;
int indexMax = 0;
if (indexPlanet1 >= 0 && indexPlanet2 >= 0) {
if (indexPlanet1 < indexPlanet2) {
indexMin = indexPlanet1;
indexMax = indexPlanet2;
} else {
indexMin = indexPlanet2;
indexMax = indexPlanet1;
}
ArrayList<String> planetsInBetween = new ArrayList<String>();
for (int i = indexMin + 1; i < indexMax; i++) {
planetsInBetween.add(planets.get(i));
}
return planetsInBetween;
} else {
return new ArrayList<String>(); | }
} | } | }
public static void main(String[] args) {
assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus")))));
assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))));
assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_124_valid_date.json-L47 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// >>> validDate(("03-11-2000"))
// (true)
// >>> validDate(("15-01-2012"))
// (false)
// >>> validDate(("04-0-2040"))
// (false)
// >>> validDate(("06-04-2020"))
// (true)
// >>> validDate(("06/04/2020"))
// (false)
public static boolean validDate(String date) {
boolean valid_date = false;
if (date.equals("")) return valid_date;
String[] parts = date.split("-");
if (parts.length != 3) return valid_date;
try {
int month = Integer.parseInt(parts[0]);
int day = Integer.parseInt(parts[1]);
int year = Integer.parseInt(parts[2]);
if (month < 1 || month > 12) return valid_date;
if (month == 2) {
if (day < 1 || day > 29) return valid_date;
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day < 1 || day > 31) return valid_date;
} else {
if (day < 1 || day > 30) return valid_date;
}
valid_date = true;
} catch (Exception e) {
valid_date = false;
} | }
} | return valid_date; | }
public static void main(String[] args) {
assert(validDate(("03-11-2000")) == (true));
assert(validDate(("15-01-2012")) == (false));
assert(validDate(("04-0-2040")) == (false));
assert(validDate(("06-04-2020")) == (true));
assert(validDate(("01-01-2007")) == (true));
assert(validDate(("03-32-2011")) == (false));
assert(validDate(("")) == (false));
assert(validDate(("04-31-3000")) == (false));
assert(validDate(("06-06-2005")) == (true));
assert(validDate(("21-31-2000")) == (false));
assert(validDate(("04-12-2003")) == (true));
assert(validDate(("04122003")) == (false));
assert(validDate(("20030412")) == (false));
assert(validDate(("2003-04")) == (false));
assert(validDate(("2003-04-12")) == (false));
assert(validDate(("04-2003")) == (false));
}
}
|
humaneval-HumanEval_6_parse_nested_parens.json-L16 | py | from typing import List
def parse_nested_parens(paren_string: str) -> List[int]:
""" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
For each of the group, output the deepest level of nesting of parentheses.
E.g. (()()) has maximum two levels of nesting while ((())) has three.
>>> parse_nested_parens('(()()) ((())) () ((())()())')
[2, 3, 1, 3]
"""
result = []
for parens in paren_string.split(' '):
max_depth = 0
current_depth = 0
for paren in parens: | current_depth += 1
max_depth = max(max_depth, current_depth)
elif paren == ')':
current_depth -= 1
result.append(max_depth)
return result
| if paren == '(': | def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3]
assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4]
assert candidate('(()(())((())))') == [4]
def test_check():
check(parse_nested_parens)
test_check()
|
humaneval-HumanEval_75_is_multiply_prime.json-L20 | js | //Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// >>> is_multiply_prime(30)
// true
// 30 = 2 * 3 * 5
function is_multiply_prime(a){
a = Math.abs(a);
const prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
let i = 0;
let check = [];
while(a != 1){
if(a % prime[i] == 0){
a = a / prime[i];
check.push(prime[i]);
}else{
i++;
} | if(check.length == 3){
return true;
}else{
return false;
}
} | } | const assert = require('node:assert');
function test() {
let candidate = is_multiply_prime;
assert.deepEqual(candidate(5),false);
assert.deepEqual(candidate(30),true);
assert.deepEqual(candidate(8),true);
assert.deepEqual(candidate(10),false);
assert.deepEqual(candidate(125),true);
assert.deepEqual(candidate(105),true);
assert.deepEqual(candidate(126),false);
assert.deepEqual(candidate(729),false);
assert.deepEqual(candidate(891),false);
assert.deepEqual(candidate(1001),true);
}
test(); |
humaneval-HumanEval_85_add.json-L10 | js | //Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// >>> add([4, 2, 6, 7])
// 2
function add(lst){
var add = 0;
for(var i = 0; i < lst.length; i++) {
if(lst[i] % 2 == 0 && i % 2 != 0) {
add += lst[i]; | }
return add;
} | } | const assert = require('node:assert');
function test() {
let candidate = add;
assert.deepEqual(candidate([4, 88]),88);
assert.deepEqual(candidate([4, 5, 6, 7, 2, 122]),122);
assert.deepEqual(candidate([4, 0, 6, 7]),0);
assert.deepEqual(candidate([4, 4, 6, 8]),12);
}
test(); |
humaneval-HumanEval_128_prod_signs.json-L20 | 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{ | total += Math.abs(arr[i]);
if(arr[i] < 0){
pro *= -1;
}
else if(arr[i] == 0){
pro *= 0;
}
}
total *= pro;
return total;
}
}
| for(var i = 0; i < len; i++){ | 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_16_count_distinct_characters.json-L13 | js | //Given a string, find out how many distinct characters (regardless of case) does it consist of
// >>> count_distinct_characters("xyzXYZ")
// 3
// >>> count_distinct_characters("Jerry")
// 4
function count_distinct_characters(string){
var arr = string.split("");
var result = [];
for(var i = 0; i < arr.length; i++){
if(result.indexOf(arr[i].toLowerCase()) < 0){
result.push(arr[i].toLowerCase());
} | return result.length;
}
| } | const assert = require('node:assert');
function test() {
let candidate = count_distinct_characters;
assert.deepEqual(candidate(""),0);
assert.deepEqual(candidate("abcde"),5);
assert.deepEqual(candidate("abcdecadeCADE"),5);
assert.deepEqual(candidate("aaaaAAAAaaaa"),1);
assert.deepEqual(candidate("Jerry jERRY JeRRRY"),5);
}
test(); |
humaneval-HumanEval_57_monotonic.json-L10 | js | //Return true is array elements are monotonically increasing or decreasing.
// >>> monotonic([1, 2, 4, 20])
// true
// >>> monotonic([1, 20, 4, 10])
// false
// >>> monotonic([4, 1, 0, -10])
// true
function monotonic(l){
if(l.length <= 1){ | }
if(l[0] < l[1]){
for(var i = 1; i < l.length - 1; i++){
if(l[i] > l[i + 1]){
return false;
}
}
}
else{
for(var i = 1; i < l.length - 1; i++){
if(l[i] < l[i + 1]){
return false;
}
}
}
return true;
}
| return true; | const assert = require('node:assert');
function test() {
let candidate = monotonic;
assert.deepEqual(candidate([1, 2, 4, 10]),true);
assert.deepEqual(candidate([1, 2, 4, 20]),true);
assert.deepEqual(candidate([1, 20, 4, 10]),false);
assert.deepEqual(candidate([4, 1, 0, -10]),true);
assert.deepEqual(candidate([4, 1, 1, 0]),true);
assert.deepEqual(candidate([1, 2, 3, 2, 5, 60]),false);
assert.deepEqual(candidate([1, 2, 3, 4, 5, 60]),true);
assert.deepEqual(candidate([9, 9, 9, 9]),true);
}
test(); |
humaneval-HumanEval_71_triangle_area.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 the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// >>> triangleArea((3l), (4l), (5l))
// (6.0f)
// >>> triangleArea((1l), (2l), (10l))
// (float)-1l
public static float triangleArea(long a, long b, long c) {
if(a + b > c && a + c > b && b + c > a) {
float s = (a + b + c) / 2.0f;
float area = (float)Math.sqrt(s * (s - a) * (s - b) * (s - c));
return (float)Math.round(area * 100) / 100;
}
return -1; | } | } | }
public static void main(String[] args) {
assert(triangleArea((3l), (4l), (5l)) == (6.0f));
assert(triangleArea((1l), (2l), (10l)) == (float)-1l);
assert(triangleArea((4l), (8l), (5l)) == (8.18f));
assert(triangleArea((2l), (2l), (2l)) == (1.73f));
assert(triangleArea((1l), (2l), (3l)) == (float)-1l);
assert(triangleArea((10l), (5l), (7l)) == (16.25f));
assert(triangleArea((2l), (6l), (3l)) == (float)-1l);
assert(triangleArea((1l), (1l), (1l)) == (0.43f));
assert(triangleArea((2l), (2l), (10l)) == (float)-1l);
}
}
|
humaneval-HumanEval_70_strange_sort_list.json-L12 | js | //Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// >>> strange_sort_list([1, 2, 3, 4])
// [1, 4, 2, 3]
// >>> strange_sort_list([5, 5, 5, 5])
// [5, 5, 5, 5]
// >>> strange_sort_list([])
// []
function strange_sort_list(lst){
| return [];
}
var output = [];
var tmp = lst.slice();
for(var i = 0; i < lst.length; i++){
if(i % 2 === 0){
output.push(Math.min.apply(null, tmp));
}
else{
output.push(Math.max.apply(null, tmp));
}
tmp.splice(tmp.indexOf(output[i]), 1);
}
return output;
} | if(lst.length === 0){ | const assert = require('node:assert');
function test() {
let candidate = strange_sort_list;
assert.deepEqual(candidate([1, 2, 3, 4]),[1, 4, 2, 3]);
assert.deepEqual(candidate([5, 6, 7, 8, 9]),[5, 9, 6, 8, 7]);
assert.deepEqual(candidate([1, 2, 3, 4, 5]),[1, 5, 2, 4, 3]);
assert.deepEqual(candidate([5, 6, 7, 8, 9, 1]),[1, 9, 5, 8, 6, 7]);
assert.deepEqual(candidate([5, 5, 5, 5]),[5, 5, 5, 5]);
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7, 8]),[1, 8, 2, 7, 3, 6, 4, 5]);
assert.deepEqual(candidate([0, 2, 2, 2, 5, 5, -5, -5]),[-5, 5, -5, 5, 0, 2, 2, 2]);
assert.deepEqual(candidate([111111]),[111111]);
}
test(); |
humaneval-HumanEval_75_is_multiply_prime.json-L21 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// >>> isMultiplyPrime((30l))
// (true)
// 30 = 2 * 3 * 5
public static boolean isMultiplyPrime(long a) {
if (a == 1) {
return false;
}
if (a == 2) { | }
long copyOfInput = a;
ArrayList<Long> arr = new ArrayList<Long>();
while (a % 2 == 0) {
arr.add(2l);
a /= 2;
}
for (long i = 3; i <= Math.sqrt(a); i += 2) {
while (a % i == 0) {
arr.add(i);
a /= i;
}
}
if (a > 2) {
arr.add(a);
}
return arr.size() == 3;
}
} | return true; | }
public static void main(String[] args) {
assert(isMultiplyPrime((5l)) == (false));
assert(isMultiplyPrime((30l)) == (true));
assert(isMultiplyPrime((8l)) == (true));
assert(isMultiplyPrime((10l)) == (false));
assert(isMultiplyPrime((125l)) == (true));
assert(isMultiplyPrime((105l)) == (true));
assert(isMultiplyPrime((126l)) == (false));
assert(isMultiplyPrime((729l)) == (false));
assert(isMultiplyPrime((891l)) == (false));
assert(isMultiplyPrime((1001l)) == (true));
}
}
|
humaneval-HumanEval_160_do_algebra.json-L47 | 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; | count++;
do_again = false;
}
}
answer = operand[0];
operand.splice(0, 1);
while(operand.length > 0){
switch(operator[0]){
case '+':
answer += operand[0];
break;
case '-':
answer -= operand[0];
break;
}
operand.splice(0, 1);
operator.splice(0, 1);
}
return answer;
}
| default: | 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_6_parse_nested_parens.json-L21 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Input to this function is a string 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()) { | current_depth += 1;
max_depth = Math.max(max_depth, current_depth);
} else if (c == ')') {
current_depth -= 1;
}
}
result.add(max_depth);
}
return result;
}
} | if (c == '(') { | }
public static void main(String[] args) {
assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l)))));
assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))));
assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l)))));
}
}
|
humaneval-HumanEval_68_pluck.json-L29 | js | //"Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// >>> pluck([4, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// >>> pluck([1, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// >>> pluck([])
// []
// Example 4:
// >>> pluck([5, 0, 3, 0, 4, 2])
// [0, 1]
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
function pluck(arr){
let result = [],
index = -1; | if(arr[i] % 2 === 0){
if(result.length === 0 || result[0] > arr[i]){
result = [arr[i], i];
}
}
}
return result;
}
| for(let i = 0; i < arr.length; i++){ | 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_67_fruit_distribution.json-L16 | js | //In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// >>> fruit_distribution("5 apples and 6 oranges", 19)
// 8
// >>> fruit_distribution("0 apples and 1 oranges", 3)
// 2
// >>> fruit_distribution("2 apples and 3 oranges", 100)
// 95
// >>> fruit_distribution("100 apples and 1 oranges", 120)
// 19
function fruit_distribution(s, n){
| let num_of_apples = parseInt(split_s[0]);
let num_of_oranges = parseInt(split_s[3]);
let sum = num_of_apples + num_of_oranges;
return n - sum;
} | let split_s = s.split(" "); | const assert = require('node:assert');
function test() {
let candidate = fruit_distribution;
assert.deepEqual(candidate("5 apples and 6 oranges", 19),8);
assert.deepEqual(candidate("5 apples and 6 oranges", 21),10);
assert.deepEqual(candidate("0 apples and 1 oranges", 3),2);
assert.deepEqual(candidate("1 apples and 0 oranges", 3),2);
assert.deepEqual(candidate("2 apples and 3 oranges", 100),95);
assert.deepEqual(candidate("2 apples and 3 oranges", 5),0);
assert.deepEqual(candidate("1 apples and 100 oranges", 120),19);
}
test(); |
humaneval-HumanEval_119_match_parens.json-L27 | py | from typing import List
def match_parens(lst: List[str]) -> str:
"""
You are given a 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:
>>> match_parens(['()(', ')'])
'Yes'
>>> match_parens([')', ')'])
'No'
"""
s1, s2 = lst
strings = [s1 + s2, s2 + s1]
for s in strings:
open_parens = 0
close_parens = 0
for c in s:
if c == '(': | elif c == ')':
if open_parens:
open_parens -= 1
else:
close_parens += 1
if open_parens == 0 and close_parens == 0:
return 'Yes'
return 'No'
| open_parens += 1 | def check(candidate):
assert candidate(['()(', ')']) == 'Yes'
assert candidate([')', ')']) == 'No'
assert candidate(['(()(())', '())())']) == 'No'
assert candidate([')())', '(()()(']) == 'Yes'
assert candidate(['(())))', '(()())((']) == 'Yes'
assert candidate(['()', '())']) == 'No'
assert candidate(['(()(', '()))()']) == 'Yes'
assert candidate(['((((', '((())']) == 'No'
assert candidate([')(()', '(()(']) == 'No'
assert candidate([')(', ')(']) == 'No'
assert candidate(['(', ')']) == 'Yes'
assert candidate([')', '(']) == 'Yes'
def test_check():
check(match_parens)
test_check()
|
humaneval-HumanEval_108_count_nums.json-L16 | 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; | 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]);
}
}
if(sum > 0) {
count++;
}
}
return count;
} | for(var i = 0; i < arr.length; i++) { | const assert = require('node:assert');
function test() {
let candidate = count_nums;
assert.deepEqual(candidate([]),0);
assert.deepEqual(candidate([-1, -2, 0]),0);
assert.deepEqual(candidate([1, 1, 2, -2, 3, 4, 5]),6);
assert.deepEqual(candidate([1, 6, 9, -6, 0, 1, 5]),5);
assert.deepEqual(candidate([1, 100, 98, -7, 1, -1]),4);
assert.deepEqual(candidate([12, 23, 34, -45, -56, 0]),5);
assert.deepEqual(candidate([0, 1]),1);
assert.deepEqual(candidate([1]),1);
}
test(); |
humaneval-HumanEval_90_next_smallest.json-L18 | py | from typing import List, Optional
def next_smallest(lst: List[int]) -> Optional[int]:
"""
You are given a list of integers.
Write a function next_smallest() that returns the 2nd smallest element of the list.
Return None if there is no such element.
>>> next_smallest([1, 2, 3, 4, 5])
2
>>> next_smallest([5, 1, 4, 3, 2])
2
>>> next_smallest([])
None
>>> next_smallest([1, 1])
None
"""
if len(lst) < 2: | min1 = min(lst[0], lst[1])
min2 = max(lst[0], lst[1])
for i in range(2, len(lst)):
if lst[i] < min1:
min2 = min1
min1 = lst[i]
elif lst[i] < min2:
min2 = lst[i]
return min2 if min1 != min2 else None
| return None | def check(candidate):
assert candidate([1, 2, 3, 4, 5]) == 2
assert candidate([5, 1, 4, 3, 2]) == 2
assert candidate([]) == None
assert candidate([1, 1]) == None
assert candidate([1, 1, 1, 1, 0]) == 1
assert candidate([1, 1]) == None
assert candidate([-35, 34, 12, -45]) == -35
def test_check():
check(next_smallest)
test_check()
|
humaneval-HumanEval_109_move_one_ball.json-L31 | js | //We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// >>> move_one_ball([3, 4, 5, 1, 2])
// true
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// >>> move_one_ball([3, 5, 4, 1, 2])
// false
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
function move_one_ball(arr){
var diff_count = 0;
var i = 0;
var temp = 0;
for(var i = 0; i < arr.length - 1; i++){
if(arr[i] > arr[i + 1]){
diff_count += 1;
}
} | return false;
}
else{
return true;
}
} | if(diff_count > 1){ | const assert = require('node:assert');
function test() {
let candidate = move_one_ball;
assert.deepEqual(candidate([3, 4, 5, 1, 2]),true);
assert.deepEqual(candidate([3, 5, 10, 1, 2]),true);
assert.deepEqual(candidate([4, 3, 1, 2]),false);
assert.deepEqual(candidate([3, 5, 4, 1, 2]),false);
assert.deepEqual(candidate([]),true);
}
test(); |
humaneval-HumanEval_161_solve.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 {
// 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_135_can_arrange.json-L17 | py | from typing import List
def can_arrange(arr: List[int]) -> int:
"""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
"""
ans = -1
for i in range(len(arr)): | ans = i
return ans
| if i != 0 and arr[i] < arr[i - 1]: | def check(candidate):
assert candidate([1, 2, 4, 3, 5]) == 3
assert candidate([1, 2, 4, 5]) == -1
assert candidate([1, 4, 2, 5, 6, 7, 8, 9, 10]) == 2
assert candidate([4, 8, 5, 7, 3]) == 4
assert candidate([]) == -1
def test_check():
check(can_arrange)
test_check()
|
humaneval-HumanEval_31_is_prime.json-L30 | js | //Return true if a given number is prime, and false otherwise.
// >>> is_prime(6)
// false
// >>> is_prime(101)
// true
// >>> is_prime(11)
// true
// >>> is_prime(13441)
// true
// >>> is_prime(61)
// true
// >>> is_prime(4)
// false
// >>> is_prime(1)
// false
function is_prime(n){
if (n==1) {
return false;
}
if (n==2) {
return true;
}
if (n%2==0) {
return false;
}
var limit = Math.sqrt(n); | if (n%i==0) {
return false;
}
}
return true;
}
| for (var i = 3; i <= limit; i += 2) { | const assert = require('node:assert');
function test() {
let candidate = is_prime;
assert.deepEqual(candidate(6),false);
assert.deepEqual(candidate(101),true);
assert.deepEqual(candidate(11),true);
assert.deepEqual(candidate(13441),true);
assert.deepEqual(candidate(61),true);
assert.deepEqual(candidate(4),false);
assert.deepEqual(candidate(1),false);
assert.deepEqual(candidate(5),true);
assert.deepEqual(candidate(11),true);
assert.deepEqual(candidate(17),true);
assert.deepEqual(candidate(85),false);
assert.deepEqual(candidate(77),false);
assert.deepEqual(candidate(255379),false);
}
test(); |
humaneval-HumanEval_113_odd_count.json-L16 | js | //Given an array of strings, where each string consists of only digits, return an array.
// 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.
// >>> odd_count(["1234567"])
// ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// >>> odd_count(["3", "11111111"])
// ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
function odd_count(lst){
var new_lst = [];
for (var i = 0; i < lst.length; i++){
var word = lst[i];
var odd_sum = 0;
for (var j = 0; j < word.length; j++){
if (word[j] % 2 == 1){ | }
}
var odd_word = "the number of odd elements " + odd_sum + "n the str" + odd_sum + "ng " + odd_sum + " of the " + odd_sum + "nput.";
new_lst.push(odd_word);
}
return new_lst;
} | odd_sum += 1; | const assert = require('node:assert');
function test() {
let candidate = odd_count;
assert.deepEqual(candidate(["1234567"]),["the number of odd elements 4n the str4ng 4 of the 4nput."]);
assert.deepEqual(candidate(["3", "11111111"]),["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]);
assert.deepEqual(candidate(["271", "137", "314"]),["the number of odd elements 2n the str2ng 2 of the 2nput.", "the number of odd elements 3n the str3ng 3 of the 3nput.", "the number of odd elements 2n the str2ng 2 of the 2nput."]);
}
test(); |
humaneval-HumanEval_153_Strongest_Extension.json-L24 | py | from typing import List
def Strongest_Extension(class_name: str, extensions: List[str]) -> str:
"""You will be given the name of a class (a string) and a list of extensions.
The extensions are to be used to load additional classes to the class. The
strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the extension's name, and let SM be the number of lowercase letters
in the extension's name, the strength is given by the fraction CAP - SM.
You should find the strongest extension and return a string in this
format: ClassName.StrongestExtensionName.
If there are two or more extensions with the same strength, you should
choose the one that comes first in the list.
For example, if you are given "Slices" as the class and a list of the
extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
(its strength is -1).
Example:
>>> Strongest_Extension('my_class', ['AA', 'Be', 'CC'])
'my_class.AA'
"""
best_strength, best_extension = -1, ''
for extension in extensions:
n_uppercase = sum(1 for c in extension if c.isupper()) | if n_uppercase - n_lowercase > best_strength:
best_strength = n_uppercase - n_lowercase
best_extension = extension
return class_name + '.' + best_extension | n_lowercase = sum(1 for c in extension if c.islower()) | def check(candidate):
assert candidate('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) == 'Watashi.eIGHt8OKe'
assert candidate('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg']) == 'Boku123.YEs.WeCaNe'
assert candidate('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321']) == '__YESIMHERE.NuLl__'
assert candidate('K', ['Ta', 'TAR', 't234An', 'cosSo']) == 'K.TAR'
assert candidate('__HAHA', ['Tab', '123', '781345', '-_-']) == '__HAHA.123'
assert candidate('YameRore', ['HhAas', 'okIWILL123', 'WorkOut', 'Fails', '-_-']) == 'YameRore.okIWILL123'
assert candidate('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) == 'finNNalLLly.WoW'
assert candidate('_', ['Bb', '91245']) == '_.Bb'
assert candidate('Sp', ['671235', 'Bb']) == 'Sp.671235'
def test_check():
check(Strongest_Extension)
test_check()
|
humaneval-HumanEval_149_sorted_list_sum.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 {
// Write a function that accepts an array array list of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array list with a sorted order,
// The array list is always an array array list of strings and never an array array list of numbers,
// and it may contain duplicates.
// The order of the array list should be ascending by length of each word, and you
// should return the array list sorted by that rule.
// If two words have the same length, sort the array list alphabetically.
// The function should return an array array list of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// >>> listSort((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa"))))
// (new ArrayList<String>(Arrays.asList((String)"aa")))
// >>> listSort((new ArrayList<String>(Arrays.asList((String)"ab", (String)"a", (String)"aaa", (String)"cd"))))
// (new ArrayList<String>(Arrays.asList((String)"ab", (String)"cd")))
public static ArrayList<String> sortedListSum(ArrayList<String> lst) {
ArrayList<String> result = new ArrayList<String>();
for (String s : lst) {
if (s.length() % 2 == 0) {
result.add(s);
}
} | @Override
public int compare(String s1, String s2) {
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
}
return s1.length() - s2.length();
}
});
return result;
}
} | Collections.sort(result, new Comparator<String>() { | }
public static void main(String[] args) {
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa")))).equals((new ArrayList<String>(Arrays.asList((String)"aa")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"school", (String)"AI", (String)"asdf", (String)"b")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"asdf", (String)"school")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"b", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList()))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"dcba", (String)"abcd", (String)"a")))).equals((new ArrayList<String>(Arrays.asList((String)"abcd", (String)"dcba")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au")))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"a", (String)"b", (String)"b", (String)"c", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList()))));
assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aaaa", (String)"bbbb", (String)"dd", (String)"cc")))).equals((new ArrayList<String>(Arrays.asList((String)"cc", (String)"dd", (String)"aaaa", (String)"bbbb")))));
}
}
|
humaneval-HumanEval_49_modp.json-L15 | js | //Return 2^n modulo p (be aware of numerics).
// >>> modp(3, 5)
// 3
// >>> modp(1101, 101)
// 2
// >>> modp(0, 101)
// 1
// >>> modp(3, 11)
// 8
// >>> modp(100, 101)
// 1
function modp(n, p){
var result = 1;
while(n>0){ | n--;
}
return result;
}
| result = (result*2)%p; | const assert = require('node:assert');
function test() {
let candidate = modp;
assert.deepEqual(candidate(3, 5),3);
assert.deepEqual(candidate(1101, 101),2);
assert.deepEqual(candidate(0, 101),1);
assert.deepEqual(candidate(3, 11),8);
assert.deepEqual(candidate(100, 101),1);
assert.deepEqual(candidate(30, 5),4);
assert.deepEqual(candidate(31, 5),3);
}
test(); |
humaneval-HumanEval_75_is_multiply_prime.json-L18 | py | def is_multiply_prime(a: int) -> bool:
"""Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
>>> is_multiply_prime(30)
True
30 = 2 * 3 * 5
"""
n = a
d = 2
prime_factors = []
while d * d <= n:
if n % d == 0:
prime_factors.append(d)
n //= d
else: | if n > 1:
prime_factors.append(n)
if len(prime_factors) == 3:
return True
else:
return False
| d += 1 | def check(candidate):
assert candidate(5) == False
assert candidate(30) == True
assert candidate(8) == True
assert candidate(10) == False
assert candidate(125) == True
assert candidate(105) == True
assert candidate(126) == False
assert candidate(729) == False
assert candidate(891) == False
assert candidate(1001) == True
def test_check():
check(is_multiply_prime)
test_check()
|
humaneval-HumanEval_9_rolling_max.json-L12 | py | from typing import List
def rolling_max(numbers: List[int]) -> List[int]:
""" From a given list of integers, generate a list of rolling maximum element found until given moment
in the sequence.
>>> rolling_max([1, 2, 3, 2, 3, 4, 2])
[1, 2, 3, 3, 3, 4, 4]
"""
if len(numbers) == 0:
return []
else: | return [max(numbers[:i + 1]) for i in range(len(numbers))] | def check(candidate):
assert candidate([]) == []
assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4]
assert candidate([4, 3, 2, 1]) == [4, 4, 4, 4]
assert candidate([3, 2, 3, 100, 3]) == [3, 3, 3, 100, 100]
def test_check():
check(rolling_max)
test_check()
|
|
humaneval-HumanEval_136_largest_smallest_integers.json-L25 | py | from typing import List, Tuple, Optional
def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]:
"""
Create a function that returns a tuple (a, b), where 'a' is
the largest of negative integers, and 'b' is the smallest
of positive integers in a list.
If there is no negative or positive integers, return them as None.
Examples:
>>> largest_smallest_integers([2, 4, 1, 3, 5, 7])
(None, 1)
>>> largest_smallest_integers([])
(None, None)
>>> largest_smallest_integers([0])
(None, None)
"""
smallest_positive = None
largest_negative = None
for num in lst:
if num > 0:
if smallest_positive is None or num < smallest_positive:
smallest_positive = num
elif num < 0: | largest_negative = num
return (largest_negative, smallest_positive)
| if largest_negative is None or num > largest_negative: | def check(candidate):
assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1)
assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1)
assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1)
assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2)
assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2)
assert candidate([]) == (None, None)
assert candidate([0]) == (None, None)
assert candidate([-1, -3, -5, -6]) == (-1, None)
assert candidate([-1, -3, -5, -6, 0]) == (-1, None)
assert candidate([-6, -4, -4, -3, 1]) == (-3, 1)
assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1)
def test_check():
check(largest_smallest_integers)
test_check()
|
humaneval-HumanEval_12_longest.json-L16 | js | //Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return undefined in case the input array is empty.
// >>> longest([])
// undefined
// >>> longest(["a", "b", "c"])
// "a"
// >>> longest(["a", "bb", "ccc"])
// "ccc"
function longest(strings){
var result;
if (strings.length === 0) {
return undefined;
}
for (var i = 0; i < strings.length; i++) {
if (!result || strings[i].length > result.length) { | }
}
return result;
}
| result = strings[i]; | const assert = require('node:assert');
function test() {
let candidate = longest;
assert.deepEqual(candidate([]),undefined);
assert.deepEqual(candidate(["x", "y", "z"]),"x");
assert.deepEqual(candidate(["x", "yyy", "zzzz", "www", "kkkk", "abc"]),"zzzz");
}
test(); |
humaneval-HumanEval_105_by_length.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 {
// 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_43_pairs_sum_to_zero.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 {
// 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_98_count_upper.json-L20 | py | def count_upper(s: str) -> int:
"""
Given a string s, count the number of uppercase vowels in even indices.
For example:
>>> count_upper('aBCdEf')
1
>>> count_upper('abcdefg')
0
>>> count_upper('dBBE')
0
"""
vowel_set = set('AEIOU')
count = 0
for i in range(0, len(s), 2):
if s[i] in vowel_set:
count += 1
return count
| D.1 Recursion
Given a positive integer n, write a recursive function that returns the sum of the squares of the
positive odd integers smaller than n. Assume n is greater than or equal to 3.
""" | """ | def check(candidate):
assert candidate('aBCdEf') == 1
assert candidate('abcdefg') == 0
assert candidate('dBBE') == 0
assert candidate('B') == 0
assert candidate('U') == 1
assert candidate('') == 0
assert candidate('EEEE') == 2
def test_check():
check(count_upper)
test_check()
|
humaneval-HumanEval_96_count_up_to.json-L30 | js | //Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// >>> count_up_to(5)
// [2, 3]
// >>> count_up_to(11)
// [2, 3, 5, 7]
// >>> count_up_to(0)
// []
// >>> count_up_to(20)
// [2, 3, 5, 7, 11, 13, 17, 19]
// >>> count_up_to(1)
// []
// >>> count_up_to(18)
// [2, 3, 5, 7, 11, 13, 17]
function count_up_to(n){
if (n < 2) return [];
var output = [2];
for (var i = 3; i < n; i += 2){
var prime = true;
for (var j = 3; j < i; j += 2){
if (i % j === 0){
prime = false;
break;
}
}
if (prime) output.push(i);
}
return output; | } | const assert = require('node:assert');
function test() {
let candidate = count_up_to;
assert.deepEqual(candidate(5),[2, 3]);
assert.deepEqual(candidate(6),[2, 3, 5]);
assert.deepEqual(candidate(7),[2, 3, 5]);
assert.deepEqual(candidate(10),[2, 3, 5, 7]);
assert.deepEqual(candidate(0),[]);
assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]);
assert.deepEqual(candidate(1),[]);
assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]);
assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]);
assert.deepEqual(candidate(101),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]);
}
test(); |
|
humaneval-HumanEval_19_sort_numbers.json-L24 | js | //Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// >>> sort_numbers("three one five")
// "one three five"
function sort_numbers(numbers){
var numString = numbers.split(" ");
var numMap = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9
};
numString.sort(function(a, b){
return numMap[a] - numMap[b];
});
numString = numString.join(" "); | } | return numString; | const assert = require('node:assert');
function test() {
let candidate = sort_numbers;
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("three"),"three");
assert.deepEqual(candidate("three five nine"),"three five nine");
assert.deepEqual(candidate("five zero four seven nine eight"),"zero four five seven eight nine");
assert.deepEqual(candidate("six five four three two one zero"),"zero one two three four five six");
}
test(); |
humaneval-HumanEval_71_triangle_area.json-L16 | py | def triangle_area(a: int, b: int, c: int) -> float:
"""
Given the lengths of the three sides of a triangle. Return the area of
the triangle rounded to 2 decimal points if the three sides form a valid triangle.
Otherwise return -1
Three sides make a valid triangle when the sum of any two sides is greater
than the third side.
Example:
>>> triangle_area(3, 4, 5)
6.0
>>> triangle_area(1, 2, 10)
-1
"""
if a + b > c and a + c > b and b + c > a:
perimeter = (a + b + c) / 2 | return round(area, 2)
else:
return -1
| area = (perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c)) ** 0.5 | def check(candidate):
assert candidate(3, 4, 5) == 6.0
assert candidate(1, 2, 10) == -1
assert candidate(4, 8, 5) == 8.18
assert candidate(2, 2, 2) == 1.73
assert candidate(1, 2, 3) == -1
assert candidate(10, 5, 7) == 16.25
assert candidate(2, 6, 3) == -1
assert candidate(1, 1, 1) == 0.43
assert candidate(2, 2, 10) == -1
def test_check():
check(triangle_area)
test_check()
|
humaneval-HumanEval_140_fix_spaces.json-L28 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// >>> fixSpaces((" Example"))
// ("Example")
// >>> fixSpaces((" Example 1"))
// ("Example_1")
// >>> fixSpaces((" Example 2"))
// ("_Example_2")
// >>> fixSpaces((" Example 3"))
// ("_Example-3")
public static String fixSpaces(String text) {
String result = text.replace(" ", "_");
int i = 0;
while (i < result.length() - 2) {
if (result.charAt(i) == '_' && result.charAt(i + 1) == '_' && result.charAt(i + 2) == '_') {
result = result.substring(0, i) + "-" + result.substring(i + 3);
}
i++; | return result;
}
} | } | }
public static void main(String[] args) {
assert(fixSpaces(("Example")).equals(("Example")));
assert(fixSpaces(("Mudasir Hanif ")).equals(("Mudasir_Hanif_")));
assert(fixSpaces(("Yellow Yellow Dirty Fellow")).equals(("Yellow_Yellow__Dirty__Fellow")));
assert(fixSpaces(("Exa mple")).equals(("Exa-mple")));
assert(fixSpaces((" Exa 1 2 2 mple")).equals(("-Exa_1_2_2_mple")));
}
}
|
humaneval-HumanEval_90_next_smallest.json-L18 | js | //You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return undefined if there is no such element.
// >>> next_smallest([1, 2, 3, 4, 5])
// 2
// >>> next_smallest([5, 1, 4, 3, 2])
// 2
// >>> next_smallest([])
// undefined
// >>> next_smallest([1, 1])
// undefined
function next_smallest(lst){
if(lst.length<=1){
return undefined;
}
var smallest=Math.min(...lst);
var second_smallest=Number.MAX_VALUE; | if(lst[i]>smallest&&lst[i]<second_smallest){
second_smallest=lst[i];
}
}
if(second_smallest==Number.MAX_VALUE){
return undefined;
}
return second_smallest;
} | for(var i in lst){ | const assert = require('node:assert');
function test() {
let candidate = next_smallest;
assert.deepEqual(candidate([1, 2, 3, 4, 5]),2);
assert.deepEqual(candidate([5, 1, 4, 3, 2]),2);
assert.deepEqual(candidate([]),undefined);
assert.deepEqual(candidate([1, 1]),undefined);
assert.deepEqual(candidate([1, 1, 1, 1, 0]),1);
assert.deepEqual(candidate([1, 1]),undefined);
assert.deepEqual(candidate([-35, 34, 12, -45]),-35);
}
test(); |
humaneval-HumanEval_69_search.json-L18 | js | //You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// >>> search([4, 1, 2, 2, 3, 1])
// 2
// >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4])
// 3
// >>> search([5, 5, 4, 4, 4])
// -1
function search(lst){
var h = {};
for (var i=0; i<lst.length; i++){
var x = lst[i];
if (x in h){
h[x] += 1; | else{
h[x] = 1;
}
}
var keys = Object.keys(h);
var max = 0;
for (var i=0; i<keys.length; i++){
if (keys[i] > max && h[keys[i]] >= keys[i]){
max = keys[i];
}
}
if (max == 0){
return -1;
}
return max;
}
| } | const assert = require('node:assert');
function test() {
let candidate = search;
assert.deepEqual(candidate([5, 5, 5, 5, 1]),1);
assert.deepEqual(candidate([4, 1, 4, 1, 4, 4]),4);
assert.deepEqual(candidate([3, 3]),-1);
assert.deepEqual(candidate([8, 8, 8, 8, 8, 8, 8, 8]),8);
assert.deepEqual(candidate([2, 3, 3, 2, 2]),2);
assert.deepEqual(candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]),1);
assert.deepEqual(candidate([3, 2, 8, 2]),2);
assert.deepEqual(candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]),1);
assert.deepEqual(candidate([8, 8, 3, 6, 5, 6, 4]),-1);
assert.deepEqual(candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]),1);
assert.deepEqual(candidate([1, 9, 10, 1, 3]),1);
assert.deepEqual(candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]),5);
assert.deepEqual(candidate([1]),1);
assert.deepEqual(candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]),4);
assert.deepEqual(candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]),2);
assert.deepEqual(candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]),1);
assert.deepEqual(candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]),4);
assert.deepEqual(candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]),4);
assert.deepEqual(candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]),2);
assert.deepEqual(candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]),-1);
assert.deepEqual(candidate([10]),-1);
assert.deepEqual(candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]),2);
assert.deepEqual(candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]),1);
assert.deepEqual(candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]),1);
assert.deepEqual(candidate([3, 10, 10, 9, 2]),-1);
}
test(); |
humaneval-HumanEval_155_even_odd_count.json-L12 | 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)
"""
| even_count = 0
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
| num_str = str(abs(num)) | 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_106_f.json-L22 | py | from typing import List
def f(n: int) -> List[int]:
""" Implement the function f that takes n as a parameter,
and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even
or the sum of numbers from 1 to i otherwise.
i starts from 1.
the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
Example:
>>> f(5)
[1, 2, 6, 24, 15]
"""
import math
a=[]
for i in range(n):
i=i+1
if i%2==0:
a.append(math.factorial(i))
else:
a.append(sum(range(1,i+1)))
return a | pass | def check(candidate):
assert candidate(5) == [1, 2, 6, 24, 15]
assert candidate(7) == [1, 2, 6, 24, 15, 720, 28]
assert candidate(1) == [1]
assert candidate(3) == [1, 2, 6]
def test_check():
check(f)
test_check()
|
|
humaneval-HumanEval_148_bf.json-L35 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return a pair containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty pair if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf(("Jupiter"), ("Neptune"))
// (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))
// >>> bf(("Earth"), ("Mercury"))
// (ArrayList<String>("Venus"))
// >>> bf(("Mercury"), ("Uranus"))
// (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))
public static ArrayList<String> bf(String planet1, String planet2) {
ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune"));
int indexPlanet1 = planets.indexOf(planet1);
int indexPlanet2 = planets.indexOf(planet2);
int indexMin = 0;
int indexMax = 0;
if (indexPlanet1 >= 0 && indexPlanet2 >= 0) {
if (indexPlanet1 < indexPlanet2) {
indexMin = indexPlanet1;
indexMax = indexPlanet2; | indexMin = indexPlanet2;
indexMax = indexPlanet1;
}
ArrayList<String> planetsInBetween = new ArrayList<String>();
for (int i = indexMin + 1; i < indexMax; i++) {
planetsInBetween.add(planets.get(i));
}
return planetsInBetween;
} else {
return new ArrayList<String>();
}
}
} | } else { | }
public static void main(String[] args) {
assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus")))));
assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))));
assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_117_select_words.json-L22 | js | //Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// >>> select_words("Mary had a little lamb", 4)
// ["little"]
// >>> select_words("Mary had a little lamb", 3)
// ["Mary", "lamb"]
// >>> select_words("simple white space", 2)
// []
// >>> select_words("Hello world", 4)
// ["world"]
// >>> select_words("Uncle sam", 3)
// ["Uncle"]
function select_words(s, n){
let words = s.split(' ').filter(e => e != '');
let selected = words.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi) != null);
if(n > 0){
return selected.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi).length == n); | return [];
}
}
| }else{ | const assert = require('node:assert');
function test() {
let candidate = select_words;
assert.deepEqual(candidate("Mary had a little lamb", 4),["little"]);
assert.deepEqual(candidate("Mary had a little lamb", 3),["Mary", "lamb"]);
assert.deepEqual(candidate("simple white space", 2),[]);
assert.deepEqual(candidate("Hello world", 4),["world"]);
assert.deepEqual(candidate("Uncle sam", 3),["Uncle"]);
assert.deepEqual(candidate("", 4),[]);
assert.deepEqual(candidate("a b c d e f", 1),["b", "c", "d", "f"]);
}
test(); |
humaneval-HumanEval_137_compare_one.json-L32 | js | //Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return undefined if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// >>> compare_one(1, 2.5)
// 2.5
// >>> compare_one(1, "2,3")
// "2,3"
// >>> compare_one("5,1", "6")
// "6"
// >>> compare_one("1", 1)
// undefined
function compare_one(a, b){
if (typeof a === typeof b){
if (a > b) {
return a;
} else if (a < b) {
return b;
} else {
return undefined;
}
}
else if (typeof a === "string" && typeof b === "number"){
if (a[0] > b){
return a;
} else if (a[0] < b){
return b;
} else {
return undefined;
}
} | if (a > b[0]){
return a;
} else if (a < b[0]){
return b;
} else {
return undefined;
}
}
}
| else if (typeof a === "number" && typeof b === "string"){ | const assert = require('node:assert');
function test() {
let candidate = compare_one;
assert.deepEqual(candidate(1, 2),2);
assert.deepEqual(candidate(1, 2.5),2.5);
assert.deepEqual(candidate(2, 3),3);
assert.deepEqual(candidate(5, 6),6);
assert.deepEqual(candidate(1, "2,3"),"2,3");
assert.deepEqual(candidate("5,1", "6"),"6");
assert.deepEqual(candidate("1", "2"),"2");
assert.deepEqual(candidate("1", 1),undefined);
}
test(); |
humaneval-HumanEval_72_will_it_fly.json-L25 | js | //Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// >>> will_it_fly([1, 2], 5)
// false
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// >>> will_it_fly([3, 2, 3], 1)
// false
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// >>> will_it_fly([3, 2, 3], 9)
// true
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// >>> will_it_fly([3], 5)
// true
// # 3 is less than the maximum possible weight, and it's balanced.
function will_it_fly(q, w){
let sum = 0;
let balanced = true;
for(let i = 0; i < q.length; i++){
sum += q[i];
}
for(let i = 0; i < q.length; i++){
if(q[i] !== q[q.length - 1 - i]){
balanced = false; | }
}
return balanced && sum <= w;
} | break; | const assert = require('node:assert');
function test() {
let candidate = will_it_fly;
assert.deepEqual(candidate([3, 2, 3], 9),true);
assert.deepEqual(candidate([1, 2], 5),false);
assert.deepEqual(candidate([3], 5),true);
assert.deepEqual(candidate([3, 2, 3], 1),false);
assert.deepEqual(candidate([1, 2, 3], 6),false);
assert.deepEqual(candidate([5], 5),true);
}
test(); |
humaneval-HumanEval_117_select_words.json-L25 | py | from typing import List
def select_words(s: str, n: int) -> List[str]:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_words('Mary had a little lamb', 4)
['little']
>>> select_words('Mary had a little lamb', 3)
['Mary', 'lamb']
>>> select_words('simple white space', 2)
[]
>>> select_words('Hello world', 4)
['world']
>>> select_words('Uncle sam', 3)
['Uncle']
"""
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
words = s.split()
result = []
for word in words: | for char in word:
if char.lower() in CONSONANTS:
count += 1
if count == n:
result.append(word)
return result
| count = 0 | def check(candidate):
assert candidate('Mary had a little lamb', 4) == ['little']
assert candidate('Mary had a little lamb', 3) == ['Mary', 'lamb']
assert candidate('simple white space', 2) == []
assert candidate('Hello world', 4) == ['world']
assert candidate('Uncle sam', 3) == ['Uncle']
assert candidate('', 4) == []
assert candidate('a b c d e f', 1) == ['b', 'c', 'd', 'f']
def test_check():
check(select_words)
test_check()
|
humaneval-HumanEval_20_find_closest_elements.json-L8 | js | //From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
// [2.0, 2.2]
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// [2.0, 2.0]
function find_closest_elements(numbers){
| let a = numbers[0];
let b = numbers[1];
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (Math.abs(numbers[i] - numbers[j]) < closest) {
closest = Math.abs(numbers[i] - numbers[j]);
a = numbers[i];
b = numbers[j];
}
}
}
return a > b ? [b, a] : [a, b];
}
| let closest = Math.abs(numbers[0] - numbers[1]); | const assert = require('node:assert');
function test() {
let candidate = find_closest_elements;
assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]);
assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]);
assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]);
}
test(); |
humaneval-HumanEval_57_monotonic.json-L27 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Return true is array list elements are monotonically increasing or decreasing.
// >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l))))
// (true)
// >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))))
// (false)
// >>> monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l))))
// (true)
public static boolean monotonic(ArrayList<Long> l) {
long a = l.get(0);
boolean inc = true;
boolean dec = true;
for (int i = 1; i < l.size(); i++) {
if (l.get(i) < a) {
inc = false;
}
if (l.get(i) > a) {
dec = false;
} | }
return inc || dec;
}
} | a = l.get(i); | }
public static void main(String[] args) {
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l)))) == (true));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l)))) == (true));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l)))) == (false));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l)))) == (true));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l)))) == (true));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)5l, (long)60l)))) == (false));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)60l)))) == (true));
assert(monotonic((new ArrayList<Long>(Arrays.asList((long)9l, (long)9l, (long)9l, (long)9l)))) == (true));
}
}
|
humaneval-HumanEval_42_incr_list.json-L11 | js | //Return array with elements incremented by 1.
// >>> incr_list([1, 2, 3])
// [2, 3, 4]
// >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])
// [6, 4, 6, 3, 4, 4, 10, 1, 124]
function incr_list(l){
var new_list = [];
for(var i = 0; i < l.length; i++){
new_list.push(l[i] + 1);
} | }
| return new_list; | const assert = require('node:assert');
function test() {
let candidate = incr_list;
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([3, 2, 1]),[4, 3, 2]);
assert.deepEqual(candidate([5, 2, 5, 2, 3, 3, 9, 0, 123]),[6, 3, 6, 3, 4, 4, 10, 1, 124]);
}
test(); |
humaneval-HumanEval_148_bf.json-L36 | js | //There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return an array containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty array if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf("Jupiter", "Neptune")
// ["Saturn", "Uranus"]
// >>> bf("Earth", "Mercury")
// "Venus"
// >>> bf("Mercury", "Uranus")
// ["Venus", "Earth", "Mars", "Jupiter", "Saturn"]
function bf(planet1, planet2){
var planets = {
'Mercury':1,
'Venus':2,
'Earth':3,
'Mars':4,
'Jupiter':5,
'Saturn':6,
'Uranus':7,
'Neptune':8
}
if(!planets[planet1] || !planets[planet2]){
return [];
}
var keys = Object.keys(planets);
var position1 = keys.indexOf(planet1);
var position2 = keys.indexOf(planet2);
if(position1 > position2){
var temp = position1; | position2 = temp;
}
var res = [];
for(var i = position1 + 1; i < position2; i++){
res.push(keys[i]);
}
return res;
} | position1 = position2; | const assert = require('node:assert');
function test() {
let candidate = bf;
assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]);
assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]);
assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]);
assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]);
assert.deepEqual(candidate("Earth", "Earth"),[]);
assert.deepEqual(candidate("Mars", "Earth"),[]);
assert.deepEqual(candidate("Jupiter", "Makemake"),[]);
}
test(); |
humaneval-HumanEval_137_compare_one.json-L23 | py | from typing import Union
def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]:
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> compare_one(1, 2.5)
2.5
>>> compare_one(1, '2,3')
'2,3'
>>> compare_one('5,1', '6')
'6'
>>> compare_one('1', 1)
None
"""
if isinstance(a, int) and isinstance(b, int):
if a > b:
return a
elif a < b: | else:
return None
elif isinstance(a, float) and isinstance(b, float):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, str) and isinstance(b, str):
a_tmp = a.replace(',', '.')
b_tmp = b.replace(',', '.')
if float(a_tmp) > float(b_tmp):
return a
elif float(a_tmp) < float(b_tmp):
return b
else:
return None
elif isinstance(a, int) and isinstance(b, float):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, float) and isinstance(b, int):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, str) and isinstance(b, int):
a_tmp = a.replace(',', '.')
if float(a_tmp) > b:
return a
elif float(a_tmp) < b:
return b
else:
return None
elif isinstance(a, int) and isinstance(b, str):
b_tmp = b.replace(',', '.')
if a > float(b_tmp):
return a
elif a < float(b_tmp):
return b
else:
return None
elif isinstance(a, str) and isinstance(b, float):
a_tmp = a.replace(',', '.')
if float(a_tmp) > b:
return a
elif float(a_tmp) < b:
return b | return b | def check(candidate):
assert candidate(1, 2) == 2
assert candidate(1, 2.5) == 2.5
assert candidate(2, 3) == 3
assert candidate(5, 6) == 6
assert candidate(1, '2,3') == '2,3'
assert candidate('5,1', '6') == '6'
assert candidate('1', '2') == '2'
assert candidate('1', 1) == None
def test_check():
check(compare_one)
test_check()
|
humaneval-HumanEval_127_intersection.json-L26 | py | from typing import Tuple
def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str:
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
>>> intersection((1, 2), (2, 3))
'NO'
>>> intersection((-1, 1), (0, 4))
'NO'
>>> intersection((-3, -1), (-5, 5))
'YES'
"""
| end = min(interval1[1], interval2[1])
if start > end:
return "NO"
return "YES" if end - start == 2 else "NO"
| start = max(interval1[0], interval2[0]) | def check(candidate):
assert candidate((1, 2), (2, 3)) == 'NO'
assert candidate((-1, 1), (0, 4)) == 'NO'
assert candidate((-3, -1), (-5, 5)) == 'YES'
assert candidate((-2, 2), (-4, 0)) == 'YES'
assert candidate((-11, 2), (-1, -1)) == 'NO'
assert candidate((1, 2), (3, 5)) == 'NO'
assert candidate((1, 2), (1, 2)) == 'NO'
assert candidate((-2, -2), (-3, -2)) == 'NO'
def test_check():
check(intersection)
test_check()
|
humaneval-HumanEval_144_simplify.json-L18 | js | //Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// >>> simplify("1/5", "5/1")
// true
// >>> simplify("1/6", "2/1")
// false
// >>> simplify("7/10", "10/2")
// false
function simplify(x, n){
let xNumerator = parseInt(x.split('/')[0]);
let xDenominator = parseInt(x.split('/')[1]);
let nNumerator = parseInt(n.split('/')[0]);
let nDenominator = parseInt(n.split('/')[1]);
let xTimesN = xNumerator * nNumerator / (xDenominator * nDenominator); | }
| return Number.isInteger(xTimesN); | const assert = require('node:assert');
function test() {
let candidate = simplify;
assert.deepEqual(candidate("1/5", "5/1"),true);
assert.deepEqual(candidate("1/6", "2/1"),false);
assert.deepEqual(candidate("5/1", "3/1"),true);
assert.deepEqual(candidate("7/10", "10/2"),false);
assert.deepEqual(candidate("2/10", "50/10"),true);
assert.deepEqual(candidate("7/2", "4/2"),true);
assert.deepEqual(candidate("11/6", "6/1"),true);
assert.deepEqual(candidate("2/3", "5/2"),false);
assert.deepEqual(candidate("5/2", "3/5"),false);
assert.deepEqual(candidate("2/4", "8/4"),true);
assert.deepEqual(candidate("2/4", "4/2"),true);
assert.deepEqual(candidate("1/5", "5/1"),true);
assert.deepEqual(candidate("1/5", "1/5"),false);
}
test(); |
humaneval-HumanEval_139_special_factorial.json-L14 | py | def special_factorial(n: int) -> int:
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
"""
def factorial(n): | return 1
else:
return n * factorial(n-1)
if n <= 1:
return 1
else:
return n * special_factorial(n-1) * factorial(n-1)
| if n <= 1: | def check(candidate):
assert candidate(4) == 288
assert candidate(5) == 34560
assert candidate(7) == 125411328000
assert candidate(1) == 1
def test_check():
check(special_factorial)
test_check()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.