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_4_mean_absolute_deviation.json-L12
py
from typing import List def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """
absolute_deviations = [abs(x - mean) for x in numbers] return sum(absolute_deviations) / len(absolute_deviations) print(mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]))
mean = sum(numbers) / len(numbers)
def check(candidate): assert candidate([1.0, 2.0]) == 0.5 assert candidate([1.0, 2.0, 3.0, 4.0]) == 1.0 assert candidate([1.0, 2.0, 3.0, 4.0, 5.0]) == 1.2 def test_check(): check(mean_absolute_deviation) test_check()
humaneval-HumanEval_39_prime_fib.json-L26
js
//prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> prime_fib(1) // 2 // >>> prime_fib(2) // 3 // >>> prime_fib(3) // 5 // >>> prime_fib(4) // 13 // >>> prime_fib(5) // 89 function prime_fib(n){ function isPrime(number){ if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false; } }
} } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b; b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
return true;
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_116_sort_array.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // In this Kata, you have to sort an array array list of non-negative integers according to // number of ones in their binary representation in ascending order. // For similar number of ones, sort based on decimal value. // It must be implemented like this: // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))) // (new ArrayList<Long>(Arrays.asList((long)-6l, (long)-5l, (long)-4l, (long)-3l, (long)-2l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l))) public static ArrayList<Long> sortArray(ArrayList<Long> arr) { Collections.sort(arr, (a, b) -> { long a1 = a, b1 = b;
a1 = -a1; } if (b1 < 0) { b1 = -b1; } return Long.bitCount(a1) == Long.bitCount(b1) ? Long.compare(a, b) : Integer.compare(Long.bitCount(a1), Long.bitCount(b1)); }); return arr; } }
if (a1 < 0) {
} public static void main(String[] args) { assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-2l, (long)-6l, (long)-5l, (long)-3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)4l, (long)3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)77l, (long)4l, (long)5l, (long)3l, (long)5l, (long)7l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)4l, (long)4l, (long)3l, (long)3l, (long)5l, (long)5l, (long)5l, (long)7l, (long)77l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)44l, (long)12l, (long)32l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)32l, (long)3l, (long)5l, (long)6l, (long)12l, (long)44l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); } }
humaneval-HumanEval_12_longest.json-L18
py
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) None >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """ if not strings: return None else: long = strings[0] for s in strings:
long = s return long
if len(s) > len(long):
def check(candidate): assert candidate([]) == None assert candidate(['x', 'y', 'z']) == 'x' assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz' def test_check(): check(longest) test_check()
humaneval-HumanEval_75_is_multiply_prime.json-L25
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_17_parse_music.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string representing musical notes in a special ASCII format. // Your task is to parse this string and return array list of integers corresponding to how many beats does each // not last. // Here is a legend: // 'o' - whole note, lasts four beats // 'o|' - half note, lasts two beats // '.|' - quater note, lasts one beat // >>> parseMusic(("o o| .| o| o| .| .| .| .| o o")) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l))) public static ArrayList<Long> parseMusic(String music_string) { ArrayList<Long> res = new ArrayList<Long>(); char[] chars = music_string.toCharArray(); for (int i = 0; i < chars.length; i++) {
if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)2l); i += 1; } else { res.add((long)4l); } } else if (chars[i] == '.') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)1l); i += 1; } } } return res; } }
if (chars[i] == 'o') {
} public static void main(String[] args) { assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList())))); assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))); assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l))))); } }
humaneval-HumanEval_158_find_max.json-L23
py
from typing import List def find_max(words: List[str]) -> str: """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. >>> find_max(['name', 'of', 'string']) 'string' >>> find_max(['name', 'enam', 'game']) 'enam' >>> find_max(['aaaaaaa', 'bb', 'cc']) 'aaaaaaa' """ max_num = 0 max_word = "" for word in words: unique_num = len(set(word)) if unique_num > max_num: max_num = unique_num max_word = word
if word < max_word: max_word = word return max_word
elif unique_num == max_num:
def check(candidate): assert candidate(['name', 'of', 'string']) == 'string' assert candidate(['name', 'enam', 'game']) == 'enam' assert candidate(['aaaaaaa', 'bb', 'cc']) == 'aaaaaaa' assert candidate(['abc', 'cba']) == 'abc' assert candidate(['play', 'this', 'game', 'of', 'footbott']) == 'footbott' assert candidate(['we', 'are', 'gonna', 'rock']) == 'gonna' assert candidate(['we', 'are', 'a', 'mad', 'nation']) == 'nation' assert candidate(['this', 'is', 'a', 'prrk']) == 'this' assert candidate(['b']) == 'b' assert candidate(['play', 'play', 'play']) == 'play' def test_check(): check(find_max) test_check()
humaneval-HumanEval_119_match_parens.json-L33
js
//You are given an array of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> match_parens(["()(", ")"]) // "Yes" // >>> match_parens([")", ")"]) // "No" function match_parens(lst){ const open = '('; const close = ')'; const is_good = (s) => { let stack = []; for (let p of s){ if (p === open){ stack.push(p); } else if (p === close){ if (stack.length === 0){ return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1];
return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
if (is_good(str1 + str2)){
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_135_can_arrange.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array array list will not contain // duplicate values. // Examples: // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) // (3l) // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (-1l) public static long canArrange(ArrayList<Long> arr) { long p = -1l;
if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break; } } return p; } }
for (int i = arr.size() - 1; i > 0; i--) {
} public static void main(String[] args) { assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) == (3l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)5l)))) == (-1l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)10l)))) == (2l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)4l, (long)8l, (long)5l, (long)7l, (long)3l)))) == (4l)); assert(canArrange((new ArrayList<Long>(Arrays.asList()))) == (-1l)); } }
humaneval-HumanEval_129_minPath.json-L69
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; } } } let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } }
} return path; }
currCell = nextCell;
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_61_correct_bracketing.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 { // brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correctBracketing(("(")) // (false) // >>> correctBracketing(("()")) // (true) // >>> correctBracketing(("(()())")) // (true) // >>> correctBracketing((")(()")) // (false) public static boolean correctBracketing(String brackets) { int balance = 0; for (int i = 0; i < brackets.length(); i++) { if (brackets.charAt(i) == '(') { balance++; } else { balance--; } if (balance < 0) { return false; }
return balance == 0; } }
}
} public static void main(String[] args) { assert(correctBracketing(("()")) == (true)); assert(correctBracketing(("(()())")) == (true)); assert(correctBracketing(("()()(()())()")) == (true)); assert(correctBracketing(("()()((()()())())(()()(()))")) == (true)); assert(correctBracketing(("((()())))")) == (false)); assert(correctBracketing((")(()")) == (false)); assert(correctBracketing(("(")) == (false)); assert(correctBracketing(("((((")) == (false)); assert(correctBracketing((")")) == (false)); assert(correctBracketing(("(()")) == (false)); assert(correctBracketing(("()()(()())())(()")) == (false)); assert(correctBracketing(("()()(()())()))()")) == (false)); } }
humaneval-HumanEval_124_valid_date.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You 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;
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; } }
if (date.equals("")) 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_44_change_base.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 { // 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"; } StringBuilder sb = new StringBuilder(); while (x>0) { sb.append(x%base);
} return sb.reverse().toString(); } }
x = x/base;
} 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_115_max_fill.json-L35
py
from typing import List def max_fill(grid: List[List[int]], capacity: int) -> int: """ You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) 6 Example 2: >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) 5 Example 3: >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid[:,1].length <= 10^2 * grid[i][j] -> 0 | 1 * 1 <= capacity <= 10 """ times = 0 for row in grid: for i in range(0, len(row), capacity): if 1 in row[i:i+capacity]:
return times
times += 1
def check(candidate): assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) == 6 assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) == 5 assert candidate([[0, 0, 0], [0, 0, 0]], 5) == 0 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2) == 4 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9) == 2 def test_check(): check(max_fill) test_check()
humaneval-HumanEval_160_do_algebra.json-L59
js
//Given two arrays operator, and operand. The first array has basic algebra operations, and // the second array is an array of integers. Use the two given arrays to build the algebric // expression and return the evaluation of this expression. // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // Example: // operator['+', '*', '-'] // array = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array is equal to the length of operand array minus one. // Operand is an array of of non-negative integers. // Operator array has at least one operator, and operand array has at least two operands. function do_algebra(operator, operand){ let do_again; let count = 0; let temp; let answer; while(count < operator.length){ switch(operator[count]){ case '*': operand[count] = operand[count] * operand[count + 1]; operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '//': operand[count] = Math.floor(operand[count] / operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '**': operand[count] = Math.pow(operand[count], operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break;
answer -= operand[0]; break; } operand.splice(0, 1); operator.splice(0, 1); } return answer; }
case '-':
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_42_incr_list.json-L15
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return array list with elements incremented by 1. // >>> incrList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l))) // >>> incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))) // (new ArrayList<Long>(Arrays.asList((long)6l, (long)4l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))) public static ArrayList<Long> incrList(ArrayList<Long> l) {
l.set(i, l.get(i) + 1l); } return l; } }
for (int i = 0; i < l.size(); i++) {
} public static void main(String[] args) { assert(incrList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l))))); assert(incrList((new ArrayList<Long>(Arrays.asList((long)5l, (long)2l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)3l, (long)6l, (long)3l, (long)4l, (long)4l, (long)10l, (long)1l, (long)124l))))); } }
humaneval-HumanEval_116_sort_array.json-L19
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 aBinary = a.toString(2).split('').filter(el => el === '1').length; let bBinary = b.toString(2).split('').filter(el => el === '1').length; if (aBinary === bBinary) { return a - b; } else { return aBinary - bBinary;
}); }
}
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_53_add.json-L8
js
//Add two numbers x and y // >>> add(2, 3) // 5 // >>> add(5, 7) // 12 function add(x, y){ return x + y;
}
const assert = require('node:assert'); function test() { let candidate = add; assert.deepEqual(candidate(0, 1),1); assert.deepEqual(candidate(1, 0),1); assert.deepEqual(candidate(2, 3),5); assert.deepEqual(candidate(5, 7),12); assert.deepEqual(candidate(7, 5),12); } test();
humaneval-HumanEval_106_f.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 { // Implement the function f that takes n as a parameter, // and returns an array array list of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))) public static ArrayList<Long> f(long n) { ArrayList<Long> ret = new ArrayList<Long>(); for (long i = 1l; i <= n; i++) { long v = 0l; if (i % 2 == 0) { v = 1l; for (long j = 2l; j <= i; j++) { v *= j; } } else { v = (i * (i + 1l)) / 2l; }
} return ret; } }
ret.add(v);
} public static void main(String[] args) { assert(f((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))))); assert(f((7l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l, (long)720l, (long)28l))))); assert(f((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); assert(f((3l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l))))); } }
humaneval-HumanEval_90_next_smallest.json-L17
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);
for(var i in lst){ if(lst[i]>smallest&&lst[i]<second_smallest){ second_smallest=lst[i]; } } if(second_smallest==Number.MAX_VALUE){ return undefined; } return second_smallest; }
var second_smallest=Number.MAX_VALUE;
const assert = require('node:assert'); function test() { let candidate = next_smallest; assert.deepEqual(candidate([1, 2, 3, 4, 5]),2); assert.deepEqual(candidate([5, 1, 4, 3, 2]),2); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([1, 1, 1, 1, 0]),1); assert.deepEqual(candidate([1, 1]),undefined); assert.deepEqual(candidate([-35, 34, 12, -45]),-35); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L26
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) }
odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
if(collatz_sequence[i]%2 == 1){
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_149_sorted_list_sum.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 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); } } Collections.sort(result, new Comparator<String>() { @Override public int compare(String s1, String s2) {
return s1.compareTo(s2); } return s1.length() - s2.length(); } }); return result; } }
if (s1.length() == s2.length()) {
} 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_160_do_algebra.json-L52
js
//Given two arrays operator, and operand. The first array has basic algebra operations, and // the second array is an array of integers. Use the two given arrays to build the algebric // expression and return the evaluation of this expression. // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // Example: // operator['+', '*', '-'] // array = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array is equal to the length of operand array minus one. // Operand is an array of of non-negative integers. // Operator array has at least one operator, and operand array has at least two operands. function do_algebra(operator, operand){ let do_again; let count = 0; let temp; let answer; while(count < operator.length){ switch(operator[count]){ case '*': operand[count] = operand[count] * operand[count + 1]; operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '//': operand[count] = Math.floor(operand[count] / operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '**': operand[count] = Math.pow(operand[count], operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; default: count++; do_again = false; } }
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; }
answer = operand[0];
const assert = require('node:assert'); function test() { let candidate = do_algebra; assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37); assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9); assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8); } test();
humaneval-HumanEval_147_get_max_triples.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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>();
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; } }
for (int i = 1; i <= n; i++) {
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_57_monotonic.json-L26
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_156_int_to_mini_roman.json-L29
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) {
num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
res += "cm";
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_56_correct_bracketing.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 { // brackets is a string of "<" and ">". // return true if every opening bracket has a corresponding closing bracket. // >>> correctBracketing(("<")) // (false) // >>> correctBracketing(("<>")) // (true) // >>> correctBracketing(("<<><>>")) // (true) // >>> correctBracketing(("><<>")) // (false) public static boolean correctBracketing(String brackets) { int open = 0; for (int i = 0; i < brackets.length(); i++) { char c = brackets.charAt(i); if (c == '<') { open++; } else {
} if (open < 0) { return false; } } return open == 0; } }
open--;
} public static void main(String[] args) { assert(correctBracketing(("<>")) == (true)); assert(correctBracketing(("<<><>>")) == (true)); assert(correctBracketing(("<><><<><>><>")) == (true)); assert(correctBracketing(("<><><<<><><>><>><<><><<>>>")) == (true)); assert(correctBracketing(("<<<><>>>>")) == (false)); assert(correctBracketing(("><<>")) == (false)); assert(correctBracketing(("<")) == (false)); assert(correctBracketing(("<<<<")) == (false)); assert(correctBracketing((">")) == (false)); assert(correctBracketing(("<<>")) == (false)); assert(correctBracketing(("<><><<><>><>><<>")) == (false)); assert(correctBracketing(("<><><<><>><>>><>")) == (false)); } }
humaneval-HumanEval_7_filter_by_substring.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 { // Filter an input array list of strings only for ones that contain given substring // >>> filterBySubstring((new ArrayList<String>(Arrays.asList())), ("a")) // (new ArrayList<String>(Arrays.asList())) // >>> filterBySubstring((new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"cde", (String)"array"))), ("a")) // (new ArrayList<String>(Arrays.asList((String)"abc", (String)"bacd", (String)"array"))) public static ArrayList<String> filterBySubstring(ArrayList<String> strings, String substring) { return new ArrayList<String>(strings.stream().filter(s -> s.contains(substring)).collect(Collectors.toList())); }
}
} public static void main(String[] args) { assert(filterBySubstring((new ArrayList<String>(Arrays.asList())), ("john")).equals((new ArrayList<String>(Arrays.asList())))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"asd", (String)"xxy", (String)"john doe", (String)"xxxAAA", (String)"xxx"))), ("xxx")).equals((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"xxxAAA", (String)"xxx"))))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"asd", (String)"aaaxxy", (String)"john doe", (String)"xxxAAA", (String)"xxx"))), ("xx")).equals((new ArrayList<String>(Arrays.asList((String)"xxx", (String)"aaaxxy", (String)"xxxAAA", (String)"xxx"))))); assert(filterBySubstring((new ArrayList<String>(Arrays.asList((String)"grunt", (String)"trumpet", (String)"prune", (String)"gruesome"))), ("run")).equals((new ArrayList<String>(Arrays.asList((String)"grunt", (String)"prune"))))); } }
humaneval-HumanEval_146_specialFilter.json-L44
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes an array array list of numbers as input and returns // the number of elements in the array array list that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) // (1l) // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) // (2l) public static long specialFilter(ArrayList<Long> nums) { class helper { public long getFirstDigit(long n) { long[] digits = getDigits(n); return digits[0]; } public long getLastDigit(long n) { long[] digits = getDigits(n); return digits[digits.length - 1]; } public long[] getDigits(long n) { ArrayList<Long> digits = new ArrayList<Long>(); while (n != 0) { digits.add(n % 10); n /= 10; } Collections.reverse(digits); return digits.stream().mapToLong(i -> i).toArray(); } } helper h = new helper(); return nums.stream().filter(x -> x > 10).filter(x -> { long firstDigit = h.getFirstDigit(x); long lastDigit = h.getLastDigit(x); return firstDigit % 2 != 0 && lastDigit % 2 != 0; }).count(); }
}
} public static void main(String[] args) { assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)5l, (long)-2l, (long)1l, (long)-5l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) == (1l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) == (2l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)43l, (long)-12l, (long)93l, (long)125l, (long)121l, (long)109l)))) == (4l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)71l, (long)-2l, (long)-33l, (long)75l, (long)21l, (long)19l)))) == (3l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList()))) == (0l)); } }
humaneval-HumanEval_68_pluck.json-L41
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given an array array list representing a branch of a tree that has non-negative integer nodes // your task is to pluck one of the nodes and return it. // The plucked node should be the node with the smallest even value. // If multiple nodes with the same smallest even value are found return the node that has smallest index. // The plucked node should be returned in an array array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // Explanation: 0 is the smallest value, but there are two zeros, // so we will choose the first zero, which has the smallest index. // Constraints: // * 1 <= nodes.length <= 10000 // * 0 <= node.value public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i;
} } } ArrayList<Long> newArr = new ArrayList<Long>(); if (minIndex == -1) { return newArr; } newArr.add(minValue); newArr.add((long)minIndex); return newArr; } }
minValue = arr.get(i);
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_39_prime_fib.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 { // prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> primeFib((1l)) // (2l) // >>> primeFib((2l)) // (3l) // >>> primeFib((3l)) // (5l) // >>> primeFib((4l)) // (13l) // >>> primeFib((5l)) // (89l) public static long primeFib(long n) { long fib = 1; long prev = 0; long count = 0; while (count != n) {
fib += prev; prev = tmp; if (BigInteger.valueOf(fib).isProbablePrime(1)) { count++; } } return fib; } }
long tmp = fib;
} public static void main(String[] args) { assert(primeFib((1l)) == (2l)); assert(primeFib((2l)) == (3l)); assert(primeFib((3l)) == (5l)); assert(primeFib((4l)) == (13l)); assert(primeFib((5l)) == (89l)); assert(primeFib((6l)) == (233l)); assert(primeFib((7l)) == (1597l)); assert(primeFib((8l)) == (28657l)); assert(primeFib((9l)) == (514229l)); assert(primeFib((10l)) == (433494437l)); } }
humaneval-HumanEval_112_reverse_delete.json-L19
py
from typing import Tuple def reverse_delete(s: str, c: str) -> Tuple[str, bool]: """Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and True/False for the check. Example >>> reverse_delete('abcde', 'ae') ('bcd', False) >>> reverse_delete('abcdef', 'b') ('acdef', False) >>> reverse_delete('abcdedcba', 'ab') ('cdedc', True) """ new_str = '' for i in s:
new_str += i new_str_reverse = new_str[::-1] return (new_str, new_str == new_str_reverse)
if i not in c:
def check(candidate): assert candidate('abcde', 'ae') == ('bcd', False) assert candidate('abcdef', 'b') == ('acdef', False) assert candidate('abcdedcba', 'ab') == ('cdedc', True) assert candidate('dwik', 'w') == ('dik', False) assert candidate('a', 'a') == ('', True) assert candidate('abcdedcba', '') == ('abcdedcba', True) assert candidate('abcdedcba', 'v') == ('abcdedcba', True) assert candidate('vabba', 'v') == ('abba', True) assert candidate('mamma', 'mia') == ('', True) def test_check(): check(reverse_delete) test_check()
humaneval-HumanEval_61_correct_bracketing.json-L14
py
def correct_bracketing(brackets: str) -> bool: """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('(') False >>> correct_bracketing('()') True >>> correct_bracketing('(()())') True >>> correct_bracketing(')(()') False """
for char in brackets: if char == '(': count += 1 elif char == ')': count -= 1 if count < 0: return False return count == 0
count = 0
def check(candidate): assert candidate('()') == True assert candidate('(()())') == True assert candidate('()()(()())()') == True assert candidate('()()((()()())())(()()(()))') == True assert candidate('((()())))') == False assert candidate(')(()') == False assert candidate('(') == False assert candidate('((((') == False assert candidate(')') == False assert candidate('(()') == False assert candidate('()()(()())())(()') == False assert candidate('()()(()())()))()') == False def test_check(): check(correct_bracketing) test_check()
humaneval-HumanEval_17_parse_music.json-L16
py
from typing import List def parse_music(music_string: str) -> List[int]: """ Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] """
return [music_types[x] for x in music_string.split()]
music_types = {'o': 4, 'o|': 2, '.|': 1}
def check(candidate): assert candidate('') == [] assert candidate('o o o o') == [4, 4, 4, 4] assert candidate('.| .| .| .|') == [1, 1, 1, 1] assert candidate('o| o| .| .| o o o o') == [2, 2, 1, 1, 4, 4, 4, 4] assert candidate('o| .| o| .| o o| o o|') == [2, 1, 2, 1, 4, 2, 4, 2] def test_check(): check(parse_music) test_check()
humaneval-HumanEval_66_digitSum.json-L18
js
//Task // Write a function that takes a string as input and returns the sum of the upper characters only' // ASCII codes. // Examples: // >>> digitSum("") // 0 // >>> digitSum("abAB") // 131 // >>> digitSum("abcCd") // 67 // >>> digitSum("helloE") // 69 // >>> digitSum("woArBld") // 131 // >>> digitSum("aAaaaXa") // 153 function digitSum(s){
for(var i = 0; i < s.length; i++){ if(s[i] >= 'A' && s[i] <= 'Z'){ sum += s.charCodeAt(i); } } return sum; }
var sum = 0;
const assert = require('node:assert'); function test() { let candidate = digitSum; assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("abAB"),131); assert.deepEqual(candidate("abcCd"),67); assert.deepEqual(candidate("helloE"),69); assert.deepEqual(candidate("woArBld"),131); assert.deepEqual(candidate("aAaaaXa"),153); assert.deepEqual(candidate(" How are yOu?"),151); assert.deepEqual(candidate("You arE Very Smart"),327); } test();
humaneval-HumanEval_63_fibfib.json-L22
js
//The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib(1) // 0 // >>> fibfib(5) // 4 // >>> fibfib(8) // 24 function fibfib(n){ if(n <= 0){ return 0; } if(n == 1){ return 0; } if(n == 2){ return 1;
return fibfib(n-1) + fibfib(n-2) + fibfib(n-3); }
}
const assert = require('node:assert'); function test() { let candidate = fibfib; assert.deepEqual(candidate(2),1); assert.deepEqual(candidate(1),0); assert.deepEqual(candidate(5),4); assert.deepEqual(candidate(8),24); assert.deepEqual(candidate(10),81); assert.deepEqual(candidate(12),274); assert.deepEqual(candidate(14),927); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L36
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) } if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b})
} else{ odd_numbers.push(1) return odd_numbers } }
return odd_numbers
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_104_unique_digits.json-L40
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of positive integers x. return a sorted array list of all // elements that hasn't any even digit. // Note: Returned array list should be sorted in increasing order. // For example: // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))) // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> uniqueDigits(ArrayList<Long> x) { ArrayList<Long> b = new ArrayList<Long>(); for (int i = 0; i < x.size(); i++) { if (x.get(i) < 0) { x.set(i, x.get(i)*(long)-1); } boolean unique = true; long z = x.get(i); while (z > 0) { long y = z % 10; if (y % 2 == 0) { unique = false; break; } z = z / 10; } if (unique) { b.add(x.get(i)); } } Collections.sort(b); return b; }
}
} public static void main(String[] args) { assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)12345l, (long)2033l, (long)111l, (long)151l)))).equals((new ArrayList<Long>(Arrays.asList((long)111l, (long)151l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)135l, (long)103l, (long)31l)))).equals((new ArrayList<Long>(Arrays.asList((long)31l, (long)135l))))); } }
humaneval-HumanEval_25_factorize.json-L17
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:
factors.append(i) n = n / i i += 1 return factors
while n % i == 0:
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_129_minPath.json-L32
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){
} } } 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; }
startCell = curr;
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_104_unique_digits.json-L12
js
//Given an array of positive integers x. return a sorted array of all // elements that hasn't any even digit. // Note: Returned array should be sorted in increasing order. // For example: // >>> unique_digits([15, 33, 1422, 1]) // [1, 15, 33] // >>> unique_digits([152, 323, 1422, 10]) // [] function unique_digits(x){ let result = [] for(let i = 0; i < x.length; i++){
if(num.indexOf('2') === -1 && num.indexOf('4') === -1 && num.indexOf('6') === -1 && num.indexOf('8') === -1 && num.indexOf('0') === -1){ result.push(x[i]) } } return result.sort(function(a, b){return a-b}) }
let num = x[i].toString()
const assert = require('node:assert'); function test() { let candidate = unique_digits; assert.deepEqual(candidate([15, 33, 1422, 1]),[1, 15, 33]); assert.deepEqual(candidate([152, 323, 1422, 10]),[]); assert.deepEqual(candidate([12345, 2033, 111, 151]),[111, 151]); assert.deepEqual(candidate([135, 103, 31]),[31, 135]); } test();
humaneval-HumanEval_68_pluck.json-L35
js
//"Given an array representing a branch of a tree that has non-negative integer nodes // your task is to pluck one of the nodes and return it. // The plucked node should be the node with the smallest even value. // If multiple nodes with the same smallest even value are found return the node that has smallest index. // The plucked node should be returned in an array, [ smalest_value, its index ], // If there are no even values or the given array is empty, return []. // Example 1: // >>> pluck([4, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck([1, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck([]) // [] // Example 4: // >>> pluck([5, 0, 3, 0, 4, 2]) // [0, 1] // Explanation: 0 is the smallest value, but there are two zeros, // so we will choose the first zero, which has the smallest index. // Constraints: // * 1 <= nodes.length <= 10000 // * 0 <= node.value function pluck(arr){ let result = [], index = -1; for(let i = 0; i < arr.length; i++){ if(arr[i] % 2 === 0){ if(result.length === 0 || result[0] > arr[i]){ result = [arr[i], i]; } }
return result; }
}
const assert = require('node:assert'); function test() { let candidate = pluck; assert.deepEqual(candidate([4, 2, 3]),[2, 1]); assert.deepEqual(candidate([1, 2, 3]),[2, 1]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5, 0, 3, 0, 4, 2]),[0, 1]); assert.deepEqual(candidate([1, 2, 3, 0, 5, 3]),[0, 3]); assert.deepEqual(candidate([5, 4, 8, 4, 8]),[4, 1]); assert.deepEqual(candidate([7, 6, 7, 1]),[6, 1]); assert.deepEqual(candidate([7, 9, 7, 1]),[]); } test();
humaneval-HumanEval_85_add.json-L11
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_8_sum_product.json-L15
js
//For a given array of integers, return an array consisting of a sum and a product of all the integers in an array. // Empty sum should be equal to 0 and empty product should be equal to 1. // >>> sum_product([]) // [0, 1] // >>> sum_product([1, 2, 3, 4]) // [10, 24] function sum_product(numbers){ if(numbers.length == 0){ return [0, 1]; } let sum = 0; let product = 1; for(let i = 0; i < numbers.length; i++){ sum += numbers[i];
} return [sum, product]; }
product *= numbers[i];
const assert = require('node:assert'); function test() { let candidate = sum_product; assert.deepEqual(candidate([]),[0, 1]); assert.deepEqual(candidate([1, 1, 1]),[3, 1]); assert.deepEqual(candidate([100, 0]),[100, 0]); assert.deepEqual(candidate([3, 5, 7]),[15, 105]); assert.deepEqual(candidate([10]),[10, 10]); } test();
humaneval-HumanEval_1_separate_paren_groups.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 { // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0;
char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } } return output; } }
for (int i = 0; i < paren_string.length(); i++) {
} public static void main(String[] args) { assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())"))))); assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))"))))); assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))"))))); assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))))); } }
humaneval-HumanEval_98_count_upper.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s, count the number of uppercase vowels in even indices. // For example: // >>> countUpper(("aBCdEf")) // (1l) // >>> countUpper(("abcdefg")) // (0l) // >>> countUpper(("dBBE")) // (0l) public static long countUpper(String s) { return (long) IntStream.range(0, s.length()) .filter(i -> i % 2 == 0)
.count(); } }
.filter(i -> s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I' || s.charAt(i) == 'O' || s.charAt(i) == 'U')
} public static void main(String[] args) { assert(countUpper(("aBCdEf")) == (1l)); assert(countUpper(("abcdefg")) == (0l)); assert(countUpper(("dBBE")) == (0l)); assert(countUpper(("B")) == (0l)); assert(countUpper(("U")) == (1l)); assert(countUpper(("")) == (0l)); assert(countUpper(("EEEE")) == (2l)); } }
humaneval-HumanEval_77_iscube.json-L27
py
def iscube(a: int) -> bool: """ Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: >>> iscube(1) True >>> iscube(2) False >>> iscube(-1) True >>> iscube(64) True >>> iscube(0) True >>> iscube(180) False """ import math a = abs(a) if a == 0: return True for i in range(1,int(math.sqrt(a))+1): if i**3 == a: return True
pass
return False
def check(candidate): assert candidate(1) == True assert candidate(2) == False assert candidate(-1) == True assert candidate(64) == True assert candidate(180) == False assert candidate(1000) == True assert candidate(0) == True assert candidate(1729) == False def test_check(): check(iscube) test_check()
humaneval-HumanEval_150_x_or_y.json-L13
py
def x_or_y(n: int, x: int, y: int) -> int: """A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. Examples: >>> x_or_y(7, 34, 12) 34 >>> x_or_y(15, 8, 5) 5 """ if n < 2:
for i in range(2, n): if n % i == 0: return y return x
return y
def check(candidate): assert candidate(7, 34, 12) == 34 assert candidate(15, 8, 5) == 5 assert candidate(3, 33, 5212) == 33 assert candidate(1259, 3, 52) == 3 assert candidate(7919, -1, 12) == -1 assert candidate(3609, 1245, 583) == 583 assert candidate(91, 56, 129) == 129 assert candidate(6, 34, 1234) == 1234 assert candidate(1, 2, 0) == 0 assert candidate(2, 2, 0) == 2 def test_check(): check(x_or_y) test_check()
humaneval-HumanEval_18_how_many_times.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 { // Find how many times a given substring can be found in the original string. Count overlaping cases. // >>> howManyTimes((""), ("a")) // (0l) // >>> howManyTimes(("aaa"), ("a")) // (3l) // >>> howManyTimes(("aaaa"), ("aa")) // (3l) public static long howManyTimes(String string, String substring) { long count = 0; int index = 0; while (index != -1) { index = string.indexOf(substring, index);
index++; count++; } } return count; } }
if (index != -1) {
} public static void main(String[] args) { assert(howManyTimes((""), ("x")) == (0l)); assert(howManyTimes(("xyxyxyx"), ("x")) == (4l)); assert(howManyTimes(("cacacacac"), ("cac")) == (4l)); assert(howManyTimes(("john doe"), ("john")) == (1l)); } }
humaneval-HumanEval_56_correct_bracketing.json-L15
js
//brackets is a string of "<" and ">". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("<") // false // >>> correct_bracketing("<>") // true // >>> correct_bracketing("<<><>>") // true // >>> correct_bracketing("><<>") // false function correct_bracketing(brackets){ var opens = 0; for (var i = 0; i < brackets.length; i++) { if (brackets[i] === "<") {
} else if (brackets[i] === ">") { opens--; } if (opens < 0) { return false; } } return opens === 0; }
opens++;
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("<>"),true); assert.deepEqual(candidate("<<><>>"),true); assert.deepEqual(candidate("<><><<><>><>"),true); assert.deepEqual(candidate("<><><<<><><>><>><<><><<>>>"),true); assert.deepEqual(candidate("<<<><>>>>"),false); assert.deepEqual(candidate("><<>"),false); assert.deepEqual(candidate("<"),false); assert.deepEqual(candidate("<<<<"),false); assert.deepEqual(candidate(">"),false); assert.deepEqual(candidate("<<>"),false); assert.deepEqual(candidate("<><><<><>><>><<>"),false); assert.deepEqual(candidate("<><><<><>><>>><>"),false); } test();
humaneval-HumanEval_141_file_name_check.json-L18
js
//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: // >>> file_name_check("example.txt") // "Yes" // >>> file_name_check("1example.dll") // "No" function file_name_check(file_name){ let str_1 = file_name.slice(0,file_name.indexOf('.')); let str_2 = file_name.slice(file_name.indexOf('.')+1);
if (file_name.includes('.') && /[a-zA-Z]/.test(str_1[0]) && (str_2 == 'txt' || str_2 == 'exe' || str_2 == 'dll') && str_1.length != 0 && str_3.filter(item => /[0-9]/.test(item)).length < 4) { return 'Yes'; } return 'No'; }
let str_3 = file_name.split('');
const assert = require('node:assert'); function test() { let candidate = file_name_check; assert.deepEqual(candidate("example.txt"),"Yes"); assert.deepEqual(candidate("1example.dll"),"No"); assert.deepEqual(candidate("s1sdf3.asd"),"No"); assert.deepEqual(candidate("K.dll"),"Yes"); assert.deepEqual(candidate("MY16FILE3.exe"),"Yes"); assert.deepEqual(candidate("His12FILE94.exe"),"No"); assert.deepEqual(candidate("_Y.txt"),"No"); assert.deepEqual(candidate("?aREYA.exe"),"No"); assert.deepEqual(candidate("/this_is_valid.dll"),"No"); assert.deepEqual(candidate("this_is_valid.wow"),"No"); assert.deepEqual(candidate("this_is_valid.txt"),"Yes"); assert.deepEqual(candidate("this_is_valid.txtexe"),"No"); assert.deepEqual(candidate("#this2_i4s_5valid.ten"),"No"); assert.deepEqual(candidate("@this1_is6_valid.exe"),"No"); assert.deepEqual(candidate("this_is_12valid.6exe4.txt"),"No"); assert.deepEqual(candidate("all.exe.txt"),"No"); assert.deepEqual(candidate("I563_No.exe"),"Yes"); assert.deepEqual(candidate("Is3youfault.txt"),"Yes"); assert.deepEqual(candidate("no_one#knows.dll"),"Yes"); assert.deepEqual(candidate("1I563_Yes3.exe"),"No"); assert.deepEqual(candidate("I563_Yes3.txtt"),"No"); assert.deepEqual(candidate("final..txt"),"No"); assert.deepEqual(candidate("final132"),"No"); assert.deepEqual(candidate("_f4indsartal132."),"No"); assert.deepEqual(candidate(".txt"),"No"); assert.deepEqual(candidate("s."),"No"); } test();
humaneval-HumanEval_5_intersperse.json-L13
py
from typing import List def intersperse(numbers: List[int], delimeter: int) -> List[int]: """ Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """ result = [] if len(numbers) == 0: return result
for num in numbers[1:]: result.append(delimeter) result.append(num) return result
result.append(numbers[0])
def check(candidate): assert candidate([], 7) == [] assert candidate([5, 6, 3, 2], 8) == [5, 8, 6, 8, 3, 8, 2] assert candidate([2, 2, 2], 2) == [2, 2, 2, 2, 2] def test_check(): check(intersperse) test_check()
humaneval-HumanEval_31_is_prime.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return true if a given number is prime, and false otherwise. // >>> isPrime((6l)) // (false) // >>> isPrime((101l)) // (true) // >>> isPrime((11l)) // (true) // >>> isPrime((13441l)) // (true) // >>> isPrime((61l)) // (true) // >>> isPrime((4l)) // (false) // >>> isPrime((1l)) // (false) public static boolean isPrime(long n) { if (n <= 1) return false;
if (n % 2 == 0 || n % 3 == 0) return false; long i = 5; while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; } return true; } }
if (n <= 3) return true;
} public static void main(String[] args) { assert(isPrime((6l)) == (false)); assert(isPrime((101l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((13441l)) == (true)); assert(isPrime((61l)) == (true)); assert(isPrime((4l)) == (false)); assert(isPrime((1l)) == (false)); assert(isPrime((5l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((17l)) == (true)); assert(isPrime((85l)) == (false)); assert(isPrime((77l)) == (false)); assert(isPrime((255379l)) == (false)); } }
humaneval-HumanEval_57_monotonic.json-L18
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_83_starts_one_ends.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer n, return the count of the numbers of n-digit // positive integers that start or end with 1. public static long startsOneEnds(long n) { long lower = (long) Math.pow(10, n - 1); long upper = (long) Math.pow(10, n) - 1; long count = 0; for (long i = lower; i <= upper; i++) { String s = "" + i; if (s.startsWith("1") || s.endsWith("1")) count++; } return count; }
}
} public static void main(String[] args) { assert(startsOneEnds((1l)) == (1l)); assert(startsOneEnds((2l)) == (18l)); assert(startsOneEnds((3l)) == (180l)); assert(startsOneEnds((4l)) == (1800l)); assert(startsOneEnds((5l)) == (18000l)); } }
humaneval-HumanEval_91_is_bored.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You'll be given a string of words, and your task is to count the number // of boredoms. A boredom is a sentence that starts with the word "I". // Sentences are delimited by '.', '?' or '!'. // For example: // >>> isBored(("Hello world")) // (0l) // >>> isBored(("The sky is blue. The sun is shining. I love this weather")) // (1l) public static long isBored(String S) { long boredoms = 0; String[] sentences = S.split("\\.\\s|\\?\\s|\\!\\s");
String[] words = sentence.split("\\s"); if (words.length > 0 && words[0].equals("I")) { boredoms++; } } return boredoms; } }
for (String sentence : sentences) {
} public static void main(String[] args) { assert(isBored(("Hello world")) == (0l)); assert(isBored(("Is the sky blue?")) == (0l)); assert(isBored(("I love It !")) == (1l)); assert(isBored(("bIt")) == (0l)); assert(isBored(("I feel good today. I will be productive. will kill It")) == (2l)); assert(isBored(("You and I are going for a walk")) == (0l)); } }
humaneval-HumanEval_137_compare_one.json-L15
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){
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; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){ return a; } else if (a < b[0]){ return b; } else { return undefined; } } }
if (a > b) {
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_114_minSubArraySum.json-L39
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of integers nums, find the minimum sum of any non-empty sub-array array list // of nums. // Example // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) // (1l) // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) // (-6l) public static long minSubArraySum(ArrayList<Long> nums) { long minSum = Long.MAX_VALUE; long prevMinSum = Long.MAX_VALUE; for (int i = 0; i < nums.size(); i++) { long currSum = nums.get(i); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum; } for (int j = i + 1; j < nums.size(); j++) { currSum += nums.get(j); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum; } } } return minSum; }
}
} public static void main(String[] args) { assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) == (1l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)2l, (long)-10l)))) == (-14l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-9999999999999999l)))) == (-9999999999999999l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)0l, (long)10l, (long)20l, (long)1000000l)))) == (0l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)10l, (long)11l, (long)13l, (long)8l, (long)3l, (long)4l)))) == (3l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-33l, (long)32l, (long)-1l, (long)0l, (long)-2l)))) == (-33l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-10l)))) == (-10l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)7l)))) == (7l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l)))) == (-1l)); } }
humaneval-HumanEval_75_is_multiply_prime.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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);
} } if (a > 2) { arr.add(a); } return arr.size() == 3; } }
a /= i;
} 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_128_prod_signs.json-L18
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_108_count_nums.json-L20
js
//Write a function count_nums which takes an array of integers and returns // the number of elements which has a sum of digits > 0. // If a number is negative, then its first signed digit will be negative: // e.g. -123 has signed digits -1, 2, and 3. // >>> count_nums([]) // 0 // >>> count_nums([-1, 11, -11]) // 1 // >>> count_nums([1, 1, 2]) // 3 function count_nums(arr){ if(!arr.length) { return 0; } var count = 0; for(var i = 0; i < arr.length; i++) { var sum = 0; var str = arr[i].toString(); if(str[0] === '-') {
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; }
sum += Number(str[0] + str[1]);
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_27_flip_case.json-L13
js
//For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flip_case("Hello") // "hELLO" function flip_case(string){ var result = ""; for(var i = 0; i < string.length; i++){ if(string[i] == string[i].toUpperCase()){ result += string[i].toLowerCase(); }else{ result += string[i].toUpperCase(); } }
}
return result;
const assert = require('node:assert'); function test() { let candidate = flip_case; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hello!"),"hELLO!"); assert.deepEqual(candidate("These violent delights have violent ends"),"tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"); } test();
humaneval-HumanEval_128_prod_signs.json-L22
py
from typing import List, Optional def prod_signs(arr: List[int]) -> Optional[int]: """ You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prod_signs([1, 2, 2, -4]) 9 >>> prod_signs([0, 1]) 0 >>> prod_signs([]) None """ def product(lst: List[int]) -> int: out = 1 for item in lst: out *= item
if len(arr) == 0: return None else: sign_arr = [] for num in arr: if num > 0: sign_arr.append(1) elif num < 0: sign_arr.append(-1) else: sign_arr.append(0) return sum(map(abs, arr)) * product(sign_arr)
return out
def check(candidate): assert candidate([1, 2, 2, -4]) == -9 assert candidate([0, 1]) == 0 assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10 assert candidate([]) == None assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20 assert candidate([-1, 1, -1, 1]) == 4 assert candidate([-1, 1, 1, 1]) == -4 assert candidate([-1, 1, 1, 0]) == 0 def test_check(): check(prod_signs) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L49
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) {
num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
res += "l";
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_48_is_palindrome.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 { // Checks if given string is a palindrome // >>> isPalindrome(("")) // (true) // >>> isPalindrome(("aba")) // (true) // >>> isPalindrome(("aaaaa")) // (true) // >>> isPalindrome(("zbcd")) // (false) public static boolean isPalindrome(String text) { boolean isPalindrome = true; int left = 0; int right = text.length() - 1; while (left < right) { if (text.charAt(left) != text.charAt(right)) { isPalindrome = false; break; } left++; right--;
return isPalindrome; } }
}
} public static void main(String[] args) { assert(isPalindrome(("")) == (true)); assert(isPalindrome(("aba")) == (true)); assert(isPalindrome(("aaaaa")) == (true)); assert(isPalindrome(("zbcd")) == (false)); assert(isPalindrome(("xywyx")) == (true)); assert(isPalindrome(("xywyz")) == (false)); assert(isPalindrome(("xywzx")) == (false)); } }
humaneval-HumanEval_88_sort_array.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of non-negative integers, return a cojava of the given array array list after sorting, // you will sort the given array array list in ascending order if the sum( first index value, last index value) is odd, // or sort it in descending order if the sum( first index value, last index value) is even. // Note: // * don't change the given array array list. // Examples: // >>> sortArray((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)5l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l, (long)5l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l, (long)6l)))) // (new ArrayList<Long>(Arrays.asList((long)6l, (long)5l, (long)4l, (long)3l, (long)2l, (long)1l, (long)0l))) public static ArrayList<Long> sortArray(ArrayList<Long> array) { if(array.size()==0) { return array; } if(array.size()==1) { return array; } if(array.size()>1) { if((array.get(0)+array.get(array.size()-1))%2==0) { Collections.sort(array, Collections.reverseOrder()); } else {
} } return array; } }
Collections.sort(array);
} public static void main(String[] args) { assert(sortArray((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l, (long)5l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)3l, (long)0l, (long)1l, (long)5l, (long)6l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l, (long)4l, (long)3l, (long)2l, (long)1l, (long)0l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)15l, (long)42l, (long)87l, (long)32l, (long)11l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)11l, (long)15l, (long)32l, (long)42l, (long)87l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)21l, (long)14l, (long)23l, (long)11l)))).equals((new ArrayList<Long>(Arrays.asList((long)23l, (long)21l, (long)14l, (long)11l))))); } }
humaneval-HumanEval_158_find_max.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 { // Write a function that accepts an array array list of strings. // The array list contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))) // ("string") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))) // ("enam") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))) // ("aaaaaaa") public static String findMax(ArrayList<String> words) { Map<String, Integer> wordsToUniqueCharacters = new HashMap<String, Integer>(); for (String word : words) { Set<Character> uniqueCharacters = new HashSet<Character>(); for (char c : word.toCharArray()) { uniqueCharacters.add(c); } wordsToUniqueCharacters.put(word, uniqueCharacters.size()); } words.sort(new Comparator<String>() { @Override
int compareResult = wordsToUniqueCharacters.get(o2).compareTo(wordsToUniqueCharacters.get(o1)); if (compareResult == 0) { return o1.compareTo(o2); } return compareResult; } }); return words.get(0); } }
public int compare(String o1, String o2) {
} public static void main(String[] args) { assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))).equals(("string"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))).equals(("enam"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))).equals(("aaaaaaa"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"abc", (String)"cba")))).equals(("abc"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"this", (String)"game", (String)"of", (String)"footbott")))).equals(("footbott"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"gonna", (String)"rock")))).equals(("gonna"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"a", (String)"mad", (String)"nation")))).equals(("nation"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"this", (String)"is", (String)"a", (String)"prrk")))).equals(("this"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"b")))).equals(("b"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"play", (String)"play")))).equals(("play"))); } }
humaneval-HumanEval_123_get_odd_collatz.json-L40
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) } if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i]) odd_count += 1 } if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1)
} }
return odd_numbers
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L28
js
//Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> get_odd_collatz(5) // [1, 5] function get_odd_collatz(n){ var collatz_sequence = [] var odd_numbers = [] var odd_count = 0 collatz_sequence.push(n) for(var i = 0; i < collatz_sequence.length; i++){ if(collatz_sequence[i]%2 == 0){ collatz_sequence.push(collatz_sequence[i]/2) } else if(collatz_sequence[i]%2 == 1){ collatz_sequence.push(collatz_sequence[i]*3+1) } if(collatz_sequence[i]%2 == 1){ odd_numbers.push(collatz_sequence[i])
} if(collatz_sequence[i] == 1){ break } } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
odd_count += 1
const assert = require('node:assert'); function test() { let candidate = get_odd_collatz; assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]); assert.deepEqual(candidate(5),[1, 5]); assert.deepEqual(candidate(12),[1, 3, 5]); assert.deepEqual(candidate(1),[1]); } test();
humaneval-HumanEval_109_move_one_ball.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 { // We have an array array list 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array array list will be randomly ordered. Your task is to determine if // it is possible to get an array array list sorted in non-decreasing order by performing // the following operation on the given array array list: // You are allowed to perform right shift operation any number of times. // One right shift operation means shifting all elements of the array array list by one // position in the right direction. The last element of the array array list will be moved to // the starting position in the array array list i.e. 0th index. // If it is possible to obtain the sorted array array list by performing the above operation // then return true else return false. // If the given array array list is empty then return true. // Note: The given array list is guaranteed to have unique elements. // For Example: // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) // (true) // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array array list. // >>> moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) // (false) // Explanation:It is not possible to get non-decreasing order for the given // array array list by performing any number of right shift operations. public static boolean moveOneBall(ArrayList<Long> arr) { if (arr.size() == 0) return true; ArrayList<Long> sorted = new ArrayList<Long>(arr); Collections.sort(sorted);
ArrayList<Long> copy = new ArrayList<Long>(arr); long last = copy.remove(copy.size() - 1); copy.add(0, last); if (copy.equals(sorted)) return true; arr = copy; } return false; } }
for (int i = 0; i < arr.size(); i++) {
} public static void main(String[] args) { assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)4l, (long)5l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)10l, (long)1l, (long)2l)))) == (true)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)4l, (long)1l, (long)2l)))) == (false)); assert(moveOneBall((new ArrayList<Long>(Arrays.asList()))) == (true)); } }
humaneval-HumanEval_115_max_fill.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 rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // Example 1: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) // (6l) // Example 2: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) // (5l) // Example 3: // >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) // (0l) // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) { long count = 0l; for (ArrayList<Long> well : grid) { long level = 0l; for (Long unit : well) { if (unit == 1l) { level += 1l; } } long units = level / capacity; if (level % capacity != 0l) {
} count += units; } return count; } }
units += 1l;
} public static void main(String[] args) { assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l)); assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l)); } }
humaneval-HumanEval_81_numerical_letter_grade.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 { // It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array array list of GPAs for some students and you have to write // a function that can output an array array list of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-");
letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-"); } else { letterGrades.add("E"); } } return letterGrades; } }
} else if (currentGrade > 2.0f) {
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_143_words_in_sentence.json-L34
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> wordsInSentence(("This is a test")) // ("is") // Example 2: // >>> wordsInSentence(("lets go for swimming")) // ("go for") // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters public static String wordsInSentence(String sentence) { StringBuilder ans = new StringBuilder(); String[] words = sentence.split(" "); int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; boolean isPrime; for (String word : words) { isPrime = false; for (int prime : primes) { if (word.length() == prime) { isPrime = true; break;
} if (isPrime) { ans.append(word + " "); } } if (ans.length() > 0) { ans.deleteCharAt(ans.length() - 1); } return ans.toString(); } }
}
} public static void main(String[] args) { assert(wordsInSentence(("This is a test")).equals(("is"))); assert(wordsInSentence(("lets go for swimming")).equals(("go for"))); assert(wordsInSentence(("there is no place available here")).equals(("there is no place"))); assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein"))); assert(wordsInSentence(("go for it")).equals(("go for it"))); assert(wordsInSentence(("here")).equals((""))); assert(wordsInSentence(("here is")).equals(("is"))); } }
humaneval-HumanEval_119_match_parens.json-L20
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){
stack.push(p); } else if (p === close){ if (stack.length === 0){ return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
if (p === open){
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_6_parse_nested_parens.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 { // 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;
for (char c : paren.toCharArray()) { if (c == '(') { current_depth += 1; max_depth = Math.max(max_depth, current_depth); } else if (c == ')') { current_depth -= 1; } } result.add(max_depth); } return result; } }
long current_depth = 0;
} 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_151_double_the_difference.json-L20
py
from typing import List def double_the_difference(lst: List[float]) -> int: """ Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. >>> double_the_difference([1, 3, 2, 0]) 10 >>> double_the_difference([-1, -2, 0]) 0 >>> double_the_difference([9, -2]) 81 >>> double_the_difference([0]) 0 If the input list is empty, return 0. """ sum = 0
if not x < 0 and x % 2 == 1: sum += x * x return sum
for x in lst:
def check(candidate): assert candidate([]) == 0 assert candidate([5.0, 4.0]) == 25 assert candidate([0.1, 0.2, 0.3]) == 0 assert candidate([-10.0, -20.0, -30.0]) == 0 assert candidate([-1.0, -2.0, 8.0]) == 0 assert candidate([0.2, 3.0, 5.0]) == 34 assert candidate([-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0]) == 165 def test_check(): check(double_the_difference) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L23
py
def int_to_mini_roman(number: int) -> str: """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) 'xix' >>> int_to_mini_roman(152) 'clii' >>> int_to_mini_roman(426) 'cdxxvi' """ roman_numerals = { 1000: 'm', 900: 'cm', 500: 'd', 400: 'cd', 100: 'c', 90: 'xc', 50: 'l',
10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i' } roman_numeral = '' for key in sorted(roman_numerals.keys(), reverse=True): roman_numeral += roman_numerals[key] * (number // key) number = number % key return roman_numeral
40: 'xl',
def check(candidate): assert candidate(19) == 'xix' assert candidate(152) == 'clii' assert candidate(251) == 'ccli' assert candidate(426) == 'cdxxvi' assert candidate(500) == 'd' assert candidate(1) == 'i' assert candidate(4) == 'iv' assert candidate(43) == 'xliii' assert candidate(90) == 'xc' assert candidate(94) == 'xciv' assert candidate(532) == 'dxxxii' assert candidate(900) == 'cm' assert candidate(994) == 'cmxciv' assert candidate(1000) == 'm' def test_check(): check(int_to_mini_roman) test_check()
humaneval-HumanEval_10_make_palindrome.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 { // Find the shortest palindrome that begins with a supplied string. // Algorithm idea is simple: // - Find the longest postfix of supplied string that is a palindrome. // - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. // >>> makePalindrome(("")) // ("") // >>> makePalindrome(("cat")) // ("catac") // >>> makePalindrome(("cata")) // ("catac") public static String makePalindrome(String string) { StringBuilder newString = new StringBuilder(string); String reverse = new StringBuilder(string).reverse().toString(); for (int index = 0; index < string.length(); index++) { if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { newString.append(reverse.substring(string.length() - index)); break;
} return newString.toString(); } }
}
} public static void main(String[] args) { assert(makePalindrome(("")).equals((""))); assert(makePalindrome(("x")).equals(("x"))); assert(makePalindrome(("xyz")).equals(("xyzyx"))); assert(makePalindrome(("xyx")).equals(("xyx"))); assert(makePalindrome(("jerry")).equals(("jerryrrej"))); } }
humaneval-HumanEval_0_has_close_elements.json-L9
js
//Check if in given array of numbers, are any two numbers closer to each other than // given threshold. // >>> has_close_elements([1.0, 2.0, 3.0], 0.5) // false // >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) // true function has_close_elements(numbers, threshold){ for(var i = 0; i < numbers.length; i++){
if(Math.abs(numbers[i] - numbers[j]) < threshold){ return true; } } } return false; }
for(var j = i + 1; j < numbers.length; j++){
const assert = require('node:assert'); function test() { let candidate = has_close_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3),true); assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05),false); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95),true); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8),false); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1),true); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0),true); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5),false); } test();
humaneval-HumanEval_59_largest_prime_factor.json-L13
py
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ largest = 1 factor = 2 while factor < n: if n % factor == 0: largest = factor
n = n // factor factor += 1 return max(largest, n)
while n % factor == 0:
def check(candidate): assert candidate(15) == 5 assert candidate(27) == 3 assert candidate(63) == 7 assert candidate(330) == 11 assert candidate(13195) == 29 def test_check(): check(largest_prime_factor) test_check()
humaneval-HumanEval_129_minPath.json-L44
py
from typing import List def minPath(grid: List[List[int]], k: int) -> List[int]: """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) [1, 2, 1] >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) [1] """ min_val = float('inf') for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path = [min_val] while len(path) < k: min_val = float('inf') for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val:
row = i col = j path.append(min_val) return path
min_val = grid[i][j]
def check(candidate): assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3] def test_check(): check(minPath) test_check()
humaneval-HumanEval_89_encrypt.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 { // Create a function encrypt that takes a string as an argument and // returns a string encrypted with the alphabet being rotated. // The alphabet should be rotated in a manner such that the letters // shift down by two multiplied to two places. // For example: // >>> encrypt(("hi")) // ("lm") // >>> encrypt(("asdfghjkl")) // ("ewhjklnop") // >>> encrypt(("gf")) // ("kj") // >>> encrypt(("et")) // ("ix") public static String encrypt(String s) { StringBuffer b = new StringBuffer(); for (char c : s.toCharArray()) { b.append((char)((c+4) > 'z' ? (((c+4)%'z')+'a'-1) : c+4)); }
} }
return b.toString();
} public static void main(String[] args) { assert(encrypt(("hi")).equals(("lm"))); assert(encrypt(("asdfghjkl")).equals(("ewhjklnop"))); assert(encrypt(("gf")).equals(("kj"))); assert(encrypt(("et")).equals(("ix"))); assert(encrypt(("faewfawefaewg")).equals(("jeiajeaijeiak"))); assert(encrypt(("hellomyfriend")).equals(("lippsqcjvmirh"))); assert(encrypt(("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh")).equals(("hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"))); assert(encrypt(("a")).equals(("e"))); } }
humaneval-HumanEval_153_Strongest_Extension.json-L26
js
//You will be given the name of a class (a string) and an array of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array. // For example, if you are given "Slices" as the class and an array of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> Strongest_Extension("my_class", ["AA", "Be", "CC"]) // "my_class.AA" function Strongest_Extension(class_name, extensions){ var output = class_name + "."; var min_strength = 1; for (var i = 0; i < extensions.length; i++) { var strength = -1*(extensions[i].replace(/[^A-Z]/g, "").length - extensions[i].replace(/[^a-z]/g, "").length); if (strength < min_strength) { min_strength = strength; output = class_name + "." + extensions[i]; }
return output; }
}
const assert = require('node:assert'); function test() { let candidate = Strongest_Extension; assert.deepEqual(candidate("Watashi", ["tEN", "niNE", "eIGHt8OKe"]),"Watashi.eIGHt8OKe"); assert.deepEqual(candidate("Boku123", ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]),"Boku123.YEs.WeCaNe"); assert.deepEqual(candidate("__YESIMHERE", ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]),"__YESIMHERE.NuLl__"); assert.deepEqual(candidate("K", ["Ta", "TAR", "t234An", "cosSo"]),"K.TAR"); assert.deepEqual(candidate("__HAHA", ["Tab", "123", "781345", "-_-"]),"__HAHA.123"); assert.deepEqual(candidate("YameRore", ["HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"]),"YameRore.okIWILL123"); assert.deepEqual(candidate("finNNalLLly", ["Die", "NowW", "Wow", "WoW"]),"finNNalLLly.WoW"); assert.deepEqual(candidate("_", ["Bb", "91245"]),"_.Bb"); assert.deepEqual(candidate("Sp", ["671235", "Bb"]),"Sp.671235"); } test();
humaneval-HumanEval_113_odd_count.json-L21
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){ odd_sum += 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; }
}
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_89_encrypt.json-L16
js
//Create a function encrypt that takes a string as an argument and // returns a string encrypted with the alphabet being rotated. // The alphabet should be rotated in a manner such that the letters // shift down by two multiplied to two places. // For example: // >>> encrypt("hi") // "lm" // >>> encrypt("asdfghjkl") // "ewhjklnop" // >>> encrypt("gf") // "kj" // >>> encrypt("et") // "ix" function encrypt(s){ var alphabet = "abcdefghijklmnopqrstuvwxyz";
var shiftBy = 2 * 2; for(var i = 0; i < s.length; i++){ var index = alphabet.indexOf(s[i]); newString += alphabet[(index + shiftBy) % 26]; } return newString; }
var newString = "";
const assert = require('node:assert'); function test() { let candidate = encrypt; assert.deepEqual(candidate("hi"),"lm"); assert.deepEqual(candidate("asdfghjkl"),"ewhjklnop"); assert.deepEqual(candidate("gf"),"kj"); assert.deepEqual(candidate("et"),"ix"); assert.deepEqual(candidate("faewfawefaewg"),"jeiajeaijeiak"); assert.deepEqual(candidate("hellomyfriend"),"lippsqcjvmirh"); assert.deepEqual(candidate("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh"),"hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"); assert.deepEqual(candidate("a"),"e"); } test();
humaneval-HumanEval_39_prime_fib.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 { // prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> primeFib((1l)) // (2l) // >>> primeFib((2l)) // (3l) // >>> primeFib((3l)) // (5l) // >>> primeFib((4l)) // (13l) // >>> primeFib((5l)) // (89l) public static long primeFib(long n) { long fib = 1; long prev = 0; long count = 0; while (count != n) { long tmp = fib; fib += prev;
if (BigInteger.valueOf(fib).isProbablePrime(1)) { count++; } } return fib; } }
prev = tmp;
} public static void main(String[] args) { assert(primeFib((1l)) == (2l)); assert(primeFib((2l)) == (3l)); assert(primeFib((3l)) == (5l)); assert(primeFib((4l)) == (13l)); assert(primeFib((5l)) == (89l)); assert(primeFib((6l)) == (233l)); assert(primeFib((7l)) == (1597l)); assert(primeFib((8l)) == (28657l)); assert(primeFib((9l)) == (514229l)); assert(primeFib((10l)) == (433494437l)); } }
humaneval-HumanEval_137_compare_one.json-L43
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float):
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
if a > 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_59_largest_prime_factor.json-L14
py
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ largest = 1 factor = 2 while factor < n: if n % factor == 0: largest = factor while n % factor == 0:
factor += 1 return max(largest, n)
n = n // factor
def check(candidate): assert candidate(15) == 5 assert candidate(27) == 3 assert candidate(63) == 7 assert candidate(330) == 11 assert candidate(13195) == 29 def test_check(): check(largest_prime_factor) test_check()
humaneval-HumanEval_111_histogram.json-L42
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string representing a space separated lowercase letters, return a hash map // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram(("a b c")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) { HashMap<String,Long> s = new HashMap<String,Long>(); if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" "); for (String sss : ss) { if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) {
s.put(key, hm.get(key)); } } } return s; } }
if (hm.get(key) == max) {
} 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_77_iscube.json-L24
py
def iscube(a: int) -> bool: """ Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: >>> iscube(1) True >>> iscube(2) False >>> iscube(-1) True >>> iscube(64) True >>> iscube(0) True >>> iscube(180) False """ import math a = abs(a) if a == 0: return True
if i**3 == a: return True return False pass
for i in range(1,int(math.sqrt(a))+1):
def check(candidate): assert candidate(1) == True assert candidate(2) == False assert candidate(-1) == True assert candidate(64) == True assert candidate(180) == False assert candidate(1000) == True assert candidate(0) == True assert candidate(1729) == False def test_check(): check(iscube) test_check()
humaneval-HumanEval_142_sum_squares.json-L19
js
//" // This function will take an array of integers. For all entries in the array, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the array whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // Examples: // >>> lst // [1, 2, 3] // >>> lst // [] // >>> lst // [-1, -5, 2, -1, -5] function sum_squares(lst){ var sum = 0; var len = lst.length; for (var i = 0; i < len; i++){ if (i % 3 == 0){ sum += lst[i]*lst[i]; } else if (i % 4 == 0){
} else { sum += lst[i]; } } return sum; }
sum += lst[i]*lst[i]*lst[i];
const assert = require('node:assert'); function test() { let candidate = sum_squares; assert.deepEqual(candidate([1, 2, 3]),6); assert.deepEqual(candidate([1, 4, 9]),14); assert.deepEqual(candidate([]),0); assert.deepEqual(candidate([1, 1, 1, 1, 1, 1, 1, 1, 1]),9); assert.deepEqual(candidate([-1, -1, -1, -1, -1, -1, -1, -1, -1]),-3); assert.deepEqual(candidate([0]),0); assert.deepEqual(candidate([-1, -5, 2, -1, -5]),-126); assert.deepEqual(candidate([-56, -99, 1, 0, -2]),3030); assert.deepEqual(candidate([-1, 0, 0, 0, 0, 0, 0, 0, -1]),0); assert.deepEqual(candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]),-14196); assert.deepEqual(candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]),-1448); } test();
humaneval-HumanEval_117_select_words.json-L22
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'
result = [] for word in words: count = 0 for char in word: if char.lower() in CONSONANTS: count += 1 if count == n: result.append(word) return result
words = s.split()
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_1_separate_paren_groups.json-L22
py
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ paren_string = paren_string.replace(' ', '') groups = [] group = '' open_count = 0 for c in paren_string: if c == '(': open_count += 1 elif c == ')': open_count -= 1 group += c if open_count == 0:
group = '' return groups
groups.append(group)
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())'] assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))'] assert candidate('(()(())((())))') == ['(()(())((())))'] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())'] def test_check(): check(separate_paren_groups) test_check()
humaneval-HumanEval_69_search.json-L19
py
from typing import List def search(lst: List[int]) -> int: """ You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: >>> search([4, 1, 2, 2, 3, 1]) 2 >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) 3 >>> search([5, 5, 4, 4, 4]) -1 """ dic = dict() for i in lst:
dic[i] += 1 else: dic[i] = 1 maxValue = -1 for key, value in dic.items(): if value >= key and key > maxValue: maxValue = key return maxValue
if i in dic:
def check(candidate): assert candidate([5, 5, 5, 5, 1]) == 1 assert candidate([4, 1, 4, 1, 4, 4]) == 4 assert candidate([3, 3]) == -1 assert candidate([8, 8, 8, 8, 8, 8, 8, 8]) == 8 assert candidate([2, 3, 3, 2, 2]) == 2 assert candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]) == 1 assert candidate([3, 2, 8, 2]) == 2 assert candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1 assert candidate([8, 8, 3, 6, 5, 6, 4]) == -1 assert candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]) == 1 assert candidate([1, 9, 10, 1, 3]) == 1 assert candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]) == 5 assert candidate([1]) == 1 assert candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]) == 4 assert candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]) == 2 assert candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1 assert candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]) == 4 assert candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]) == 4 assert candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]) == 2 assert candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]) == -1 assert candidate([10]) == -1 assert candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2 assert candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1 assert candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]) == 1 assert candidate([3, 10, 10, 9, 2]) == -1 def test_check(): check(search) test_check()
humaneval-HumanEval_43_pairs_sum_to_zero.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 { // 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_48_is_palindrome.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 { // Checks if given string is a palindrome // >>> isPalindrome(("")) // (true) // >>> isPalindrome(("aba")) // (true) // >>> isPalindrome(("aaaaa")) // (true) // >>> isPalindrome(("zbcd")) // (false) public static boolean isPalindrome(String text) { boolean isPalindrome = true; int left = 0; int right = text.length() - 1; while (left < right) { if (text.charAt(left) != text.charAt(right)) { isPalindrome = false; break;
left++; right--; } return isPalindrome; } }
}
} public static void main(String[] args) { assert(isPalindrome(("")) == (true)); assert(isPalindrome(("aba")) == (true)); assert(isPalindrome(("aaaaa")) == (true)); assert(isPalindrome(("zbcd")) == (false)); assert(isPalindrome(("xywyx")) == (true)); assert(isPalindrome(("xywyz")) == (false)); assert(isPalindrome(("xywzx")) == (false)); } }
humaneval-HumanEval_55_fib.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return n-th Fibonacci number. // >>> fib((10l)) // (55l) // >>> fib((1l)) // (1l) // >>> fib((8l)) // (21l) public static long fib(long n) { if (n == 0) { return 0l; } else if (n == 1) { return 1l; }
return Problem.fib((n - 1)) + Problem.fib((n - 2)); } } }
else {
} public static void main(String[] args) { assert(fib((10l)) == (55l)); assert(fib((1l)) == (1l)); assert(fib((8l)) == (21l)); assert(fib((11l)) == (89l)); assert(fib((12l)) == (144l)); } }
humaneval-HumanEval_128_prod_signs.json-L19
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; }
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; } }
else{
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_137_compare_one.json-L60
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a
return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
elif float(a_tmp) < 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_158_find_max.json-L15
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){
var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
var unique_word = {};
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();