prompt
stringlengths
96
1.46k
canonical_solution
stringlengths
16
1.4k
lang
stringclasses
5 values
source
stringclasses
1 value
import java.util.*; import java.lang.*; class Solution { /** 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: largestSmallestIntegers(Arrays.asList(2, 4, 1, 3, 5, 7)) == (Optional.empty(), Optional.of(1)) largestSmallestIntegers(Arrays.asList()) == (Optional.empty(), Optional.empty()) largestSmallestIntegers(Arrays.asList(0)) == (Optional.empty(), Optional.empty()) */ public List<Optional<Integer>> largestSmallestIntegers(List<Integer> lst){
List<Integer> smallest = lst.stream().filter(p -> p < 0).toList(); List<Integer> largest = lst.stream().filter(p -> p > 0).toList(); Optional<Integer> s = Optional.empty(); if (smallest.size() > 0) { s = Optional.of(Collections.max(smallest)); } Optional<Integer> l = Optional.empty(); if (largest.size() > 0) { l = Optional.of(Collections.min(largest)); } return Arrays.asList(s, l); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 , compareOne(1, 2.5) -> Optional.of(2.5) compareOne(1, "2,3") -> Optional.of("2,3") compareOne("5,1", "6") -> Optional.of("6") compareOne("1", 1) -> Optional.empty() */ public Optional<Object> compareOne(Object a, Object b) {
double temp_a = 0, temp_b = 0; if (a instanceof Integer) { temp_a = (Integer) a * 1.0; } else if (a instanceof Double) { temp_a = (double) a; } else if (a instanceof String) { temp_a = Double.parseDouble(((String) a).replace(',', '.')); } if (b instanceof Integer) { temp_b = (Integer) b * 1.0; } else if (b instanceof Double) { temp_b = (double) b; } else if (b instanceof String) { temp_b = Double.parseDouble(((String) b).replace(',', '.')); } if (temp_a == temp_b) { return Optional.empty(); } else if (temp_a > temp_b) { return Optional.of(a); } else { return Optional.of(b); } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example isEqualToSumEven(4) == false isEqualToSumEven(6) == false isEqualToSumEven(8) == true */ public boolean isEqualToSumEven(int n) {
return n % 2 == 0 && n >= 8; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> specialFactorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. */ public long specialFactorial(int n) {
long fact_i = 1, special_fact = 1; for (int i = 1; i <= n; i++) { fact_i *= i; special_fact *= fact_i; } return special_fact; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fixSpaces("Example") == "Example" fixSpaces("Example 1") == "Example_1" fixSpaces(" Example 2") == "_Example_2" fixSpaces(" Example 3") == "_Example-3" */ public String fixSpaces(String text) {
StringBuilder sb = new StringBuilder(); int start = 0, end = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == ' ') { end += 1; } else { if (end - start > 2) { sb.append('-'); } else if (end - start > 0) { sb.append("_".repeat(end - start)); } sb.append(text.charAt(i)); start = i + 1; end = i + 1; } } if (end - start > 2) { sb.append('-'); } else if (end - start > 0) { sb.append("_".repeat(end - start)); } return sb.toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Create a function which takes a string representing a file's name, and returns "Yes" if the the file's name is valid, and returns "No" otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: ["txt", "exe", "dll"] Examples: file_name_check("example.txt") # => "Yes" file_name_check("1example.dll") # => "No" (the name should start with a latin alphapet letter) */ public String filenameCheck(String file_name) {
List<String> suf = Arrays.asList("txt", "exe", "dll"); String[] lst = file_name.split("\\." ); if (lst.length != 2 || !suf.contains(lst[1]) || lst[0].isEmpty() || !Character.isLetter(lst[0].charAt(0))) { return "No"; } int t = (int) lst[0].chars().map(x -> (char) x).filter(Character::isDigit).count(); if (t > 3) { return "No"; } return "Yes"; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. Examples: For lst = [1,2,3] the output should be 6 For lst = [] the output should be 0 For lst = [-1,-5,2,-1,-5] the output should be -126 */ public int sumSquares(List<Integer> lst) {
List<Integer> result = new ArrayList<>(); for (int i = 0; i < lst.size(); i++) { if (i % 3 == 0) { result.add(lst.get(i) * lst.get(i)); } else if (i % 4 == 0) { result.add((int) Math.pow(lst.get(i), 3)); } else { result.add(lst.get(i)); } } return result.stream().reduce(Integer::sum).orElse(0); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters */ public String wordsInSentence(String sentence) {
List<String> new_lst = new ArrayList<>(); for (String word : sentence.split(" " )) { boolean flg = true; if (word.length() == 1) { continue; } for (int i = 2; i < word.length(); i++) { if (word.length() % i == 0) { flg = false; break; } } if (flg) { new_lst.add(word); } } return String.join(" ", new_lst); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public boolean simplify(String x, String n) {
String[] a = x.split("/"); String[] b = n.split("/"); int numerator = Integer.parseInt(a[0]) * Integer.parseInt(b[0]); int denom = Integer.parseInt(a[1]) * Integer.parseInt(b[1]); return numerator / denom * denom == numerator; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function which sorts the given list of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original list. For example: >>> orderByPoints(Arrays.asList(1, 11, -1, -11, -12)) == [-1, -11, 1, -12, 11] >>> orderByPoints(Arrays.asList()) == [] */ public List<Integer> orderByPoints(List<Integer> nums) {
List<Integer> result = new ArrayList<>(nums); result.sort((o1, o2) -> { int sum1 = 0; int sum2 = 0; for (int i = 0; i < String.valueOf(o1).length(); i++) { if (i != 0 || o1 >= 0) { sum1 += (String.valueOf(o1).charAt(i) - '0' ); if (i == 1 && o1 < 0) { sum1 = -sum1; } } } for (int i = 0; i < String.valueOf(o2).length(); i++) { if (i != 0 || o2 >= 0) { sum2 += (String.valueOf(o2).charAt(i) - '0' ); if (i == 1 && o2 < 0) { sum2 = -sum2; } } } return Integer.compare(sum1, sum2); }); return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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(Arrays.asList(15, -73, 14, -15)) => 1 specialFilter(Arrays.asList(33, -2, -3, 45, 21, 109)) => 2 */ public int specialFilter(List<Integer> nums) {
int count = 0; for (int num : nums) { if (num > 10) { String odd_digits = "13579"; String number_as_string = String.valueOf(num); if (odd_digits.indexOf(number_as_string.charAt(0)) != -1 && odd_digits.indexOf(number_as_string.charAt(number_as_string.length() - 1)) != -1) { count += 1; } } } return count; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a positive integer n. You have to create an integer array a of length n. For each i (1 <= i <= n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). */ public int getMaxTriples(int n) {
List<Integer> A = new ArrayList<>(); for (int i = 1; i <= n; i++) { A.add(i * i - i + 1); } int count = 0; for (int i = 0; i < A.size(); i++) { for (int j = i + 1; j < A.size(); j++) { for (int k = j + 1; k < A.size(); k++) { if ((A.get(i) + A.get(j) + A.get(k)) % 3 == 0) { count += 1; } } } } return count; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple 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 tuple 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"] */ public List<String> bf(String planet1, String planet2) {
List<String> planet_names = Arrays.asList("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"); if (!planet_names.contains(planet1) || !planet_names.contains(planet2) || planet1.equals(planet2)) { return List.of(); } int planet1_index = planet_names.indexOf(planet1); int planet2_index = planet_names.indexOf(planet2); if (planet1_index < planet2_index) { return planet_names.subList(planet1_index + 1, planet2_index); } else { return planet_names.subList(planet2_index + 1, planet1_index); } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that accepts a list of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted list with a sorted order, The list is always a list of strings and never an array of numbers, and it may contain duplicates. The order of the list should be ascending by length of each word, and you should return the list sorted by that rule. If two words have the same length, sort the list alphabetically. The function should return a list of strings in sorted order. You may assume that all words will have the same length. For example: assert listSort(Arrays.asList("aa", "a", "aaa")) => ["aa"] assert listSort(Arrays.asList("ab", "a", "aaa", "cd")) => ["ab", "cd"] */ public List<String> listSort(List<String> lst) {
List<String> lst_sorted = new ArrayList<>(lst); Collections.sort(lst_sorted); List<String> new_lst = new ArrayList<>(); for (String i : lst_sorted) { if (i.length() % 2 == 0) { new_lst.add(i); } } new_lst.sort(Comparator.comparingInt(String::length)); return new_lst; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. Examples: for xOrY(7, 34, 12) == 34 for xOrY(15, 8, 5) == 5 */ public int xOrY(int n, int x, int y) {
if (n == 1) { return y; } for (int i = 2; i < n; i++) { if (n % i == 0) { return y; } } return x; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. doubleTheDifference(Arrays.asList(1, 3, 2, 0)) == 1 + 9 + 0 + 0 = 10 doubleTheDifference(Arrays.asList(-1, -2, 0)) == 0 doubleTheDifference(Arrays.asList(9, -2)) == 81 doubleTheDifference(Arrays.asList(0)) == 0 If the input list is empty, return 0. */ public int doubleTheDifference(List<Object> lst) {
return lst.stream().filter(i -> i instanceof Integer p && p > 0 && p % 2 != 0).map(i -> (Integer) i * (Integer) i).reduce(Integer::sum).orElse(0); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. example: compare(Arrays.asList(1,2,3,4,5,1),Arrays.asList(1,2,3,4,2,-2)) -> [0,0,0,0,3,3] compare(Arrays.asList(0,5,0,0,0,4),Arrays.asList(4,1,1,0,0,-2)) -> [4,4,1,0,0,6] */ public List<Integer> compare(List<Integer> game, List<Integer> guess) {
List<Integer> result = new ArrayList<>(); for (int i = 0; i < game.size(); i++) { result.add(Math.abs(game.get(i) - guess.get(i))); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ["SErviNGSliCes", "Cheese", "StuFfed"] then you should return "Slices.SErviNGSliCes" since "SErviNGSliCes" is the strongest extension (its strength is -1). Example: for StrongestExtension("my_class", ["AA", "Be", "CC"]) == "my_class.AA" */ public String StrongestExtension(String class_name, List<String> extensions) {
String strong = extensions.get(0); int my_val = (int) (strong.chars().filter(Character::isUpperCase).count() - strong.chars().filter(Character::isLowerCase).count()); for (String s : extensions) { int val = (int) (s.chars().filter(Character::isUpperCase).count() - s.chars().filter(Character::isLowerCase).count()); if (val > my_val) { strong = s; my_val = val; } } return class_name + "." + strong; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word cycpatternCheck("abcd","abd") => false cycpatternCheck("hello","ell") => true cycpatternCheck("whassup","psus") => false cycpatternCheck("abab","baa") => true cycpatternCheck("efef","eeff") => false cycpatternCheck("himenss","simen") => true */ public boolean cycpatternCheck(String a, String b) {
int l = b.length(); String pat = b + b; for (int i = 0; i <= a.length() - l; i++) { for (int j = 0; j <= l; j++) { if (a.substring(i, i + l).equals(pat.substring(j, j + l))) { return true; } } } return false; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an integer. return a tuple that has the number of even and odd digits respectively. Example: evenOddCount(-12) ==> (1, 1) evenOddCount(123) ==> (1, 2) */ public List<Integer> evenOddCount(int num) {
int even_count = 0, odd_count = 0; for (char i : String.valueOf(Math.abs(num)).toCharArray()) { if ((i - '0') % 2 == 0) { even_count += 1; } else { odd_count += 1; } } return Arrays.asList(even_count, odd_count); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> intToMiniRoman(19) == "xix" >>> intToMiniRoman(152) == "clii" >>> intToMiniRoman(426) == "cdxxvi" */ public String intToMiniRoman(int number) {
List<Integer> num = Arrays.asList(1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000); List<String> sym = Arrays.asList("I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"); int i = 12; String res = ""; while (number > 0) { int div = number / num.get(i); number %= num.get(i); while (div != 0) { res += sym.get(i); div -= 1; } i -= 1; } return res.toLowerCase(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given the lengths of the three sides of a triangle. Return true if the three sides form a right-angled triangle, false otherwise. A right-angled triangle is a triangle in which one angle is right angle or 90 degree. Example: rightAngleTriangle(3, 4, 5) == true rightAngleTriangle(1, 2, 3) == false */ public boolean rightAngleTriangle(int a, int b, int c) {
return a * a == b * b + c * c || b * b == a * a + c * c || c * c == a * a + b * b; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. findMax(["name", "of", "string"]) == "string" findMax(["name", "enam", "game"]) == "enam" findMax(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa" */ public String findMax(List<String> words) {
List<String> words_sort = new ArrayList<>(words); words_sort.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { Set<Character> s1 = new HashSet<>(); for (char ch : o1.toCharArray()) { s1.add(ch); } Set<Character> s2 = new HashSet<>(); for (char ch : o2.toCharArray()) { s2.add(ch); } if (s1.size() > s2.size()) { return 1; } else if (s1.size() < s2.size()) { return -1; } else { return -o1.compareTo(o2); } } }); return words_sort.get(words_sort.size() - 1); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 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(5, 6, 10) -> [11, 4] * eat(4, 8, 9) -> [12, 1] * eat(1, 10, 10) -> [11, 0] * eat(2, 11, 5) -> [7, 0] 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 List<Integer> eat(int number, int need, int remaining) {
if (need <= remaining) { return Arrays.asList(number + need, remaining - need); } else { return Arrays.asList(number + remaining, 0); } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given 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 = [2, 3, 4, 5] result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. */ public int doAlgebra(List<String> operator, List<Integer> operand) {
List<String> ops = new ArrayList<>(operator); List<Integer> nums = new ArrayList<>(operand); for (int i = ops.size() - 1; i >= 0; i--) { if (ops.get(i).equals("**")) { nums.set(i, (int) Math.round(Math.pow(nums.get(i), nums.get(i + 1)))); nums.remove(i + 1); ops.remove(i); } } for (int i = 0; i < ops.size(); i++) { if (ops.get(i).equals("*")) { nums.set(i, nums.get(i) * nums.get(i + 1)); nums.remove(i + 1); ops.remove(i); i--; } else if (ops.get(i).equals("/")) { nums.set(i, nums.get(i) / nums.get(i + 1)); nums.remove(i + 1); ops.remove(i); i--; } } for (int i = 0; i < ops.size(); i++) { if (ops.get(i).equals("+")) { nums.set(i, nums.get(i) + nums.get(i + 1)); nums.remove(i + 1); ops.remove(i); i--; } else if (ops.get(i).equals("-")) { nums.set(i, nums.get(i) - nums.get(i + 1)); nums.remove(i + 1); ops.remove(i); i--; } } return nums.get(0); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c" */ public String solve(String s) {
boolean flag = true; StringBuilder new_string = new StringBuilder(); for (char i : s.toCharArray()) { if (Character.isUpperCase(i)) { new_string.append(Character.toLowerCase(i)); flag = false; } else if (Character.isLowerCase(i)) { new_string.append(Character.toUpperCase(i)); flag = false; } else { new_string.append(i); } } if (flag) { new_string.reverse(); } return new_string.toString(); } }
java
THUDM/humaneval-x
import java.math.BigInteger; import java.security.*; import java.util.*; import java.lang.*; class Solution { /** Given a string "text", return its md5 hash equivalent string with length being 32. If "text" is an empty string, return Optional.empty(). >>> stringToMd5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62" */ public Optional<String> stringToMd5(String text) throws NoSuchAlgorithmException {
if (text.isEmpty()) { return Optional.empty(); } String md5 = new BigInteger(1, java.security.MessageDigest.getInstance("MD5").digest(text.getBytes())).toString(16); md5 = "0".repeat(32 - md5.length()) + md5; return Optional.of(md5); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generateIntegers(2, 8) => [2, 4, 6, 8] generateIntegers(8, 2) => [2, 4, 6, 8] generateIntegers(10, 14) => [] */ public List<Integer> generateIntegers(int a, int b) {
int lower = Math.max(2, Math.min(a, b)); int upper = Math.min(8, Math.max(a, b)); List<Integer> result = new ArrayList<>(); for (int i = lower; i <= upper; i += 2) { result.add(i); } return result; } }
java
THUDM/humaneval-x
/* Check if in given vector 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 */ #include<stdio.h> #include<vector> #include<math.h> using namespace std; bool has_close_elements(vector<float> numbers, float threshold){
int i,j; for (i=0;i<numbers.size();i++) for (j=i+1;j<numbers.size();j++) if (abs(numbers[i]-numbers[j])<threshold) return true; return false; }
cpp
THUDM/humaneval-x
/* 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 vector of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups("( ) (( )) (( )( ))") {"()", "(())", "(()())"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> separate_paren_groups(string paren_string){
vector<string> all_parens; string current_paren; int level=0; char chr; int i; for (i=0;i<paren_string.length();i++) { chr=paren_string[i]; if (chr=='(') { level+=1; current_paren+=chr; } if (chr==')') { level-=1; current_paren+=chr; if (level==0){ all_parens.push_back(current_paren); current_paren=""; } } } return all_parens; }
cpp
THUDM/humaneval-x
/* Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5 */ #include<stdio.h> #include<math.h> using namespace std; float truncate_number(float number){
return number-int(number); }
cpp
THUDM/humaneval-x
/* You"re given a vector 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 falls below zero, and at that point function should return true. Otherwise it should return false. >>> below_zero({1, 2, 3}) false >>> below_zero({1, 2, -4, 5}) true */ #include<stdio.h> #include<vector> using namespace std; bool below_zero(vector<int> operations){
int num=0; for (int i=0;i<operations.size();i++) { num+=operations[i]; if (num<0) return true; } return false; }
cpp
THUDM/humaneval-x
/* For a given vector 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 */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; float mean_absolute_deviation(vector<float> numbers){
float sum=0; float avg,msum,mavg; int i=0; for (i=0;i<numbers.size();i++) sum+=numbers[i]; avg=sum/numbers.size(); msum=0; for (i=0;i<numbers.size();i++) msum+=abs(numbers[i]-avg); return msum/numbers.size(); }
cpp
THUDM/humaneval-x
/* Insert a number "delimeter" between every two consecutive elements of input vector `numbers" >>> intersperse({}, 4) {} >>> intersperse({1, 2, 3}, 4) {1, 4, 2, 4, 3} */ #include<stdio.h> #include<vector> using namespace std; vector<int> intersperse(vector<int> numbers, int delimeter){
vector<int> out={}; if (numbers.size()>0) out.push_back(numbers[0]); for (int i=1;i<numbers.size();i++) { out.push_back(delimeter); out.push_back(numbers[i]); } return out; }
cpp
THUDM/humaneval-x
/* 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} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<int> parse_nested_parens(string paren_string){
vector<int> all_levels; string current_paren; int level=0,max_level=0; char chr; int i; for (i=0;i<paren_string.length();i++) { chr=paren_string[i]; if (chr=='(') { level+=1; if (level>max_level) max_level=level; current_paren+=chr; } if (chr==')') { level-=1; current_paren+=chr; if (level==0){ all_levels.push_back(max_level); current_paren=""; max_level=0; } } } return all_levels; }
cpp
THUDM/humaneval-x
/* Filter an input vector of strings only for ones that contain given substring >>> filter_by_substring({}, "a") {} >>> filter_by_substring({"abc", "bacd", "cde", "vector"}, "a") {"abc", "bacd", "vector"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> filter_by_substring(vector<string> strings, string substring){
vector<string> out; for (int i=0;i<strings.size();i++) { if (strings[i].find(substring)!=strings[i].npos) out.push_back(strings[i]); } return out; }
cpp
THUDM/humaneval-x
/* For a given vector of integers, return a vector consisting of a sum and a product of all the integers in a vector. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product({}) (0, 1) >>> sum_product({1, 2, 3, 4}) (10, 24) */ #include<stdio.h> #include<vector> using namespace std; vector<int> sum_product(vector<int> numbers){
int sum=0,product=1; for (int i=0;i<numbers.size();i++) { sum+=numbers[i]; product*=numbers[i]; } return {sum,product}; }
cpp
THUDM/humaneval-x
/* From a given vector of integers, generate a vector 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} */ #include<stdio.h> #include<vector> using namespace std; vector<int> rolling_max(vector<int> numbers){
vector<int> out; int max=0; for (int i=0;i<numbers.size();i++) { if (numbers[i]>max) max=numbers[i]; out.push_back(max); } return out; }
cpp
THUDM/humaneval-x
#include<stdio.h> #include<string> using namespace std; bool is_palindrome(string str){ //Test if given string is a palindrome string s(str.rbegin(),str.rend()); return s==str; } string make_palindrome(string str){ /* Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome("") "" >>> make_palindrome("cat") "catac" >>> make_palindrome("cata") "catac" */
int i; for (i=0;i<str.length();i++) { string rstr=str.substr(i); if (is_palindrome(rstr)) { string nstr; nstr=str.substr(0,i); string n2str(nstr.rbegin(),nstr.rend()); return str+n2str; } } string n2str(str.rbegin(),str.rend()); return str+n2str; }
cpp
THUDM/humaneval-x
/* Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor("010", "110") "100" */ #include<stdio.h> #include<string> using namespace std; string string_xor(string a,string b){
string output=""; for (int i=0;(i<a.length() and i<b.length());i++) { if (i<a.length() and i<b.length()) { if (a[i]== b[i]) { output+='0'; } else output+='1'; } else { if (i>=a.length()) { output+=b[i]; } else output+=a[i]; } } return output; }
cpp
THUDM/humaneval-x
/* Out of vector of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input vector is empty. >>> longest({}) >>> longest({"a", "b", "c"}) "a" >>> longest({"a", "bb", "ccc"}) "ccc" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string longest(vector<string> strings){
string out; for (int i=0;i<strings.size();i++) { if (strings[i].length()>out.length()) out=strings[i]; } return out; }
cpp
THUDM/humaneval-x
/* Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 */ #include<stdio.h> using namespace std; int greatest_common_divisor(int a, int b){
int out,m; while (true){ if (a<b) { m=a;a=b;b=m; } a=a%b; if (a==0) return b; } }
cpp
THUDM/humaneval-x
/* Return vector of all prefixes from shortest to longest of the input string >>> all_prefixes("abc") {"a", "ab", "abc"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> all_prefixes(string str){
vector<string> out; string current=""; for (int i=0;i<str.length();i++) { current=current+str[i]; out.push_back(current); } return out; }
cpp
THUDM/humaneval-x
/* Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) "0" >>> string_sequence(5) "0 1 2 3 4 5" */ #include<stdio.h> #include<string> using namespace std; string string_sequence(int n){
string out="0"; for (int i=1;i<=n;i++) out=out+" "+to_string(i); return out; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> #include<vector> #include<string> #include<algorithm> using namespace std; int count_distinct_characters(string str){
vector<char> distinct={}; transform(str.begin(),str.end(),str.begin(),::tolower); for (int i=0;i<str.size();i++) { bool isin=false; for (int j=0;j<distinct.size();j++) if (distinct[j]==str[i]) isin=true; if (isin==false) distinct.push_back(str[i]); } return distinct.size(); }
cpp
THUDM/humaneval-x
/* Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return vector 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} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<int> parse_music(string music_string){
string current=""; vector<int> out={}; if (music_string.length()>0) music_string=music_string+' '; for (int i=0;i<music_string.length();i++) { if (music_string[i]==' ') { if (current=="o") out.push_back(4); if (current=="o|") out.push_back(2); if (current==".|") out.push_back(1); current=""; } else current+=music_string[i]; } return out; }
cpp
THUDM/humaneval-x
/* Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times("", "a") 0 >>> how_many_times("aaa", "a") 3 >>> how_many_times("aaaa", "aa") 3 */ #include<stdio.h> #include<string> using namespace std; int how_many_times(string str,string substring){
int out=0; if (str.length()==0) return 0; for (int i=0;i<=str.length()-substring.length();i++) if (str.substr(i,substring.length())==substring) out+=1; return out; }
cpp
THUDM/humaneval-x
/* Input is a space-delimited string of numberals from "zero" to "nine". Valid choices are "zero", "one", 'two", 'three", "four", "five", 'six", 'seven", "eight" and "nine". Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five") "one three five" */ #include<stdio.h> #include<string> #include<map> using namespace std; string sort_numbers(string numbers){
map<string,int> tonum={{"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},{"five",5},{"six",6},{"seven",7},{"eight",8},{"nine",9}}; map<int,string> numto={{0,"zero"},{1,"one"},{2,"two"},{3,"three"},{4,"four"},{5,"five"},{6,"six"},{7,"seven"},{8,"eight"},{9,"nine"}}; int count[10]; for (int i=0;i<10;i++) count[i]=0; string out="",current=""; if (numbers.length()>0) numbers=numbers+' '; for (int i=0;i<numbers.length();i++) if (numbers[i]==' ') { count[tonum[current]]+=1; current=""; } else current+=numbers[i]; for (int i=0;i<10;i++) for (int j=0;j<count[i];j++) out=out+numto[i]+' '; if (out.length()>0) out.pop_back(); return out; }
cpp
THUDM/humaneval-x
/* From a supplied vector of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements({1.0, 2.0, 3.0, 4.0, 5.0, 2.2}) (2.0, 2.2) >>> find_closest_elements({1.0, 2.0, 3.0, 4.0, 5.0, 2.0}) (2.0, 2.0) */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; vector<float> find_closest_elements(vector<float> numbers){
vector<float> out={}; for (int i=0;i<numbers.size();i++) for (int j=i+1;j<numbers.size();j++) if (out.size()==0 or abs(numbers[i]-numbers[j])<abs(out[0]-out[1])) out={numbers[i],numbers[j]}; if (out[0]>out[1]) out={out[1],out[0]}; return out; }
cpp
THUDM/humaneval-x
/* Given vector of numbers (of at least two elements), apply a linear transform to that vector, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit({1.0, 2.0, 3.0, 4.0, 5.0}) {0.0, 0.25, 0.5, 0.75, 1.0} */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; vector<float> rescale_to_unit(vector<float> numbers){
float min=100000,max=-100000; for (int i=0;i<numbers.size();i++) { if (numbers[i]<min) min=numbers[i]; if (numbers[i]>max) max=numbers[i]; } for (int i=0;i<numbers.size();i++) numbers[i]=(numbers[i]-min)/(max-min); return numbers; }
cpp
THUDM/humaneval-x
/* Filter given vector of any python values only for integers >>> filter_integers({"a", 3.14, 5}) {5} >>> filter_integers({1, 2, 3, "abc", {}, {}}) {1, 2, 3} */ #include<stdio.h> #include<vector> #include<string> #include<boost/any.hpp> #include<list> typedef std::list<boost::any> list_any; using namespace std; vector<int> filter_integers(list_any values){
list_any::iterator it; boost::any anyone; vector<int> out; for (it=values.begin();it!=values.end();it++) { anyone=*it; if( anyone.type() == typeid(int) ) out.push_back(boost::any_cast<int>(*it)); } return out; }
cpp
THUDM/humaneval-x
/* Return length of given string >>> strlen("") 0 >>> strlen("abc") 3 */ #include<stdio.h> #include<string> using namespace std; int strlen(string str){
return str.length(); }
cpp
THUDM/humaneval-x
/* For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 */ #include<stdio.h> using namespace std; int largest_divisor(int n){
for (int i=2;i*i<=n;i++) if (n%i==0) return n/i; return 1; }
cpp
THUDM/humaneval-x
/* Return vector of prime factors of given integer in the order from smallest to largest. Each of the factors should be vectored number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) {2, 2, 2} >>> factorize(25) {5, 5} >>> factorize(70) {2, 5, 7} */ #include<stdio.h> #include<vector> using namespace std; vector<int> factorize(int n){
vector<int> out={}; for (int i=2;i*i<=n;i++) if (n%i==0) { n=n/i; out.push_back(i); i-=1; } out.push_back(n); return out; }
cpp
THUDM/humaneval-x
/* From a vector of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates({1, 2, 3, 2, 4}) {1, 3, 4} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> remove_duplicates(vector<int> numbers){
vector<int> out={}; vector<int> has1={}; vector<int> has2={}; for (int i=0;i<numbers.size();i++) { if (find(has2.begin(),has2.end(),numbers[i])!=has2.end()) continue; if (find(has1.begin(),has1.end(),numbers[i])!=has1.end()) { has2.push_back(numbers[i]); } else has1.push_back(numbers[i]); } for (int i=0;i<numbers.size();i++) if (find(has2.begin(),has2.end(),numbers[i])==has2.end()) out.push_back(numbers[i]); return out; }
cpp
THUDM/humaneval-x
/* For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case("Hello") "hELLO" */ #include<stdio.h> #include<string> using namespace std; string filp_case(string str){
string out=""; for (int i=0;i<str.length();i++) { char w=str[i]; if (w>=97 and w<=122) {w-=32;} else if (w>=65 and w<=90){ w+=32;} out=out+w; } return out; }
cpp
THUDM/humaneval-x
/* Concatenate vector of strings into a single string >>> concatenate({}) "" >>> concatenate({"a", "b", "c"}) "abc" */ #include<stdio.h> #include<vector> #include<string> using namespace std; string concatenate(vector<string> strings){
string out=""; for (int i=0;i<strings.size();i++) out=out+strings[i]; return out; }
cpp
THUDM/humaneval-x
/* Filter an input vector of strings only for ones that start with a given prefix. >>> filter_by_prefix({}, "a") {} >>> filter_by_prefix({"abc", "bcd", "cde", "vector"}, "a") {"abc", "vector"} */ #include<stdio.h> #include<vector> #include<string> using namespace std; vector<string> filter_by_prefix(vector<string> strings, string prefix){
vector<string> out={}; for (int i=0;i<strings.size();i++) if (strings[i].substr(0,prefix.length())==prefix) out.push_back(strings[i]); return out; }
cpp
THUDM/humaneval-x
/* Return only positive numbers in the vector. >>> get_positive({-1, 2, -4, 5, 6}) {2, 5, 6} >>> get_positive({5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10}) {5, 3, 2, 3, 9, 123, 1} */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; vector<float> get_positive(vector<float> l){
vector<float> out={}; for (int i=0;i<l.size();i++) if (l[i]>0) out.push_back(l[i]); return out; }
cpp
THUDM/humaneval-x
/* Return true if a given number is prime, and false otherwise. >>> is_prime(6) false >>> is_prime(101) true >>> is_prime(11) true >>> is_prime(13441) true >>> is_prime(61) true >>> is_prime(4) false >>> is_prime(1) false */ #include<stdio.h> using namespace std; bool is_prime(long long n){
if (n<2) return false; for (long long i=2;i*i<=n;i++) if (n%i==0) return false; return true; }
cpp
THUDM/humaneval-x
#include<stdio.h> #include<math.h> #include<vector> using namespace std; double poly(vector<double> xs, double x){ /* Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n */ double sum=0; int i; for (i=0;i<xs.size();i++) { sum+=xs[i]*pow(x,i); } return sum; } double find_zero(vector<double> xs){ /* xs are coefficients of a polynomial. find_zero find x such that poly(x) = 0. find_zero returns only only zero point, even if there are many. Moreover, find_zero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. >>> round(find_zero([1, 2]), 2) #f(x) = 1 + 2x -0.5 >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3 1.0 */
double ans=0; double value; value=poly(xs,ans); while (abs(value)>1e-6) { double driv=0; for (int i=1;i<xs.size();i++) { driv+=xs[i]*pow(ans,i-1)*i; } ans=ans-value/driv; value=poly(xs,ans); } return ans; }
cpp
THUDM/humaneval-x
/* This function takes a vector l and returns a vector l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third({1, 2, 3}) {1, 2, 3} >>> sort_third({5, 6, 3, 4, 8, 9, 2}) {2, 6, 3, 4, 8, 9, 5} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> sort_third(vector<int> l){
vector<int> third={}; int i; for (i=0;i*3<l.size();i++) third.push_back(l[i*3]); sort(third.begin(),third.end()); vector<int> out={}; for (i=0;i<l.size();i++) { if (i%3==0) {out.push_back(third[i/3]);} else out.push_back(l[i]); } return out; }
cpp
THUDM/humaneval-x
/* Return sorted unique elements in a vector >>> unique({5, 3, 5, 2, 3, 3, 9, 0, 123}) {0, 2, 3, 5, 9, 123} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> unique(vector<int> l){
vector<int> out={}; for (int i=0;i<l.size();i++) if (find(out.begin(),out.end(),l[i])==out.end()) out.push_back(l[i]); sort(out.begin(),out.end()); return out; }
cpp
THUDM/humaneval-x
/* Return maximum element in the vector. >>> max_element({1, 2, 3}) 3 >>> max_element({5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10}) 123 */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; float max_element(vector<float> l){
float max=-10000; for (int i=0;i<l.size();i++) if (max<l[i]) max=l[i]; return max; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> using namespace std; int fizz_buzz(int n){
int count=0; for (int i=0;i<n;i++) if (i%11==0 or i%13==0) { int q=i; while (q>0) { if (q%10==7) count+=1; q=q/10; } } return count; }
cpp
THUDM/humaneval-x
/* This function takes a vector l and returns a vector l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even({1, 2, 3}) {1, 2, 3} >>> sort_even({5, 6, 3, 4}) {3, 6, 5, 4} */ #include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; vector<float> sort_even(vector<float> l){
vector<float> out={}; vector<float> even={}; for (int i=0;i*2<l.size();i++) even.push_back(l[i*2]); sort(even.begin(),even.end()); for (int i=0;i<l.size();i++) { if (i%2==0) out.push_back(even[i/2]); if (i%2==1) out.push_back(l[i]); } return out; }
cpp
THUDM/humaneval-x
#include<stdio.h> #include<string> using namespace std; string encode_cyclic(string s){ // returns encoded string by cycling groups of three characters. // split string to groups. Each of length 3. int l=s.length(); int num=(l+2)/3; string x,output; int i; for (i=0;i*3<l;i++) { //cycle elements in each group. Unless group has fewer elements than 3. x=s.substr(i*3,3); if (x.length()==3) x=x.substr(1)+x[0]; output=output+x; } return output; } string decode_cyclic(string s){ /* takes as input string encoded with encode_cyclic function. Returns decoded string. */
int l=s.length(); int num=(l+2)/3; string x,output; int i; for (i=0;i*3<l;i++) { x=s.substr(i*3,3); if (x.length()==3) x=x[2]+x.substr(0,2); output=output+x; } return output; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> using namespace std; int prime_fib(int n){
int f1,f2,m; f1=1;f2=2; int count=0; while (count<n) { f1=f1+f2; m=f1;f1=f2;f2=m; bool isprime=true; for (int w=2;w*w<=f1;w++) if (f1%w==0) { isprime=false; break; } if (isprime) count+=1; if (count==n) return f1; } }
cpp
THUDM/humaneval-x
/* triples_sum_to_zero takes a vector of integers as an input. it returns true if there are three distinct elements in the vector that sum to zero, and false otherwise. >>> triples_sum_to_zero({1, 3, 5, 0}) false >>> triples_sum_to_zero({1, 3, -2, 1}) true >>> triples_sum_to_zero({1, 2, 3, 7}) false >>> triples_sum_to_zero({2, 4, -5, 3, 9, 7}) true >>> triples_sum_to_zero({1}) false */ #include<stdio.h> #include<vector> using namespace std; bool triples_sum_to_zero(vector<int> l){
for (int i=0;i<l.size();i++) for (int j=i+1;j<l.size();j++) for (int k=j+1;k<l.size();k++) if (l[i]+l[j]+l[k]==0) return true; return false; }
cpp
THUDM/humaneval-x
/* 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. */ #include<stdio.h> using namespace std; int car_race_collision(int n){
return n*n; }
cpp
THUDM/humaneval-x
/* Return vector with elements incremented by 1. >>> incr_vector({1, 2, 3}) {2, 3, 4} >>> incr_vector({5, 3, 5, 2, 3, 3, 9, 0, 123}) {6, 4, 6, 3, 4, 4, 10, 1, 124} */ #include<stdio.h> #include<vector> using namespace std; vector<int> incr_list(vector<int> l){
for (int i=0;i<l.size();i++) l[i]+=1; return l; }
cpp
THUDM/humaneval-x
/* pairs_sum_to_zero takes a vector of integers as an input. it returns true if there are two distinct elements in the vector that sum to zero, and false otherwise. >>> pairs_sum_to_zero({1, 3, 5, 0}) false >>> pairs_sum_to_zero({1, 3, -2, 1}) false >>> pairs_sum_to_zero({1, 2, 3, 7}) false >>> pairs_sum_to_zero({2, 4, -5, 3, 5, 7}) true >>> pairs_sum_to_zero({1}) false */ #include<stdio.h> #include<vector> using namespace std; bool pairs_sum_to_zero(vector<int> l){
for (int i=0;i<l.size();i++) for (int j=i+1;j<l.size();j++) if (l[i]+l[j]==0) return true; return false; }
cpp
THUDM/humaneval-x
/* Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) "22" >>> change_base(8, 2) "1000" >>> change_base(7, 2) "111" */ #include<stdio.h> #include<string> using namespace std; string change_base(int x,int base){
string out=""; while (x>0) { out=to_string(x%base)+out; x=x/base; } return out; }
cpp
THUDM/humaneval-x
/* Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 */ #include<stdio.h> #include<math.h> using namespace std; float triangle_area(float a,float h){
return (a*h)*0.5; }
cpp
THUDM/humaneval-x
/* The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 */ #include<stdio.h> using namespace std; int fib4(int n){
int f[100]; f[0]=0; f[1]=0; f[2]=2; f[3]=0; for (int i=4;i<=n;i++) { f[i]=f[i-1]+f[i-2]+f[i-3]+f[i-4]; } return f[n]; }
cpp
THUDM/humaneval-x
/* Return median of elements in the vector l. >>> median({3, 1, 2, 4, 5}) 3 >>> median({-10, 4, 6, 1000, 10, 20}) 15.0 */ #include<stdio.h> #include<math.h> #include<vector> #include<algorithm> using namespace std; float median(vector<float> l){
sort(l.begin(),l.end()); if (l.size()%2==1) return l[l.size()/2]; return 0.5*(l[l.size()/2]+l[l.size()/2-1]); }
cpp
THUDM/humaneval-x
/* Checks if given string is a palindrome >>> is_palindrome("") true >>> is_palindrome("aba") true >>> is_palindrome("aaaaa") true >>> is_palindrome("zbcd") false */ #include<stdio.h> #include<string> using namespace std; bool is_palindrome(string text){
string pr(text.rbegin(),text.rend()); return pr==text; }
cpp
THUDM/humaneval-x
/* Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 */ #include<stdio.h> using namespace std; int modp(int n,int p){
int out=1; for (int i=0;i<n;i++) out=(out*2)%p; return out; }
cpp
THUDM/humaneval-x
#include<stdio.h> #include<string> using namespace std; string encode_shift(string s){ // returns encoded string by shifting every character by 5 in the alphabet. string out; int i; for (i=0;i<s.length();i++) { int w=((int)s[i]+5-(int)'a')%26+(int)'a'; out=out+(char)w; } return out; } string decode_shift(string s){ // takes as input string encoded with encode_shift function. Returns decoded string.
string out; int i; for (i=0;i<s.length();i++) { int w=((int)s[i]+21-(int)'a')%26+(int)'a'; out=out+(char)w; } return out; }
cpp
THUDM/humaneval-x
/* remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels("") "" >>> remove_vowels("abcdef\nghijklm") "bcdf\nghjklm" >>> remove_vowels("abcdef") "bcdf" >>> remove_vowels("aaaaa") "" >>> remove_vowels("aaBAA") "B" >>> remove_vowels("zbcd") "zbcd" */ #include<stdio.h> #include<string> #include<algorithm> using namespace std; string remove_vowels(string text){
string out=""; string vowels="AEIOUaeiou"; for (int i=0;i<text.length();i++) if (find(vowels.begin(),vowels.end(),text[i])==vowels.end()) out=out+text[i]; return out; }
cpp
THUDM/humaneval-x
/* Return true if all numbers in the vector l are below threshold t. >>> below_threshold({1, 2, 4, 10}, 100) true >>> below_threshold({1, 20, 4, 10}, 5) false */ #include<stdio.h> #include<vector> using namespace std; bool below_threshold(vector<int>l, int t){
for (int i=0;i<l.size();i++) if (l[i]>=t) return false; return true; }
cpp
THUDM/humaneval-x
/* Add two numbers x and y >>> add(2, 3) 5 >>> add(5, 7) 12 */ #include<stdio.h> #include<stdlib.h> using namespace std; int add(int x,int y){
return x+y; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> #include<string> #include<algorithm> using namespace std; bool same_chars(string s0,string s1){
for (int i=0;i<s0.length();i++) if (find(s1.begin(),s1.end(),s0[i])==s1.end()) return false; for (int i=0;i<s1.length();i++) if (find(s0.begin(),s0.end(),s1[i])==s0.end()) return false; return true; }
cpp
THUDM/humaneval-x
/* Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 */ #include<stdio.h> using namespace std; int fib(int n){
int f[1000]; f[0]=0;f[1]=1; for (int i=2;i<=n; i++) f[i]=f[i-1]+f[i-2]; return f[n]; }
cpp
THUDM/humaneval-x
/* brackets is a string of '<' and '>'. return true if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("<") false >>> correct_bracketing("<>") true >>> correct_bracketing("<<><>>") true >>> correct_bracketing("><<>") false */ #include<stdio.h> #include<string> using namespace std; bool correct_bracketing(string brackets){
int level=0; for (int i=0;i<brackets.length();i++) { if (brackets[i]=='<') level+=1; if (brackets[i]=='>') level-=1; if (level<0) return false; } if (level!=0) return false; return true; }
cpp
THUDM/humaneval-x
/* Return true is vector elements are monotonically increasing or decreasing. >>> monotonic({1, 2, 4, 20}) true >>> monotonic({1, 20, 4, 10}) false >>> monotonic({4, 1, 0, -10}) true */ #include<stdio.h> #include<vector> using namespace std; bool monotonic(vector<float> l){
int incr,decr; incr=0;decr=0; for (int i=1;i<l.size();i++) { if (l[i]>l[i-1]) incr=1; if (l[i]<l[i-1]) decr=1; } if (incr+decr==2) return false; return true; }
cpp
THUDM/humaneval-x
/* Return sorted unique common elements for two vectors. >>> common({1, 4, 3, 34, 653, 2, 5}, {5, 7, 1, 5, 9, 653, 121}) {1, 5, 653} >>> common({5, 3, 2, 8}, {3, 2}) {2, 3} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> common(vector<int> l1,vector<int> l2){
vector<int> out={}; for (int i=0;i<l1.size();i++) if (find(out.begin(),out.end(),l1[i])==out.end()) if (find(l2.begin(),l2.end(),l1[i])!=l2.end()) out.push_back(l1[i]); sort(out.begin(),out.end()); return out; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> using namespace std; int largest_prime_factor(int n){
for (int i=2;i*i<=n;i++) while (n%i==0 and n>i) n=n/i; return n; }
cpp
THUDM/humaneval-x
/* sum_to_n is a function that sums numbers from 1 to n. >>> sum_to_n(30) 465 >>> sum_to_n(100) 5050 >>> sum_to_n(5) 15 >>> sum_to_n(10) 55 >>> sum_to_n(1) 1 */ #include<stdio.h> using namespace std; int sum_to_n(int n){
return n*(n+1)/2; }
cpp
THUDM/humaneval-x
/* brackets is a string of '(' and ')'. return true if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("(") false >>> correct_bracketing("()") true >>> correct_bracketing("(()())") true >>> correct_bracketing(")(()") false */ #include<stdio.h> #include<string> using namespace std; bool correct_bracketing(string brackets){
int level=0; for (int i=0;i<brackets.length();i++) { if (brackets[i]=='(') level+=1; if (brackets[i]==')') level-=1; if (level<0) return false; } if (level!=0) return false; return true; }
cpp
THUDM/humaneval-x
/* 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({3, 1, 2, 4, 5}) {1, 4, 12, 20} >>> derivative({1, 2, 3}) {2, 6} */ #include<stdio.h> #include<math.h> #include<vector> using namespace std; vector<float> derivative(vector<float> xs){
vector<float> out={}; for (int i=1;i<xs.size();i++) out.push_back(i*xs[i]); return out; }
cpp
THUDM/humaneval-x
/* The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Please write a function to efficiently compute the n-th element of the fibfib number sequence. >>> fibfib(1) 0 >>> fibfib(5) 4 >>> fibfib(8) 24 */ #include<stdio.h> using namespace std; int fibfib(int n){
int ff[100]; ff[0]=0; ff[1]=0; ff[2]=1; for (int i=3;i<=n;i++) ff[i]=ff[i-1]+ff[i-2]+ff[i-3]; return ff[n]; }
cpp
THUDM/humaneval-x
/* 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 */ #include<stdio.h> #include<string> #include<algorithm> using namespace std; int vowels_count(string s){
string vowels="aeiouAEIOU"; int count=0; for (int i=0;i<s.length();i++) if (find(vowels.begin(),vowels.end(),s[i])!=vowels.end()) count+=1; if (s[s.length()-1]=='y' or s[s.length()-1]=='Y') count+=1; return count; }
cpp
THUDM/humaneval-x
/* Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" */ #include<stdio.h> #include<string> using namespace std; string circular_shift(int x,int shift){
string xs; xs=to_string(x); if (xs.length()<shift) { string s(xs.rbegin(),xs.rend()); return s; } xs=xs.substr(xs.length()-shift)+xs.substr(0,xs.length()-shift); return xs; }
cpp
THUDM/humaneval-x
/* Task Write a function that takes a string as input and returns the sum of the upper characters only's ASCII codes. Examples: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153 */ #include<stdio.h> #include<string> using namespace std; int digitSum(string s){
int sum=0; for (int i=0;i<s.length();i++) if (s[i]>=65 and s[i]<=90) sum+=s[i]; return sum; }
cpp
THUDM/humaneval-x
/* In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for example: fruit_distribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruit_distribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruit_distribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruit_distribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 */ #include<stdio.h> #include<string> using namespace std; int fruit_distribution(string s,int n){
string num1="",num2=""; int is12; is12=0; for (int i=0;i<s.size();i++) if (s[i]>=48 and s[i]<=57) { if (is12==0) num1=num1+s[i]; if (is12==1) num2=num2+s[i]; } else if (is12==0 and num1.length()>0) is12=1; return n-atoi(num1.c_str())-atoi(num2.c_str()); }
cpp
THUDM/humaneval-x
/* Given a vector representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a vector, { smalest_value, its index }, If there are no even values or the given vector is empty, return {}. Example 1: Input: {4,2,3} Output: {2, 1} Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: Input: {1,2,3} Output: {2, 1} Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: Input: {} Output: {} Example 4: Input: {5, 0, 3, 0, 4, 2} Output: {0, 1} Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value */ #include<stdio.h> #include<vector> using namespace std; vector<int> pluck(vector<int> arr){
vector<int> out={}; for (int i=0;i<arr.size();i++) if (arr[i]%2==0 and (out.size()==0 or arr[i]<out[0])) out={arr[i],i}; return out; }
cpp
THUDM/humaneval-x
/* You are given a non-empty vector 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 vector. 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 */ #include<stdio.h> #include<vector> using namespace std; int search(vector<int> lst){
vector<vector<int>> freq={}; int max=-1; for (int i=0;i<lst.size();i++) { bool has=false; for (int j=0;j<freq.size();j++) if (lst[i]==freq[j][0]) { freq[j][1]+=1; has=true; if (freq[j][1]>=freq[j][0] and freq[j][0]>max) max=freq[j][0]; } if (not(has)) { freq.push_back({lst[i],1}); if (max==-1 and lst[i]==1) max=1; } } return max; }
cpp
THUDM/humaneval-x
/* Given vector of integers, return vector 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_vector({1, 2, 3, 4}) == {1, 4, 2, 3} strange_sort_vector({5, 5, 5, 5}) == {5, 5, 5, 5} strange_sort_vector({}) == {} */ #include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> strange_sort_list(vector<int> lst){
vector<int> out={}; sort(lst.begin(),lst.end()); int l=0,r=lst.size()-1; while (l<r) { out.push_back(lst[l]); l+=1; out.push_back(lst[r]); r-=1; } if (l==r) out.push_back(lst[l]); return out; }
cpp
THUDM/humaneval-x
/* Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangle_area(3, 4, 5) == 6.00 triangle_area(1, 2, 10) == -1 */ #include<stdio.h> #include<math.h> using namespace std; float triangle_area(float a,float b,float c){
if (a+b<=c or a+c<=b or b+c<=a) return -1; float h=(a+b+c)/2; float area; area=pow(h*(h-a)*(h-b)*(h-c),0.5); return area; }
cpp
THUDM/humaneval-x