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_70_strange_sort_list.json-L21
js
//Given array of integers, return array in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strange_sort_list([1, 2, 3, 4]) // [1, 4, 2, 3] // >>> strange_sort_list([5, 5, 5, 5]) // [5, 5, 5, 5] // >>> strange_sort_list([]) // [] function strange_sort_list(lst){ if(lst.length === 0){ return []; } var output = []; var tmp = lst.slice(); for(var i = 0; i < lst.length; i++){ if(i % 2 === 0){ output.push(Math.min.apply(null, tmp)); }
output.push(Math.max.apply(null, tmp)); } tmp.splice(tmp.indexOf(output[i]), 1); } return output; }
else{
const assert = require('node:assert'); function test() { let candidate = strange_sort_list; assert.deepEqual(candidate([1, 2, 3, 4]),[1, 4, 2, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9]),[5, 9, 6, 8, 7]); assert.deepEqual(candidate([1, 2, 3, 4, 5]),[1, 5, 2, 4, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9, 1]),[1, 9, 5, 8, 6, 7]); assert.deepEqual(candidate([5, 5, 5, 5]),[5, 5, 5, 5]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7, 8]),[1, 8, 2, 7, 3, 6, 4, 5]); assert.deepEqual(candidate([0, 2, 2, 2, 5, 5, -5, -5]),[-5, 5, -5, 5, 0, 2, 2, 2]); assert.deepEqual(candidate([111111]),[111111]); } test();
humaneval-HumanEval_16_count_distinct_characters.json-L9
py
def count_distinct_characters(string: str) -> int: """ Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ assert isinstance(string, str)
for l in string: s.add(l.lower()) return len(s)
s = set()
def check(candidate): assert candidate('') == 0 assert candidate('abcde') == 5 assert candidate('abcdecadeCADE') == 5 assert candidate('aaaaAAAAaaaa') == 1 assert candidate('Jerry jERRY JeRRRY') == 5 def test_check(): check(count_distinct_characters) test_check()
humaneval-HumanEval_108_count_nums.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 { // Write a function count_nums which takes an array array list of integers and returns // the number of elements which has a sum of digits > 0. // If a number is negative, then its first signed digit will be negative: // e.g. -123 has signed digits -1, 2, and 3. // >>> countNums((new ArrayList<Long>(Arrays.asList()))) // (0l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)11l, (long)-11l)))) // (1l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l)))) // (3l) public static long countNums(ArrayList<Long> arr) { long result = 0l; for (long i : arr) { String str = String.valueOf(i); int sum = 0; if (str.startsWith("-")) { sum = sum - (int) Character.getNumericValue(str.charAt(1)); for (int j = 2; j < str.length(); j++) {
} } else { for (int j = 0; j < str.length(); j++) { sum = sum + (int) Character.getNumericValue(str.charAt(j)); } } if (sum > 0) { result++; } } return result; } }
sum = sum + (int) Character.getNumericValue(str.charAt(j));
} public static void main(String[] args) { assert(countNums((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)0l)))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l, (long)-2l, (long)3l, (long)4l, (long)5l)))) == (6l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)6l, (long)9l, (long)-6l, (long)0l, (long)1l, (long)5l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)100l, (long)98l, (long)-7l, (long)1l, (long)-1l)))) == (4l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)12l, (long)23l, (long)34l, (long)-45l, (long)-56l, (long)0l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l)))) == (1l)); } }
humaneval-HumanEval_135_can_arrange.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 { // 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; for (int i = arr.size() - 1; i > 0; i--) { if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break; }
return p; } }
}
} 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_33_sort_third.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) {
} else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) { min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j)); j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
l_e.add(l.get(i));
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_155_even_odd_count.json-L11
js
//Given an integer. return an array that has the number of even and odd digits respectively. // Example: // >>> even_odd_count(-12) // [1, 1] // >>> even_odd_count(123) // [1, 2] function even_odd_count(num){ num = Math.abs(num); var evens = 0; var odds = 0;
if(num.toString()[i] % 2 == 0){ evens ++; } else{ odds ++; } } return [evens, odds]; }
for(var i = 0; i < num.toString().length; i++){
const assert = require('node:assert'); function test() { let candidate = even_odd_count; assert.deepEqual(candidate(7),[0, 1]); assert.deepEqual(candidate(-78),[1, 1]); assert.deepEqual(candidate(3452),[2, 2]); assert.deepEqual(candidate(346211),[3, 3]); assert.deepEqual(candidate(-345821),[3, 3]); assert.deepEqual(candidate(-2),[1, 0]); assert.deepEqual(candidate(-45347),[2, 3]); assert.deepEqual(candidate(0),[1, 0]); } test();
humaneval-HumanEval_64_vowels_count.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function vowels_count which takes a string representing // a word as input and returns the number of vowels in the string. // Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a // vowel, but only when it is at the end of the given word. // Example: // >>> vowelsCount(("abcde")) // (2l) // >>> vowelsCount(("ACEDY")) // (3l) public static long vowelsCount(String s) { long sum = 0; String sUpper = s.toUpperCase(); int lastIndex = sUpper.length() - 1; for (int i = 0; i < sUpper.length(); i++) { if (sUpper.charAt(i) == 'A' || sUpper.charAt(i) == 'E' || sUpper.charAt(i) == 'I' || sUpper.charAt(i) == 'O' || sUpper.charAt(i) == 'U') { sum++; } if (sUpper.charAt(i) == 'Y' && i == lastIndex) { sum++;
} return sum; } }
}
} public static void main(String[] args) { assert(vowelsCount(("abcde")) == (2l)); assert(vowelsCount(("Alone")) == (3l)); assert(vowelsCount(("key")) == (2l)); assert(vowelsCount(("bye")) == (1l)); assert(vowelsCount(("keY")) == (2l)); assert(vowelsCount(("bYe")) == (1l)); assert(vowelsCount(("ACEDY")) == (3l)); } }
humaneval-HumanEval_86_anti_shuffle.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that takes a string and returns an ordered version of it. // Ordered version of string, is a string where all words (separated by space) // are replaced by a new word where all the characters arranged in // ascending order based on ascii value. // Note: You should keep the order of words and blank spaces in the sentence. // For example: // >>> antiShuffle(("Hi")) // ("Hi") // >>> antiShuffle(("hello")) // ("ehllo") // >>> antiShuffle(("Hello World!!!")) // ("Hello !!!Wdlor") public static String antiShuffle(String s) { StringBuilder sb = new StringBuilder();
for (String word : words) { char[] chars = word.toCharArray(); Arrays.sort(chars); sb.append(new String(chars)); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
String[] words = s.split(" ");
} public static void main(String[] args) { assert(antiShuffle(("Hi")).equals(("Hi"))); assert(antiShuffle(("hello")).equals(("ehllo"))); assert(antiShuffle(("number")).equals(("bemnru"))); assert(antiShuffle(("abcd")).equals(("abcd"))); assert(antiShuffle(("Hello World!!!")).equals(("Hello !!!Wdlor"))); assert(antiShuffle(("")).equals((""))); assert(antiShuffle(("Hi. My name is Mister Robot. How are you?")).equals((".Hi My aemn is Meirst .Rboot How aer ?ouy"))); } }
humaneval-HumanEval_40_triples_sum_to_zero.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) {
} ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList); for (int i = 0; i < sortedList.size() - 2; i++) { int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) { j++; } else { k--; } } } return false; } }
return false;
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_146_specialFilter.json-L19
js
//Write a function that takes an array of numbers as input and returns // the number of elements in the array that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter([15, -73, 14, -15]) // 1 // >>> specialFilter([33, -2, -3, 45, 21, 109]) // 2 function specialFilter(nums){ let count = 0; for(let i = 0; i < nums.length; i++){ let num = nums[i]; let firstDigit = nums[i].toString()[0]; let lastDigit = nums[i].toString()[nums[i].toString().length - 1]; if(num > 10 && firstDigit % 2 !== 0 && lastDigit % 2 !== 0){ count++; } }
}
return count;
const assert = require('node:assert'); function test() { let candidate = specialFilter; assert.deepEqual(candidate([5, -2, 1, -5]),0); assert.deepEqual(candidate([15, -73, 14, -15]),1); assert.deepEqual(candidate([33, -2, -3, 45, 21, 109]),2); assert.deepEqual(candidate([43, -12, 93, 125, 121, 109]),4); assert.deepEqual(candidate([71, -2, -33, 75, 21, 19]),3); assert.deepEqual(candidate([1]),0); assert.deepEqual(candidate([]),0); } test();
humaneval-HumanEval_117_select_words.json-L44
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } }
ret.add(word); } } return ret; } }
if (consonants == n) {
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_55_fib.json-L14
py
def fib(n: int) -> int: """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """ assert n >= 1 f0, f1 = 0, 1 for i in range(n - 1): f0, f1 = f1, f0 + f1
return f1
def check(candidate): assert candidate(10) == 55 assert candidate(1) == 1 assert candidate(8) == 21 assert candidate(11) == 89 assert candidate(12) == 144 def test_check(): check(fib) test_check()
humaneval-HumanEval_117_select_words.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 a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break;
consonants++; break; } } if (consonants == n) { ret.add(word); } } return ret; } }
default:
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_84_solve.json-L19
js
//Given a positive integer N, return the total sum of its digits in binary. // Example // >>> solve(1000) // "1" // >>> solve(150) // "110" // >>> solve(147) // "1100" // Variables: // @N integer // Constraints: 0 ≤ N ≤ 10000. // Output: // a string of binary number function solve(N){ let newN = N.toString(); let total = 0; for(let i = 0; i < newN.length; i++){ let digit = newN[i];
} return total.toString(2); }
total += parseInt(digit);
const assert = require('node:assert'); function test() { let candidate = solve; assert.deepEqual(candidate(1000),"1"); assert.deepEqual(candidate(150),"110"); assert.deepEqual(candidate(147),"1100"); assert.deepEqual(candidate(333),"1001"); assert.deepEqual(candidate(963),"10010"); } test();
humaneval-HumanEval_21_rescale_to_unit.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 { // Given array list of numbers (of at least two elements), apply a linear transform to that array list, // such that the smallest number will become 0 and the largest will become 1 // >>> rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f)))) // (new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.25f, (float)0.5f, (float)0.75f, (float)1.0f))) public static ArrayList<Float> rescaleToUnit(ArrayList<Float> numbers) { float min = numbers.stream().min(Float::compare).get();
return numbers.stream().map(e -> (e - min) / (max - min)).collect(Collectors.toCollection(ArrayList::new)); } }
float max = numbers.stream().max(Float::compare).get();
} public static void main(String[] args) { assert(rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)2.0f, (float)49.9f)))).equals((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)1.0f))))); assert(rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)100.0f, (float)49.9f)))).equals((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.0f))))); assert(rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)2.0f, (float)3.0f, (float)4.0f, (float)5.0f)))).equals((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.25f, (float)0.5f, (float)0.75f, (float)1.0f))))); assert(rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)2.0f, (float)1.0f, (float)5.0f, (float)3.0f, (float)4.0f)))).equals((new ArrayList<Float>(Arrays.asList((float)0.25f, (float)0.0f, (float)1.0f, (float)0.5f, (float)0.75f))))); assert(rescaleToUnit((new ArrayList<Float>(Arrays.asList((float)12.0f, (float)11.0f, (float)15.0f, (float)13.0f, (float)14.0f)))).equals((new ArrayList<Float>(Arrays.asList((float)0.25f, (float)0.0f, (float)1.0f, (float)0.5f, (float)0.75f))))); } }
humaneval-HumanEval_4_mean_absolute_deviation.json-L10
js
//For a given array of input numbers, calculate Mean Absolute Deviation // around the mean of this dataset. // Mean Absolute Deviation is the average absolute difference between each // element and a centerpoint (mean in this case): // MAD = average | x - x_mean | // >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) // 1.0 function mean_absolute_deviation(numbers){ var sum = 0;
sum += numbers[i]; } var mean = sum / numbers.length; var sum_abs_diff = 0; for(var i = 0; i < numbers.length; i++){ sum_abs_diff += Math.abs(numbers[i] - mean); } return sum_abs_diff / numbers.length; }
for(var i = 0; i < numbers.length; i++){
const assert = require('node:assert'); function test() { let candidate = mean_absolute_deviation; assert.deepEqual(candidate([1.0, 2.0]),0.5); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0]),1.0); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0]),1.2); } test();
humaneval-HumanEval_106_f.json-L18
py
from typing import List def f(n: int) -> List[int]: """ Implement the function f that takes n as a parameter, and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: >>> f(5) [1, 2, 6, 24, 15] """ import math a=[] for i in range(n): i=i+1 if i%2==0:
else: a.append(sum(range(1,i+1))) return a pass
a.append(math.factorial(i))
def check(candidate): assert candidate(5) == [1, 2, 6, 24, 15] assert candidate(7) == [1, 2, 6, 24, 15, 720, 28] assert candidate(1) == [1] assert candidate(3) == [1, 2, 6] def test_check(): check(f) test_check()
humaneval-HumanEval_102_choose_num.json-L13
js
//This function takes two positive numbers x and y and returns the // biggest even integer number that is in the range [x, y] inclusive. If // there's no such number, then the function should return -1. // For example: // >>> choose_num(12, 15) // 14 // >>> choose_num(13, 12) // -1 function choose_num(x, y){ var num = -1; for(var i = x; i <= y; i++){ if(i % 2 == 0){
} } return num; }
num = i;
const assert = require('node:assert'); function test() { let candidate = choose_num; assert.deepEqual(candidate(12, 15),14); assert.deepEqual(candidate(13, 12),-1); assert.deepEqual(candidate(33, 12354),12354); assert.deepEqual(candidate(5234, 5233),-1); assert.deepEqual(candidate(6, 29),28); assert.deepEqual(candidate(27, 10),-1); assert.deepEqual(candidate(7, 7),-1); assert.deepEqual(candidate(546, 546),546); } test();
humaneval-HumanEval_143_words_in_sentence.json-L27
js
//You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> words_in_sentence("This is a test") // "is" // Example 2: // >>> words_in_sentence("lets go for swimming") // "go for" // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters function words_in_sentence(sentence){ return sentence.split(' ').filter(word => { var number = word.length; var isPrime = true; if(number === 1 || number === 0){ return false; } for(var i = 2; i < number; i++){ if(number % i === 0){ isPrime = false; break; }
return isPrime; }).join(' '); }
}
const assert = require('node:assert'); function test() { let candidate = words_in_sentence; assert.deepEqual(candidate("This is a test"),"is"); assert.deepEqual(candidate("lets go for swimming"),"go for"); assert.deepEqual(candidate("there is no place available here"),"there is no place"); assert.deepEqual(candidate("Hi I am Hussein"),"Hi am Hussein"); assert.deepEqual(candidate("go for it"),"go for it"); assert.deepEqual(candidate("here"),""); assert.deepEqual(candidate("here is"),"is"); } test();
humaneval-HumanEval_149_sorted_list_sum.json-L43
js
//Write a function that accepts an array of strings as a parameter, // deletes the strings that have odd lengths from it, // and returns the resulted array with a sorted order, // The array is always an array of strings and never an array of numbers, // and it may contain duplicates. // The order of the array should be ascending by length of each word, and you // should return the array sorted by that rule. // If two words have the same length, sort the array alphabetically. // The function should return an array of strings in sorted order. // You may assume that all words will have the same length. // For example: // >>> list_sort(["aa", "a", "aaa"]) // ["aa"] // >>> list_sort(["ab", "a", "aaa", "cd"]) // ["ab", "cd"] function sorted_list_sum(lst){ var result = []; for(var i = 0; i < lst.length; i++){ if(lst[i].length % 2 == 0){ result.push(lst[i]); } } return result.sort(function(a, b){ if(a.length < b.length){ return -1; } else if(a.length > b.length){ return 1; } else{ if(a < b){ return -1; } else if(a > b){ return 1; } else{ return 0; } } }); }
var b = ["ab", "a", "aaa", "cd"];
var a = ["aa", "a", "aaa"];
const assert = require('node:assert'); function test() { let candidate = sorted_list_sum; assert.deepEqual(candidate(["aa", "a", "aaa"]),["aa"]); assert.deepEqual(candidate(["school", "AI", "asdf", "b"]),["AI", "asdf", "school"]); assert.deepEqual(candidate(["d", "b", "c", "a"]),[]); assert.deepEqual(candidate(["d", "dcba", "abcd", "a"]),["abcd", "dcba"]); assert.deepEqual(candidate(["AI", "ai", "au"]),["AI", "ai", "au"]); assert.deepEqual(candidate(["a", "b", "b", "c", "c", "a"]),[]); assert.deepEqual(candidate(["aaaa", "bbbb", "dd", "cc"]),["cc", "dd", "aaaa", "bbbb"]); } test();
humaneval-HumanEval_9_rolling_max.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 { // From a given array list of integers, generate an array array list of rolling maximum element found until given moment // in the sequence. // >>> rollingMax((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)3l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l, (long)4l))) public static ArrayList<Long> rollingMax(ArrayList<Long> numbers) { ArrayList<Long> results = new ArrayList<Long>(); for (int i = 0; i < numbers.size(); i++) { results.add(numbers.subList(0, i + 1).stream().max(Long::compare).get()); } return results; }
}
} public static void main(String[] args) { assert(rollingMax((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l, (long)100l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)100l, (long)100l))))); } }
humaneval-HumanEval_59_largest_prime_factor.json-L17
js
//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 function largest_prime_factor(n){ var result = 2; while(n > result){ if(n % result == 0){ n = n / result; } else{ result = result + 1; } } return result;
}
const assert = require('node:assert'); function test() { let candidate = largest_prime_factor; assert.deepEqual(candidate(15),5); assert.deepEqual(candidate(27),3); assert.deepEqual(candidate(63),7); assert.deepEqual(candidate(330),11); assert.deepEqual(candidate(13195),29); } test();
humaneval-HumanEval_139_special_factorial.json-L29
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // For example: // >>> specialFactorial((4l)) // (288l) // The function will receive an integer as input and should return the special // factorial of this integer. public static long specialFactorial(long n) { long result = 1; while (n > 0) { long local_result = 1; long temp = n; while (temp > 0) { local_result *= temp; temp--; } result *= local_result; n--; }
} }
return result;
} public static void main(String[] args) { assert(specialFactorial((4l)) == (288l)); assert(specialFactorial((5l)) == (34560l)); assert(specialFactorial((7l)) == (125411328000l)); assert(specialFactorial((1l)) == (1l)); } }
humaneval-HumanEval_160_do_algebra.json-L43
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);
count = 0; do_again = true; break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break; case '-': answer -= operand[0]; break; } operand.splice(0, 1); operator.splice(0, 1); } return answer; }
operator.splice(count, 1);
const assert = require('node:assert'); function test() { let candidate = do_algebra; assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37); assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9); assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8); } test();
humaneval-HumanEval_1_separate_paren_groups.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 { // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } }
return output; } }
}
} 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_95_check_dict_case.json-L47
js
//Given an object, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; } } else if (case_type == 1){ if (key != key.toUpperCase()){ return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } } else{ return false; }
return true; }
}
const assert = require('node:assert'); function test() { let candidate = check_dict_case; assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true); assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false); assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false); assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false); assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true); assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true); assert.deepEqual(candidate({}),false); } test();
humaneval-HumanEval_98_count_upper.json-L15
js
//Given a string s, count the number of uppercase vowels in even indices. // For example: // >>> count_upper("aBCdEf") // 1 // >>> count_upper("abcdefg") // 0 // >>> count_upper("dBBE") // 0 function count_upper(s){ var index; var result = 0; var vowel = ['A', 'E', 'I', 'O', 'U']; for (index = 0; index < s.length; index += 2){ if (vowel.indexOf(s[index]) > -1){
} } return result; }
result += 1;
const assert = require('node:assert'); function test() { let candidate = count_upper; assert.deepEqual(candidate("aBCdEf"),1); assert.deepEqual(candidate("abcdefg"),0); assert.deepEqual(candidate("dBBE"),0); assert.deepEqual(candidate("B"),0); assert.deepEqual(candidate("U"),1); assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("EEEE"),2); } test();
humaneval-HumanEval_111_histogram.json-L23
js
//Given a string representing a space separated lowercase letters, return an object // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram("a b c") // {"a": 1, "b": 1, "c": 1} // >>> histogram("a b b a") // {"a": 2, "b": 2} // >>> histogram("a b c a b") // {"a": 2, "b": 2} // >>> histogram("b b b b a") // {"b": 4} // >>> histogram("") // {} function histogram(test){ if (test.length === 0){ return {}; } var lst = test.split(" "); var count = {}; for (var i = 0; i < lst.length; i++){ if (count[lst[i]]){
} else{ count[lst[i]] = 1; } } console.log(count); var max = 0; var result = {}; for (var key in count){ if (count[key] > max){ max = count[key]; result = {}; result[key] = max; } else if (count[key] === max){ result[key] = max; } } return result; }
count[lst[i]] += 1;
const assert = require('node:assert'); function test() { let candidate = histogram; assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate("b b b b a"),{"b": 4}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate(""),{}); assert.deepEqual(candidate("a"),{"a": 1}); } test();
humaneval-HumanEval_6_parse_nested_parens.json-L8
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0;
var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){ level += 1; if (level > maxlevel){ maxlevel = level; } } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
var maxlevel = 0;
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_129_minPath.json-L38
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
path = [min_val] while len(path) < k: min_val = float('inf') for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path.append(min_val) return path
col = 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_17_parse_music.json-L23
js
//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 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] function parse_music(music_string){ let songs = music_string.split(' '); let song = []; songs.forEach(s => { if(s === 'o'){ song.push(4); }else if(s === 'o|'){ song.push(2); }else if(s === '.|'){ song.push(1); } }); return song;
}
const assert = require('node:assert'); function test() { let candidate = parse_music; assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("o o o o"),[4, 4, 4, 4]); assert.deepEqual(candidate(".| .| .| .|"),[1, 1, 1, 1]); assert.deepEqual(candidate("o| o| .| .| o o o o"),[2, 2, 1, 1, 4, 4, 4, 4]); assert.deepEqual(candidate("o| .| o| .| o o| o o|"),[2, 1, 2, 1, 4, 2, 4, 2]); } test();
humaneval-HumanEval_114_minSubArraySum.json-L10
js
//Given an array of integers nums, find the minimum sum of any non-empty sub-array // of nums. // Example // >>> minSubArraySum([2, 3, 4, 1, 2, 4]) // 1 // >>> minSubArraySum([-1, -2, -3]) // -6 function minSubArraySum(nums){ let sum = 0;
for(let i = 0; i < nums.length; i++){ sum += nums[i]; if(sum < minSum){ minSum = sum; } if(sum > 0){ sum = 0; } } return minSum; }
let minSum = nums[0];
const assert = require('node:assert'); function test() { let candidate = minSubArraySum; assert.deepEqual(candidate([2, 3, 4, 1, 2, 4]),1); assert.deepEqual(candidate([-1, -2, -3]),-6); assert.deepEqual(candidate([-1, -2, -3, 2, -10]),-14); assert.deepEqual(candidate([-9999999999999999]),-9999999999999999); assert.deepEqual(candidate([0, 10, 20, 1000000]),0); assert.deepEqual(candidate([-1, -2, -3, 10, -5]),-6); assert.deepEqual(candidate([100, -1, -2, -3, 10, -5]),-6); assert.deepEqual(candidate([10, 11, 13, 8, 3, 4]),3); assert.deepEqual(candidate([100, -33, 32, -1, 0, -2]),-33); assert.deepEqual(candidate([-10]),-10); assert.deepEqual(candidate([7]),7); assert.deepEqual(candidate([1, -1]),-1); } test();
humaneval-HumanEval_6_parse_nested_parens.json-L16
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0; var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){ level += 1; if (level > maxlevel){ maxlevel = level; }
else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
}
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_70_strange_sort_list.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 array list of integers, return array list in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) { if (lst.size() <= 1) { return lst;
ArrayList<Long> result = new ArrayList<Long>(); ArrayList<Long> sorted = new ArrayList<Long>(lst); Collections.sort(sorted); int min = 0; int max = sorted.size() - 1; while (min <= max) { result.add(sorted.get(min)); min++; if (min <= max) { result.add(sorted.get(max)); max--; } } return result; } }
}
} public static void main(String[] args) { assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l))))); } }
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L18
js
//Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // Examples: // >>> check_if_last_char_is_a_letter("apple pie") // false // >>> check_if_last_char_is_a_letter("apple pi e") // true // >>> check_if_last_char_is_a_letter("apple pi e ") // false // >>> check_if_last_char_is_a_letter("") // false function check_if_last_char_is_a_letter(txt){ var result=txt.split(" "); if(result[result.length-1].length==1 && result[result.length-1].match(/[a-z]/i)){ return true;
return false; }
}
const assert = require('node:assert'); function test() { let candidate = check_if_last_char_is_a_letter; assert.deepEqual(candidate("apple"),false); assert.deepEqual(candidate("apple pi e"),true); assert.deepEqual(candidate("eeeee"),false); assert.deepEqual(candidate("A"),true); assert.deepEqual(candidate("Pumpkin pie "),false); assert.deepEqual(candidate("Pumpkin pie 1"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("eeeee e "),false); assert.deepEqual(candidate("apple pie"),false); assert.deepEqual(candidate("apple pi e "),false); } test();
humaneval-HumanEval_123_get_odd_collatz.json-L31
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){
} } if(odd_count != 0){ odd_numbers.sort(function(a, b){return a-b}) return odd_numbers } else{ odd_numbers.push(1) return odd_numbers } }
break
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_79_decimal_to_binary.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 will be given a number in decimal form and your task is to convert it to // binary format. The function should return a string, with each character representing a binary // number. Each character in the string will be '0' or '1'. // There will be an extra couple of characters 'db' at the beginning and at the end of the string. // The extra characters are there to help with the format. // Examples: // >>> decimalToBinary((15l)) // ("db1111db") // >>> decimalToBinary((32l)) // ("db100000db") public static String decimalToBinary(long decimal) {
} }
return "db" + Long.toBinaryString(decimal) + "db";
} public static void main(String[] args) { assert(decimalToBinary((0l)).equals(("db0db"))); assert(decimalToBinary((32l)).equals(("db100000db"))); assert(decimalToBinary((103l)).equals(("db1100111db"))); assert(decimalToBinary((15l)).equals(("db1111db"))); } }
humaneval-HumanEval_160_do_algebra.json-L45
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;
break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break; case '-': answer -= operand[0]; break; } operand.splice(0, 1); operator.splice(0, 1); } return answer; }
do_again = true;
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_12_longest.json-L17
js
//Out of array of strings, return the longest one. Return the first one in case of multiple // strings of the same length. Return undefined in case the input array is empty. // >>> longest([]) // undefined // >>> longest(["a", "b", "c"]) // "a" // >>> longest(["a", "bb", "ccc"]) // "ccc" function longest(strings){ var result; if (strings.length === 0) { return undefined; } for (var i = 0; i < strings.length; i++) { if (!result || strings[i].length > result.length) { result = strings[i];
} return result; }
}
const assert = require('node:assert'); function test() { let candidate = longest; assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate(["x", "y", "z"]),"x"); assert.deepEqual(candidate(["x", "yyy", "zzzz", "www", "kkkk", "abc"]),"zzzz"); } test();
humaneval-HumanEval_58_common.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 { // Return sorted unique common elements for two array lists. // >>> common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l))) // >>> common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))) public static ArrayList<Long> common(ArrayList<Long> l1, ArrayList<Long> l2) { return new ArrayList<Long>( l1.stream() .filter(l2::contains) .collect(Collectors.toSet())
} }
);
} public static void main(String[] args) { assert(common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l))))); assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_136_largest_smallest_integers.json-L18
py
from typing import List, Tuple, Optional def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]: """ Create a function that returns a tuple (a, b), where 'a' is the largest of negative integers, and 'b' is the smallest of positive integers in a list. If there is no negative or positive integers, return them as None. Examples: >>> largest_smallest_integers([2, 4, 1, 3, 5, 7]) (None, 1) >>> largest_smallest_integers([]) (None, None) >>> largest_smallest_integers([0]) (None, None) """
largest_negative = None for num in lst: if num > 0: if smallest_positive is None or num < smallest_positive: smallest_positive = num elif num < 0: if largest_negative is None or num > largest_negative: largest_negative = num return (largest_negative, smallest_positive)
smallest_positive = None
def check(candidate): assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1) assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1) assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1) assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2) assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2) assert candidate([]) == (None, None) assert candidate([0]) == (None, None) assert candidate([-1, -3, -5, -6]) == (-1, None) assert candidate([-1, -3, -5, -6, 0]) == (-1, None) assert candidate([-6, -4, -4, -3, 1]) == (-3, 1) assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1) def test_check(): check(largest_smallest_integers) test_check()
humaneval-HumanEval_49_modp.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 2^n modulo p (be aware of numerics). // >>> modp((3l), (5l)) // (3l) // >>> modp((1101l), (101l)) // (2l) // >>> modp((0l), (101l)) // (1l) // >>> modp((3l), (11l)) // (8l) // >>> modp((100l), (101l)) // (1l) public static long modp(long n, long p) { if (n == 0) return 1; long sqrt = modp(n / 2, p);
if (n % 2 == 0) { return sqrt; } return (sqrt * 2) % p; } }
sqrt = (sqrt * sqrt) % p;
} public static void main(String[] args) { assert(modp((3l), (5l)) == (3l)); assert(modp((1101l), (101l)) == (2l)); assert(modp((0l), (101l)) == (1l)); assert(modp((3l), (11l)) == (8l)); assert(modp((100l), (101l)) == (1l)); assert(modp((30l), (5l)) == (4l)); assert(modp((31l), (5l)) == (3l)); } }
humaneval-HumanEval_124_valid_date.json-L27
py
def valid_date(date: str) -> bool: """You have to write a function which validates a given date string and returns True if the date is valid otherwise False. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy >>> valid_date('03-11-2000') True >>> valid_date('15-01-2012') False >>> valid_date('04-0-2040') False >>> valid_date('06-04-2020') True >>> valid_date('06/04/2020') False """ if not date: return False
date_list = [int(d) for d in date.split('-')] if len(date_list) != 3: return False if date_list[0] < 1 or date_list[0] > 12: return False if date_list[1] < 1 or date_list[1] > days_per_month[date_list[0] - 1]: return False if len(str(date_list[2])) != 4: return False return True
days_per_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def check(candidate): assert candidate('03-11-2000') == True assert candidate('15-01-2012') == False assert candidate('04-0-2040') == False assert candidate('06-04-2020') == True assert candidate('01-01-2007') == True assert candidate('03-32-2011') == False assert candidate('') == False assert candidate('04-31-3000') == False assert candidate('06-06-2005') == True assert candidate('21-31-2000') == False assert candidate('04-12-2003') == True assert candidate('04122003') == False assert candidate('20030412') == False assert candidate('2003-04') == False assert candidate('2003-04-12') == False assert candidate('04-2003') == False def test_check(): check(valid_date) test_check()
humaneval-HumanEval_111_histogram.json-L22
py
from typing import Dict def histogram(test: str) -> Dict[str, int]: """Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: >>> histogram('a b c') { 'a': 1, 'b': 1, 'c': 1 } >>> histogram('a b b a') { 'a': 2, 'b': 2 } >>> histogram('a b c a b') { 'a': 2, 'b': 2 } >>> histogram('b b b b a') { 'b': 4 } >>> histogram('') { } """ letters = {}
result = {} for letter in test.split(): letters[letter] = letters.get(letter, 0) + 1 if letters[letter] >= most_count: most_count = letters[letter] for letter in letters: if letters[letter] == most_count: result[letter] = most_count return result
most_count = 0
def check(candidate): assert candidate('a b b a') == { 'a': 2, 'b': 2 } assert candidate('a b c a b') == { 'a': 2, 'b': 2 } assert candidate('a b c d g') == { 'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('b b b b a') == { 'b': 4 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('') == { } assert candidate('a') == { 'a': 1 } def test_check(): check(histogram) test_check()
humaneval-HumanEval_117_select_words.json-L31
py
from typing import List def select_words(s: str, n: int) -> List[str]: """Given a string s and a natural number n, you have been tasked to implement a function that returns a list of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty list. Note: you may assume the input string contains only letters and spaces. Examples: >>> select_words('Mary had a little lamb', 4) ['little'] >>> select_words('Mary had a little lamb', 3) ['Mary', 'lamb'] >>> select_words('simple white space', 2) [] >>> select_words('Hello world', 4) ['world'] >>> select_words('Uncle sam', 3) ['Uncle'] """ CONSONANTS = 'bcdfghjklmnpqrstvwxyz' words = s.split() result = [] for word in words: count = 0 for char in word: if char.lower() in CONSONANTS: count += 1 if count == n: result.append(word)
return result
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_42_incr_list.json-L7
js
//Return array with elements incremented by 1. // >>> incr_list([1, 2, 3]) // [2, 3, 4] // >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) // [6, 4, 6, 3, 4, 4, 10, 1, 124] function incr_list(l){
for(var i = 0; i < l.length; i++){ new_list.push(l[i] + 1); } return new_list; }
var new_list = [];
const assert = require('node:assert'); function test() { let candidate = incr_list; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([3, 2, 1]),[4, 3, 2]); assert.deepEqual(candidate([5, 2, 5, 2, 3, 3, 9, 0, 123]),[6, 3, 6, 3, 4, 4, 10, 1, 124]); } test();
humaneval-HumanEval_133_sum_squares.json-L24
py
from typing import List def sum_squares(lst: List[float]) -> int: """You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to the upper int(Ceiling) first. Examples: >>> lst([1.0, 2.0, 3.0]) 14 >>> lst([1.0, 4.0, 9.0]) 98 >>> lst([1.0, 3.0, 5.0, 7.0]) 84 >>> lst([1.4, 4.2, 0.0]) 29 >>> lst([-2.4, 1.0, 1.0]) 6 """ import math for i in range(len(lst)): lst[i] = math.ceil(lst[i])
for i in lst: total += i**2 return total
total = 0
def check(candidate): assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 3.0, 5.0, 7.0]) == 84 assert candidate([1.4, 4.2, 0.0]) == 29 assert candidate([-2.4, 1.0, 1.0]) == 6 assert candidate([100.0, 1.0, 15.0, 2.0]) == 10230 assert candidate([10000.0, 10000.0]) == 200000000 assert candidate([-1.4, 4.6, 6.3]) == 75 assert candidate([-1.4, 17.9, 18.9, 19.9]) == 1086 assert candidate([0.0]) == 0 assert candidate([-1.0]) == 1 assert candidate([-1.0, 1.0, 0.0]) == 2 def test_check(): check(sum_squares) test_check()
humaneval-HumanEval_54_same_chars.json-L19
js
//Check if two words have the same characters. // >>> same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") // true // >>> same_chars("abcd", "dddddddabc") // true // >>> same_chars("dddddddabc", "abcd") // true // >>> same_chars("eabcd", "dddddddabc") // false // >>> same_chars("abcd", "dddddddabce") // false // >>> same_chars("eabcdzzzz", "dddzzzzzzzddddabc") // false function same_chars(s0, s1){ let res = true; for(let i = 0; i < s0.length; i++){ if(s1.indexOf(s0[i]) === -1){ res = false;
} } for(let i = 0; i < s1.length; i++){ if(s0.indexOf(s1[i]) === -1){ res = false; break; } } return res; }
break;
const assert = require('node:assert'); function test() { let candidate = same_chars; assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddeddabc"),true); assert.deepEqual(candidate("abcd", "dddddddabc"),true); assert.deepEqual(candidate("dddddddabc", "abcd"),true); assert.deepEqual(candidate("eabcd", "dddddddabc"),false); assert.deepEqual(candidate("abcd", "dddddddabcf"),false); assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddddabc"),false); assert.deepEqual(candidate("aabb", "aaccc"),false); } test();
humaneval-HumanEval_42_incr_list.json-L8
js
//Return array with elements incremented by 1. // >>> incr_list([1, 2, 3]) // [2, 3, 4] // >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) // [6, 4, 6, 3, 4, 4, 10, 1, 124] function incr_list(l){ var new_list = [];
new_list.push(l[i] + 1); } return new_list; }
for(var i = 0; i < l.length; i++){
const assert = require('node:assert'); function test() { let candidate = incr_list; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([3, 2, 1]),[4, 3, 2]); assert.deepEqual(candidate([5, 2, 5, 2, 3, 3, 9, 0, 123]),[6, 3, 6, 3, 4, 4, 10, 1, 124]); } test();
humaneval-HumanEval_3_below_zero.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You're given an array array list of deposit and withdrawal operations on a bank account that starts with // zero balance. Your task is to detect if at any point the balance of account fallls below zero, and // at that point function should return true. Otherwise it should return false. // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (false) // >>> belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l)))) // (true) public static boolean belowZero(ArrayList<Long> operations) { long balance = 0; for (long op : operations) { balance += op; if (balance < 0) { return true; } } return false; }
}
} public static void main(String[] args) { assert(belowZero((new ArrayList<Long>(Arrays.asList()))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-3l, (long)1l, (long)2l, (long)-3l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)-4l, (long)5l, (long)6l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (false)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-5l)))) == (true)); assert(belowZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)-2l, (long)2l, (long)-2l, (long)5l, (long)-5l, (long)4l, (long)-4l)))) == (true)); } }
humaneval-HumanEval_160_do_algebra.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given two array lists operator, and operand. The first array list has basic algebra operations, and // the second array list is an array array list of integers. Use the two given array lists to build the algebric // expression and return the evaluation of this expression. // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // Example: // operator['+', '*', '-'] // array array list = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array list is equal to the length of operand array list minus one. // Operand is an array array list of of non-negative integers. // Operator array list has at least one operator, and operand array list has at least two operands. public static long doAlgebra(ArrayList<String> op, ArrayList<Long> operand) {
list.add(operand.get(0)); for (int i = 0; i < op.size(); i++) { if (op.get(i).equals("+")) list.add(operand.get(i + 1)); else if (op.get(i).equals("-")) list.add(-operand.get(i + 1)); else if (op.get(i).equals("*")) list.set(list.size() - 1, list.get(list.size() - 1) * operand.get(i + 1)); else if (op.get(i).equals("//")) list.set(list.size() - 1, list.get(list.size() - 1) / operand.get(i + 1)); else if (op.get(i).equals("**")) list.set(list.size() - 1, (long) Math.pow(list.get(list.size() - 1), operand.get(i + 1))); } return list.stream().mapToLong(x -> x).sum(); } }
ArrayList<Long> list = new ArrayList<>();
} public static void main(String[] args) { assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"**", (String)"*", (String)"+"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (37l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"+", (String)"*", (String)"-"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (9l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"//", (String)"*"))), (new ArrayList<Long>(Arrays.asList((long)7l, (long)3l, (long)4l)))) == (8l)); } }
humaneval-HumanEval_125_split_words.json-L29
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); } else if(txt.includes(',')){ return txt.split(','); } else{ let count = 0; for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){ if(txt[i] == txt[i].toLowerCase()){ count++; } } } return count; }
}
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_88_sort_array.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of 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) {
Collections.sort(array, Collections.reverseOrder()); } else { Collections.sort(array); } } return array; } }
if((array.get(0)+array.get(array.size()-1))%2==0) {
} 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_69_search.json-L31
js
//You are given a non-empty array of positive integers. Return the greatest integer that is greater than // zero, and has a frequency greater than or equal to the value of the integer itself. // The frequency of an integer is the number of times it appears in the array. // If no such a value exist, return -1. // Examples: // >>> search([4, 1, 2, 2, 3, 1]) // 2 // >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) // 3 // >>> search([5, 5, 4, 4, 4]) // -1 function search(lst){ var h = {}; for (var i=0; i<lst.length; i++){ var x = lst[i]; if (x in h){ h[x] += 1; } else{ h[x] = 1; } } var keys = Object.keys(h); var max = 0; for (var i=0; i<keys.length; i++){ if (keys[i] > max && h[keys[i]] >= keys[i]){ max = keys[i]; } } if (max == 0){
} return max; }
return -1;
const assert = require('node:assert'); function test() { let candidate = search; assert.deepEqual(candidate([5, 5, 5, 5, 1]),1); assert.deepEqual(candidate([4, 1, 4, 1, 4, 4]),4); assert.deepEqual(candidate([3, 3]),-1); assert.deepEqual(candidate([8, 8, 8, 8, 8, 8, 8, 8]),8); assert.deepEqual(candidate([2, 3, 3, 2, 2]),2); assert.deepEqual(candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]),1); assert.deepEqual(candidate([3, 2, 8, 2]),2); assert.deepEqual(candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]),1); assert.deepEqual(candidate([8, 8, 3, 6, 5, 6, 4]),-1); assert.deepEqual(candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]),1); assert.deepEqual(candidate([1, 9, 10, 1, 3]),1); assert.deepEqual(candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]),5); assert.deepEqual(candidate([1]),1); assert.deepEqual(candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]),4); assert.deepEqual(candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]),2); assert.deepEqual(candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]),1); assert.deepEqual(candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]),4); assert.deepEqual(candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]),4); assert.deepEqual(candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]),2); assert.deepEqual(candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]),-1); assert.deepEqual(candidate([10]),-1); assert.deepEqual(candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]),2); assert.deepEqual(candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]),1); assert.deepEqual(candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]),1); assert.deepEqual(candidate([3, 10, 10, 9, 2]),-1); } test();
humaneval-HumanEval_117_select_words.json-L18
js
//Given a string s and a natural number n, you have been tasked to implement // a function that returns an array of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> select_words("Mary had a little lamb", 4) // ["little"] // >>> select_words("Mary had a little lamb", 3) // ["Mary", "lamb"] // >>> select_words("simple white space", 2) // [] // >>> select_words("Hello world", 4) // ["world"] // >>> select_words("Uncle sam", 3) // ["Uncle"] function select_words(s, n){
let selected = words.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi) != null); if(n > 0){ return selected.filter(e => e.match(/[bcdfghjklmnpqrstvwxyz]/gi).length == n); }else{ return []; } }
let words = s.split(' ').filter(e => e != '');
const assert = require('node:assert'); function test() { let candidate = select_words; assert.deepEqual(candidate("Mary had a little lamb", 4),["little"]); assert.deepEqual(candidate("Mary had a little lamb", 3),["Mary", "lamb"]); assert.deepEqual(candidate("simple white space", 2),[]); assert.deepEqual(candidate("Hello world", 4),["world"]); assert.deepEqual(candidate("Uncle sam", 3),["Uncle"]); assert.deepEqual(candidate("", 4),[]); assert.deepEqual(candidate("a b c d e f", 1),["b", "c", "d", "f"]); } test();
humaneval-HumanEval_83_starts_one_ends.json-L5
js
//Given a positive integer n, return the count of the numbers of n-digit // positive integers that start or end with 1. function starts_one_ends(n){ let ones = [];
if(i.toString().startsWith('1') || i.toString().endsWith('1')){ ones.push(i); } } return ones.length; }
for(let i = Math.pow(10, n-1); i < Math.pow(10, n); i++){
const assert = require('node:assert'); function test() { let candidate = starts_one_ends; assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(2),18); assert.deepEqual(candidate(3),180); assert.deepEqual(candidate(4),1800); assert.deepEqual(candidate(5),18000); } test();
humaneval-HumanEval_57_monotonic.json-L16
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_48_is_palindrome.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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)) {
break; } left++; right--; } return isPalindrome; } }
isPalindrome = false;
} 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_110_exchange.json-L18
py
from typing import List def exchange(lst1: List[int], lst2: List[int]) -> str: """In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a list of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". For example: >>> exchange([1, 2, 3, 4], [1, 2, 3, 4]) 'YES' >>> exchange([1, 2, 3, 4], [1, 5, 3, 4]) 'NO' It is assumed that the input lists will be non-empty. """
for x in lst1: if x % 2 == 1: count += 1 for y in lst2: if y % 2 == 0: count -= 1 if count > 0: return "NO" else: return "YES"
count = 0
def check(candidate): assert candidate([1, 2, 3, 4], [1, 2, 3, 4]) == 'YES' assert candidate([1, 2, 3, 4], [1, 5, 3, 4]) == 'NO' assert candidate([1, 2, 3, 4], [2, 1, 4, 3]) == 'YES' assert candidate([5, 7, 3], [2, 6, 4]) == 'YES' assert candidate([5, 7, 3], [2, 6, 3]) == 'NO' assert candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]) == 'NO' assert candidate([100, 200], [200, 200]) == 'YES' def test_check(): check(exchange) test_check()
humaneval-HumanEval_0_has_close_elements.json-L13
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++){ for(var j = i + 1; j < numbers.length; j++){ if(Math.abs(numbers[i] - numbers[j]) < threshold){ return true; }
} return false; }
}
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_5_intersperse.json-L12
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:
result.append(numbers[0]) for num in numbers[1:]: result.append(delimeter) result.append(num) return result
return result
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_43_pairs_sum_to_zero.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 { // 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_111_histogram.json-L39
js
//Given a string representing a space separated lowercase letters, return an object // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram("a b c") // {"a": 1, "b": 1, "c": 1} // >>> histogram("a b b a") // {"a": 2, "b": 2} // >>> histogram("a b c a b") // {"a": 2, "b": 2} // >>> histogram("b b b b a") // {"b": 4} // >>> histogram("") // {} function histogram(test){ if (test.length === 0){ return {}; } var lst = test.split(" "); var count = {}; for (var i = 0; i < lst.length; i++){ if (count[lst[i]]){ count[lst[i]] += 1; } else{ count[lst[i]] = 1; } } console.log(count); var max = 0; var result = {}; for (var key in count){ if (count[key] > max){ max = count[key]; result = {}; result[key] = max; } else if (count[key] === max){
} } return result; }
result[key] = max;
const assert = require('node:assert'); function test() { let candidate = histogram; assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate("b b b b a"),{"b": 4}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate(""),{}); assert.deepEqual(candidate("a"),{"a": 1}); } test();
humaneval-HumanEval_136_largest_smallest_integers.json-L21
py
from typing import List, Tuple, Optional def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]: """ Create a function that returns a tuple (a, b), where 'a' is the largest of negative integers, and 'b' is the smallest of positive integers in a list. If there is no negative or positive integers, return them as None. Examples: >>> largest_smallest_integers([2, 4, 1, 3, 5, 7]) (None, 1) >>> largest_smallest_integers([]) (None, None) >>> largest_smallest_integers([0]) (None, None) """ smallest_positive = None largest_negative = None for num in lst:
if smallest_positive is None or num < smallest_positive: smallest_positive = num elif num < 0: if largest_negative is None or num > largest_negative: largest_negative = num return (largest_negative, smallest_positive)
if num > 0:
def check(candidate): assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1) assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1) assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1) assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2) assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2) assert candidate([]) == (None, None) assert candidate([0]) == (None, None) assert candidate([-1, -3, -5, -6]) == (-1, None) assert candidate([-1, -3, -5, -6, 0]) == (-1, None) assert candidate([-6, -4, -4, -3, 1]) == (-3, 1) assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1) def test_check(): check(largest_smallest_integers) test_check()
humaneval-HumanEval_131_digits.json-L24
js
//Given a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits(1) // 1 // >>> digits(4) // 0 // >>> digits(235) // 15 function digits(n){ if(!n){ return "error"; } if(n < 0){ return "error"; } var temp = 0; var prod = 1; var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp;
} } if(odd){ return 0; } return prod; }
odd = false;
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_69_search.json-L29
js
//You are given a non-empty array of positive integers. Return the greatest integer that is greater than // zero, and has a frequency greater than or equal to the value of the integer itself. // The frequency of an integer is the number of times it appears in the array. // If no such a value exist, return -1. // Examples: // >>> search([4, 1, 2, 2, 3, 1]) // 2 // >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) // 3 // >>> search([5, 5, 4, 4, 4]) // -1 function search(lst){ var h = {}; for (var i=0; i<lst.length; i++){ var x = lst[i]; if (x in h){ h[x] += 1; } else{ h[x] = 1; } } var keys = Object.keys(h); var max = 0; for (var i=0; i<keys.length; i++){ if (keys[i] > max && h[keys[i]] >= keys[i]){ max = keys[i]; }
if (max == 0){ return -1; } return max; }
}
const assert = require('node:assert'); function test() { let candidate = search; assert.deepEqual(candidate([5, 5, 5, 5, 1]),1); assert.deepEqual(candidate([4, 1, 4, 1, 4, 4]),4); assert.deepEqual(candidate([3, 3]),-1); assert.deepEqual(candidate([8, 8, 8, 8, 8, 8, 8, 8]),8); assert.deepEqual(candidate([2, 3, 3, 2, 2]),2); assert.deepEqual(candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]),1); assert.deepEqual(candidate([3, 2, 8, 2]),2); assert.deepEqual(candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]),1); assert.deepEqual(candidate([8, 8, 3, 6, 5, 6, 4]),-1); assert.deepEqual(candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]),1); assert.deepEqual(candidate([1, 9, 10, 1, 3]),1); assert.deepEqual(candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]),5); assert.deepEqual(candidate([1]),1); assert.deepEqual(candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]),4); assert.deepEqual(candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]),2); assert.deepEqual(candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]),1); assert.deepEqual(candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]),4); assert.deepEqual(candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]),4); assert.deepEqual(candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]),2); assert.deepEqual(candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]),-1); assert.deepEqual(candidate([10]),-1); assert.deepEqual(candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]),2); assert.deepEqual(candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]),1); assert.deepEqual(candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]),1); assert.deepEqual(candidate([3, 10, 10, 9, 2]),-1); } test();
humaneval-HumanEval_126_is_sorted.json-L35
js
//Given an array of numbers, return whether or not they are sorted // in ascending order. If array has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> is_sorted([5]) // true // >>> is_sorted([1, 2, 3, 4, 5]) // true // >>> is_sorted([1, 3, 2, 4, 5]) // false // >>> is_sorted([1, 2, 3, 4, 5, 6]) // true // >>> is_sorted([1, 2, 3, 4, 5, 6, 7]) // true // >>> is_sorted([1, 3, 2, 4, 5, 6, 7]) // false // >>> is_sorted([1, 2, 2, 3, 3, 4]) // true // >>> is_sorted([1, 2, 2, 2, 3, 4]) // false function is_sorted(lst){ var last = null; var dupe_found = false; for (var x of lst){ if (last == null){ last = x; } else if (x < last){ return false; } else if (x == last){ if (dupe_found){ return false; } else { dupe_found = true; }
last = x; dupe_found = false; } } return true; }
} else {
const assert = require('node:assert'); function test() { let candidate = is_sorted; assert.deepEqual(candidate([5]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, 7]),false); assert.deepEqual(candidate([]),true); assert.deepEqual(candidate([1]),true); assert.deepEqual(candidate([3, 2, 1]),false); assert.deepEqual(candidate([1, 2, 2, 2, 3, 4]),false); assert.deepEqual(candidate([1, 2, 3, 3, 3, 4]),false); assert.deepEqual(candidate([1, 2, 2, 3, 3, 4]),true); assert.deepEqual(candidate([1, 2, 3, 4]),true); } test();
humaneval-HumanEval_41_car_race_collision.json-L15
py
def car_race_collision(n: int) -> int: """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ l = n * n count = 0
right_cars = [i for i in range(l)] for i in range(l): for j in range(l): if left_cars[i] == right_cars[j]: count += 1 return count
left_cars = [i for i in range(l)]
def check(candidate): assert candidate(2) == 4 assert candidate(3) == 9 assert candidate(4) == 16 assert candidate(8) == 64 assert candidate(10) == 100 def test_check(): check(car_race_collision) test_check()
humaneval-HumanEval_33_sort_third.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) {
l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j)); j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
min = l_e.get(j);
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_77_iscube.json-L20
js
//Write a function that takes an integer a and returns true // if this ingeger is a cube of some integer number. // Note: you may assume the input is always valid. // Examples: // >>> iscube(1) // true // >>> iscube(2) // false // >>> iscube(-1) // true // >>> iscube(64) // true // >>> iscube(0) // true // >>> iscube(180) // false function iscube(a){ if(Math.cbrt(a)%1==0){ return true;
return false; } }
}else{
const assert = require('node:assert'); function test() { let candidate = iscube; assert.deepEqual(candidate(1),true); assert.deepEqual(candidate(2),false); assert.deepEqual(candidate(-1),true); assert.deepEqual(candidate(64),true); assert.deepEqual(candidate(180),false); assert.deepEqual(candidate(1000),true); assert.deepEqual(candidate(0),true); assert.deepEqual(candidate(1729),false); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L56
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') elif x > 2.7: final.append('B') elif x > 2.3: final.append('B-') elif x > 2.0: final.append('C+') elif x > 1.7: final.append('C') elif x > 1.3: final.append('C-') elif x > 1.0: final.append('D+') elif x > 0.7: final.append('D') elif x > 0.0: final.append('D-') else:
return final
final.append('E')
def check(candidate): assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-'] assert candidate([1.2]) == ['D+'] assert candidate([0.5]) == ['D-'] assert candidate([0.0]) == ['E'] assert candidate([1.0, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+'] assert candidate([0.0, 0.7]) == ['E', 'D-'] def test_check(): check(numerical_letter_grade) test_check()
humaneval-HumanEval_159_eat.json-L40
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You're a hungry rabbit, and you already have eaten a certain number of carrots, // but now you need to eat more carrots to complete the day's meals. // you should return an array array list of [ total number of eaten carrots after your meals, // the number of carrots left after your meals ] // if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. // Example: // >>> eat((5l), (6l), (10l)) // (new ArrayList<Long>(Arrays.asList((long)11l, (long)4l))) // >>> eat((4l), (8l), (9l)) // (new ArrayList<Long>(Arrays.asList((long)12l, (long)1l))) // >>> eat((1l), (10l), (10l)) // (new ArrayList<Long>(Arrays.asList((long)11l, (long)0l))) // >>> eat((2l), (11l), (5l)) // (new ArrayList<Long>(Arrays.asList((long)7l, (long)0l))) // Variables: // @number : integer // the number of carrots that you have eaten. // @need : integer // the number of carrots that you need to eat. // @remaining : integer // the number of remaining carrots thet exist in stock // Constrain: // * 0 <= number <= 1000 // * 0 <= need <= 1000 // * 0 <= remaining <= 1000 // Have fun :) public static ArrayList<Long> eat(long number, long need, long remaining) { long total = number + Math.min(need, remaining); long left = Math.max(0, remaining - need); return new ArrayList<Long>(Arrays.asList(total, left)); }
}
} public static void main(String[] args) { assert(eat((5l), (6l), (10l)).equals((new ArrayList<Long>(Arrays.asList((long)11l, (long)4l))))); assert(eat((4l), (8l), (9l)).equals((new ArrayList<Long>(Arrays.asList((long)12l, (long)1l))))); assert(eat((1l), (10l), (10l)).equals((new ArrayList<Long>(Arrays.asList((long)11l, (long)0l))))); assert(eat((2l), (11l), (5l)).equals((new ArrayList<Long>(Arrays.asList((long)7l, (long)0l))))); assert(eat((4l), (5l), (7l)).equals((new ArrayList<Long>(Arrays.asList((long)9l, (long)2l))))); assert(eat((4l), (5l), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l))))); } }
humaneval-HumanEval_148_bf.json-L34
js
//There are eight planets in our solar system: the closerst to the Sun // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, // Uranus, Neptune. // Write a function that takes two planet names as strings planet1 and planet2. // The function should return an array containing all planets whose orbits are // located between the orbit of planet1 and the orbit of planet2, sorted by // the proximity to the sun. // The function should return an empty array if planet1 or planet2 // are not correct planet names. // Examples // >>> bf("Jupiter", "Neptune") // ["Saturn", "Uranus"] // >>> bf("Earth", "Mercury") // "Venus" // >>> bf("Mercury", "Uranus") // ["Venus", "Earth", "Mars", "Jupiter", "Saturn"] function bf(planet1, planet2){ var planets = { 'Mercury':1, 'Venus':2, 'Earth':3, 'Mars':4, 'Jupiter':5, 'Saturn':6, 'Uranus':7, 'Neptune':8 } if(!planets[planet1] || !planets[planet2]){ return []; } var keys = Object.keys(planets); var position1 = keys.indexOf(planet1); var position2 = keys.indexOf(planet2);
var temp = position1; position1 = position2; position2 = temp; } var res = []; for(var i = position1 + 1; i < position2; i++){ res.push(keys[i]); } return res; }
if(position1 > position2){
const assert = require('node:assert'); function test() { let candidate = bf; assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]); assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]); assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Earth"),[]); assert.deepEqual(candidate("Mars", "Earth"),[]); assert.deepEqual(candidate("Jupiter", "Makemake"),[]); } test();
humaneval-HumanEval_65_circular_shift.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 { // Circular shift the digits of the integer x, shift the digits right by shift // and return the result as a string. // If shift > number of digits, return digits reversed. // >>> circularShift((12l), (1l)) // ("21") // >>> circularShift((12l), (2l)) // ("12") public static String circularShift(long x, long shift) { String digits = String.valueOf(x); if (shift > digits.length()) { return new StringBuilder(digits).reverse().toString(); }
} }
return (digits.substring(digits.length() - (int)shift, digits.length()) + digits.substring(0, digits.length() - (int)shift));
} public static void main(String[] args) { assert(circularShift((100l), (2l)).equals(("001"))); assert(circularShift((12l), (2l)).equals(("12"))); assert(circularShift((97l), (8l)).equals(("79"))); assert(circularShift((12l), (1l)).equals(("21"))); assert(circularShift((11l), (101l)).equals(("11"))); } }
humaneval-HumanEval_156_int_to_mini_roman.json-L24
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', 40: 'xl',
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
10: 'x',
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_94_skjkasdkd.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 { // You are given an array array list of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) // (10l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) // (25l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) // (13l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) // (11l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) // (3l) // >>> skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) // (7l) public static long skjkasdkd(ArrayList<Long> lst) { long largestPrime = 0l; for (Long item : lst) { long number = item; int counter = 0; if (item == 1) { continue; } if (item == 2) { counter = 1; } else { int l = 1; while (l <= (int) number) { if (number % l == 0) { counter++; } l++; } } if (counter == 2) { if (number > largestPrime) { largestPrime = number; } }
if (largestPrime == 0) { return 0l; } else { long output = 0l; while (largestPrime > 0) { output += largestPrime % 10; largestPrime /= 10; } return output; } } }
}
} public static void main(String[] args) { assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l, (long)2l, (long)1l, (long)3l, (long)5l, (long)7l, (long)4l, (long)5l, (long)5l, (long)5l, (long)2l, (long)181l, (long)32l, (long)4l, (long)32l, (long)3l, (long)2l, (long)32l, (long)324l, (long)4l, (long)3l)))) == (10l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)1l, (long)8l, (long)2l, (long)4597l, (long)2l, (long)1l, (long)3l, (long)40l, (long)1l, (long)2l, (long)1l, (long)2l, (long)4l, (long)2l, (long)5l, (long)1l)))) == (25l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)1l, (long)32l, (long)5107l, (long)34l, (long)83278l, (long)109l, (long)163l, (long)23l, (long)2323l, (long)32l, (long)30l, (long)1l, (long)9l, (long)3l)))) == (13l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)724l, (long)32l, (long)71l, (long)99l, (long)32l, (long)6l, (long)0l, (long)5l, (long)91l, (long)83l, (long)0l, (long)5l, (long)6l)))) == (11l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)81l, (long)12l, (long)3l, (long)1l, (long)21l)))) == (3l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)0l, (long)8l, (long)1l, (long)2l, (long)1l, (long)7l)))) == (7l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)8191l, (long)123456l, (long)127l, (long)7l)))) == (19l)); assert(skjkasdkd((new ArrayList<Long>(Arrays.asList((long)127l, (long)97l, (long)8192l)))) == (10l)); } }
humaneval-HumanEval_111_histogram.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a 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) {
String[] ss = test.split(" "); for (String sss : ss) { if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; } }
HashMap<String,Long> hm = new HashMap<String,Long>();
} 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_99_closest_integer.json-L28
js
//Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closest_integer("10") // 10 // >>> closest_integer("15.3") // 15 // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){ return Math.floor(value); }else{ return Math.ceil(value); } }else{ if(value - Math.floor(value) > -0.5){ return Math.floor(value); }else{ return Math.ceil(value); }
}
}
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L12
py
def is_multiply_prime(a: int) -> bool: """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: >>> is_multiply_prime(30) True 30 = 2 * 3 * 5 """ n = a d = 2
while d * d <= n: if n % d == 0: prime_factors.append(d) n //= d else: d += 1 if n > 1: prime_factors.append(n) if len(prime_factors) == 3: return True else: return False
prime_factors = []
def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(105) == True assert candidate(126) == False assert candidate(729) == False assert candidate(891) == False assert candidate(1001) == True def test_check(): check(is_multiply_prime) test_check()
humaneval-HumanEval_137_compare_one.json-L36
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(',', '.')
return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
if float(a_tmp) > float(b_tmp):
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_125_split_words.json-L22
py
from typing import Union, List def split_words(txt: str) -> Union[List[str], int]: """ Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 Examples >>> split_words('Hello world!') ['Hello', 'world!'] >>> split_words('Hello,world!') ['Hello', 'world!'] >>> split_words('abcdef') 3 """ alphabet = [chr(letter) for letter in range(ord('a'), ord('z') + 1)] if ' ' in txt: return txt.split(' ') elif ',' in txt: return txt.split(',') else:
return len([letter for letter in txt if letter in alphabet and alphabet.index(letter) % 2 == 1])
def check(candidate): assert candidate('Hello world!') == ['Hello', 'world!'] assert candidate('Hello,world!') == ['Hello', 'world!'] assert candidate('Hello world,!') == ['Hello', 'world,!'] assert candidate('Hello,Hello,world !') == ['Hello,Hello,world', '!'] assert candidate('abcdef') == 3 assert candidate('aaabb') == 2 assert candidate('aaaBb') == 1 assert candidate('') == 0 def test_check(): check(split_words) test_check()
humaneval-HumanEval_1_separate_paren_groups.json-L33
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Input to this function is a string containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); }
} return output; } }
}
} 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_62_derivative.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 { // xs represent coefficients of a polynomial. // xs[0] + xs[1] * x + xs[2] * x^2 + .... // Return derivative of this polynomial in the same form. // >>> derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)12l, (long)20l))) // >>> derivative((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l))) public static ArrayList<Long> derivative(ArrayList<Long> xs) { ArrayList<Long> ans = new ArrayList<Long>(); for (int i = 1; i < xs.size(); i++) { ans.add(xs.get(i) * i);
return ans; } }
}
} public static void main(String[] args) { assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)12l, (long)20l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l, (long)0l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)0l, (long)16l))))); assert(derivative((new ArrayList<Long>(Arrays.asList((long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_36_fizz_buzz.json-L12
py
def fizz_buzz(n: int) -> int: """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ x = 0 for i in range(n):
x += str(i).count('7') return x
if i % 11 == 0 or i % 13 == 0:
def check(candidate): assert candidate(50) == 0 assert candidate(78) == 2 assert candidate(79) == 3 assert candidate(100) == 3 assert candidate(200) == 6 assert candidate(4000) == 192 assert candidate(10000) == 639 assert candidate(100000) == 8026 def test_check(): check(fizz_buzz) test_check()
humaneval-HumanEval_64_vowels_count.json-L19
py
def vowels_count(s: str) -> int: """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count('abcde') 2 >>> vowels_count('ACEDY') 3 """ s = s.lower() i = 0 count = 0 while i < len(s): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'): count += 1
count += 1 i += 1 return count
if (s[i] == 'y' and i == len(s) - 1):
def check(candidate): assert candidate('abcde') == 2 assert candidate('Alone') == 3 assert candidate('key') == 2 assert candidate('bye') == 1 assert candidate('keY') == 2 assert candidate('bYe') == 1 assert candidate('ACEDY') == 3 def test_check(): check(vowels_count) test_check()
humaneval-HumanEval_77_iscube.json-L21
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
if a == 0: return True for i in range(1,int(math.sqrt(a))+1): if i**3 == a: return True return False pass
a = abs(a)
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_147_get_max_triples.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 are given a positive integer n. You have to create an integer array array list a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { arrayList.add(i * i - i + 1); } for (int i = 0; i < arrayList.size(); i++) { for (int j = i + 1; j < arrayList.size(); j++) { for (int k = j + 1; k < arrayList.size(); k++) {
count++; } } } } return count; } }
if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) {
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_9_rolling_max.json-L9
js
//From a given array of integers, generate an array of rolling maximum element found until given moment // in the sequence. // >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) // [1, 2, 3, 3, 3, 4, 4] function rolling_max(numbers){ let max = []; let tempMax = 0; for(let i = 0; i < numbers.length; i++){
tempMax = numbers[i]; } max.push(tempMax); } return max; }
if(tempMax < numbers[i]){
const assert = require('node:assert'); function test() { let candidate = rolling_max; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4]),[1, 2, 3, 4]); assert.deepEqual(candidate([4, 3, 2, 1]),[4, 4, 4, 4]); assert.deepEqual(candidate([3, 2, 3, 100, 3]),[3, 3, 3, 100, 100]); } test();
humaneval-HumanEval_120_maximum.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list arr of integers and a positive integer k, return a sorted array list // of length k with the maximum k numbers in arr. // Example 1: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)-4l, (long)5l))), (3l)) // (new ArrayList<Long>(Arrays.asList((long)-4l, (long)-3l, (long)5l))) // Example 2: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l, (long)4l))), (2l)) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l))) // Example 3: // >>> maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)2l, (long)1l, (long)2l, (long)-1l, (long)-2l, (long)1l))), (1l)) // (new ArrayList<Long>(Arrays.asList((long)2l))) // Note: // 1. The length of the array array list will be in the range of [1, 1000]. // 2. The elements in the array array list will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) public static ArrayList<Long> maximum(ArrayList<Long> arr, long k) { Collections.sort(arr); return new ArrayList<Long>(arr.subList((int)(arr.size() - k), (int)(arr.size())));
}
}
} public static void main(String[] args) { assert(maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)-4l, (long)5l))), (3l)).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-3l, (long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l, (long)4l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-3l, (long)2l, (long)1l, (long)2l, (long)-1l, (long)-2l, (long)1l))), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)123l, (long)-123l, (long)20l, (long)0l, (long)1l, (long)2l, (long)-3l))), (3l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)20l, (long)123l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-123l, (long)20l, (long)0l, (long)1l, (long)2l, (long)-3l))), (4l)).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)20l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)5l, (long)15l, (long)0l, (long)3l, (long)-13l, (long)-8l, (long)0l))), (7l)).equals((new ArrayList<Long>(Arrays.asList((long)-13l, (long)-8l, (long)0l, (long)0l, (long)3l, (long)5l, (long)15l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)0l, (long)2l, (long)5l, (long)3l, (long)-10l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)5l, (long)-7l))), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)5l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)4l, (long)-4l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)4l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)-10l, (long)10l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)10l))))); assert(maximum((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)-23l, (long)243l, (long)-400l, (long)0l))), (0l)).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_158_find_max.json-L20
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){
} } 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; }
unique_word[char] = 1;
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_137_compare_one.json-L27
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):
return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
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_129_minPath.json-L34
js
//Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered arrays of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered array of the values on the cells that the minimum path go through. // Examples: // >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) // [1, 2, 1] // >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) // [1] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr; }
} let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
}
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7),[1, 10, 1, 10, 1, 10, 1]); assert.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9),[1, 6, 1, 6, 1, 6, 1, 6, 1]); assert.deepEqual(candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12),[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]); assert.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_138_is_equal_to_sum_even.json-L16
js
//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> is_equal_to_sum_even(4) // false // >>> is_equal_to_sum_even(6) // false // >>> is_equal_to_sum_even(8) // true function is_equal_to_sum_even(n){ let m =0; for(let i=2;i<n;i+=2){ for(let j=2;j<n;j+=2){ for(let k=2;k<n;k+=2){ for(let l=2;l<n;l+=2){ if((i+j+k+l)==n){
break; } } } } } if(m==1){ return true; } else{ return false; } }
m=1;
const assert = require('node:assert'); function test() { let candidate = is_equal_to_sum_even; assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),true); assert.deepEqual(candidate(11),false); assert.deepEqual(candidate(12),true); assert.deepEqual(candidate(13),false); assert.deepEqual(candidate(16),true); } test();
humaneval-HumanEval_144_simplify.json-L13
js
//Your task is to implement a function that will simplify the expression // x * n. The function returns true if x * n evaluates to a whole number and false // otherwise. Both x and n, are string representation of a fraction, and have the following format, // <numerator>/<denominator> where both numerator and denominator are positive whole numbers. // You can assume that x, and n are valid fractions, and do not have zero as denominator. // >>> simplify("1/5", "5/1") // true // >>> simplify("1/6", "2/1") // false // >>> simplify("7/10", "10/2") // false function simplify(x, n){
let xDenominator = parseInt(x.split('/')[1]); let nNumerator = parseInt(n.split('/')[0]); let nDenominator = parseInt(n.split('/')[1]); let xTimesN = xNumerator * nNumerator / (xDenominator * nDenominator); return Number.isInteger(xTimesN); }
let xNumerator = parseInt(x.split('/')[0]);
const assert = require('node:assert'); function test() { let candidate = simplify; assert.deepEqual(candidate("1/5", "5/1"),true); assert.deepEqual(candidate("1/6", "2/1"),false); assert.deepEqual(candidate("5/1", "3/1"),true); assert.deepEqual(candidate("7/10", "10/2"),false); assert.deepEqual(candidate("2/10", "50/10"),true); assert.deepEqual(candidate("7/2", "4/2"),true); assert.deepEqual(candidate("11/6", "6/1"),true); assert.deepEqual(candidate("2/3", "5/2"),false); assert.deepEqual(candidate("5/2", "3/5"),false); assert.deepEqual(candidate("2/4", "8/4"),true); assert.deepEqual(candidate("2/4", "4/2"),true); assert.deepEqual(candidate("1/5", "5/1"),true); assert.deepEqual(candidate("1/5", "1/5"),false); } test();
humaneval-HumanEval_33_sort_third.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); }
for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) { min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j)); j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
}
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_129_minPath.json-L62
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]); }
for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
let nextCell = neighbours[0];
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_31_is_prime.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 { // Return true if a given number is prime, and false otherwise. // >>> isPrime((6l)) // (false) // >>> isPrime((101l)) // (true) // >>> isPrime((11l)) // (true) // >>> isPrime((13441l)) // (true) // >>> isPrime((61l)) // (true) // >>> isPrime((4l)) // (false) // >>> isPrime((1l)) // (false) public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long i = 5; while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; } 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_39_prime_fib.json-L35
js
//prime_fib returns n-th number that is a Fibonacci number and it's also prime. // >>> prime_fib(1) // 2 // >>> prime_fib(2) // 3 // >>> prime_fib(3) // 5 // >>> prime_fib(4) // 13 // >>> prime_fib(5) // 89 function prime_fib(n){ function isPrime(number){ if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false; } } return true; } } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b;
num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
b = temp;
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_40_triples_sum_to_zero.json-L36
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) { return false; } ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList); for (int i = 0; i < sortedList.size() - 2; i++) { int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) {
} else { k--; } } } return false; } }
j++;
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_149_sorted_list_sum.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 { // 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) { if (s1.length() == s2.length()) { return s1.compareTo(s2); } return s1.length() - s2.length(); }
return result; } }
});
} 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"))))); } }