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 { /** Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizzBuzz(50) 0 >>> fizzBuzz(78) 2 >>> fizzBuzz(79) 3 */ public int fizzBuzz(int n) {
int result = 0; for (int i = 1; i < n; i++) { if (i % 11 == 0 || i % 13 == 0) { char[] digits = String.valueOf(i).toCharArray(); for (char c : digits) { if (c == '7') { result += 1; } } } } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sortEven(Arrays.asList(1, 2, 3)) [1, 2, 3] >>> sortEven(Arrays.asList(5, 6, 3, 4)) [3, 6, 5, 4] */ public List<Integer> sortEven(List<Integer> l) {
List<Integer> even = new ArrayList<>(); for (int i = 0; i < l.size(); i += 2) { even.add(l.get(i)); } Collections.sort(even); List<Integer> result = l; for (int i = 0; i < l.size(); i += 2) { result.set(i, even.get(i / 2)); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** returns encoded string by cycling groups of three characters. */ public String encodeCyclic(String s) { // split string to groups. Each of length 3. List<String> groups = new ArrayList<>(); for (int i = 0; i < s.length(); i += 3) { groups.add(s.substring(i, Math.min(i + 3, s.length()))); } // cycle elements in each group. Unless group has fewer elements than 3. for (int i = 0; i < groups.size(); i++) { if (groups.get(i).length() == 3) { groups.set(i, groups.get(i).substring(1) + groups.get(i).charAt(0)); } } return String.join("", groups); } /** takes as input string encoded with encodeCyclic function. Returns decoded string. */ public String decodeCyclic(String s) {
return encodeCyclic(encodeCyclic(s)); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** primeFib returns n-th number that is a Fibonacci number and it's also prime. >>> primeFib(1) 2 >>> primeFib(2) 3 >>> primeFib(3) 5 >>> primeFib(4) 13 >>> primeFib(5) 89 */ public int primeFib(int n) {
int f0 = 0, f1 = 1; while (true) { int p = f0 + f1; boolean is_prime = p >= 2; for (int k = 2; k < Math.min(Math.sqrt(p) + 1, p - 1); k++) { if (p % k == 0) { is_prime = false; break; } } if (is_prime) { n -= 1; } if (n == 0) { return p; } f0 = f1; f1 = p; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** triplesSumToZero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triplesSumToZero(Arrays.asList(1, 3, 5, 0)) false >>> triplesSumToZero(Arrays.asList(1, 3, -2, 1)) true >>> triplesSumToZero(Arrays.asList(1, 2, 3, 7)) false >>> triplesSumToZero(Arrays.asList(2, 4, -5, 3, 9, 7)) true >>> triplesSumToZero(Arrays.asList(1)) false */ public boolean triplesSumToZero(List<Integer> 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.get(i) + l.get(j) + l.get(k) == 0) { return true; } } } } return false; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. */ public int carRaceCollision(int n) {
return n * n; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; import java.util.stream.Collectors; class Solution { /** Return list with elements incremented by 1. >>> incrList(Arrays.asList(1, 2, 3)) [2, 3, 4] >>> incrList(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123)) [6, 4, 6, 3, 4, 4, 10, 1, 124] */ public List<Integer> incrList(List<Integer> l) {
return l.stream().map(p -> p + 1).collect(Collectors.toList()); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** pairsSumToZero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairsSumToZero(Arrays.asList(1, 3, 5, 0)) false >>> pairsSumToZero(Arrays.asList(1, 3, -2, 1)) false >>> pairsSumToZero(Arrays.asList(1, 2, 3, 7)) false >>> pairsSumToZero(Arrays.asList(2, 4, -5, 3, 5, 7)) true >>> pairsSumToZero(Arrays.asList(1)) false */ public boolean pairsSumToZero(List<Integer> 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; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> changeBase(8, 3) "22" >>> changeBase(8, 2) "1000" >>> changeBase(7, 2) "111" */ public String changeBase(int x, int base) {
StringBuilder ret = new StringBuilder(); while (x > 0) { ret.append(String.valueOf(x % base)); x /= base; } return ret.reverse().toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given length of a side and high return area for a triangle. >>> triangleArea(5, 3) 7.5 */ public double triangleArea(double a, double h) {
return a * h / 2; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public int fib4(int n) {
List<Integer> results = new ArrayList<>(); results.add(0); results.add(0); results.add(2); results.add(0); if (n < 4) { return results.get(n); } for (int i = 4; i <= n; i++) { results.add(results.get(0) + results.get(1) + results.get(2) + results.get(3)); results.remove(0); } return results.get(3); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return median of elements in the list l. >>> median(Arrays.asList(3, 1, 2, 4, 5)) 3 >>> median(Arrays.asList(-10, 4, 6, 1000, 10, 20)) 15.0 */ public double median(List<Integer> l) {
List<Integer> list = l; Collections.sort(list); if (l.size() % 2 == 1) { return l.get(l.size() / 2); } else { return (l.get(l.size() / 2 - 1) + l.get(l.size() / 2)) / 2.0; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Checks if given string is a palindrome >>> isPalindrome("") true >>> isPalindrome("aba") true >>> isPalindrome("aaaaa") true >>> isPalindrome("zbcd") false */ public boolean isPalindrome(String text) {
for (int i = 0; i < text.length(); i++) { if (text.charAt(i) != text.charAt(text.length() - 1 - i)) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public int modp(int n, int p) {
int ret = 1; for (int i = 0; i < n; i++) { ret = (ret * 2) % p; } return ret; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** returns encoded string by shifting every character by 5 in the alphabet. */ public String encodeShift(String s) { StringBuilder sb = new StringBuilder(); for (char ch : s.toCharArray()) { sb.append((char) ('a' + ((ch + 5 - 'a') % 26))); } return sb.toString(); } /** takes as input string encoded with encodeShift function. Returns decoded string. */ public String decodeShift(String s) {
StringBuilder sb = new StringBuilder(); for (char ch : s.toCharArray()) { sb.append((char) ('a' + ((ch + 21 - 'a') % 26))); } return sb.toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** removeVowels is a function that takes string and returns string without vowels. >>> removeVowels("") "" >>> removeVowels("abcdef\nghijklm") "bcdf\nghjklm" >>> removeVowels("abcdef") "bcdf" >>> removeVowels("aaaaa") "" >>> removeVowels("aaBAA") "B" >>> removeVowels("zbcd") "zbcd" */ public String removeVowels(String text) {
StringBuilder sb = new StringBuilder(); for (char ch : text.toCharArray()) { if ("aeiou".indexOf(Character.toLowerCase(ch)) == -1) { sb.append(ch); } } return sb.toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return True if all numbers in the list l are below threshold t. >>> belowThreshold(Arrays.asList(1, 2, 4, 10), 100) true >>> belowThreshold(Arrays.asList(1, 20, 4, 10), 5) false */ public boolean belowThreshold(List<Integer> l, int t) {
for (int e : l) { if (e >= t) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Add two numbers x and y >>> add(2, 3) 5 >>> add(5, 7) 12 */ public int add(int x, int y) {
return x + y; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Check if two words have the same characters. >>> sameChars("eabcdzzzz", "dddzzzzzzzddeddabc") true >>> sameChars("abcd", "dddddddabc") true >>> sameChars("dddddddabc", "abcd") true >>> sameChars("eabcd", "dddddddabc") false >>> sameChars("abcd", "dddddddabce") false >>> sameChars("eabcdzzzz", "dddzzzzzzzddddabc") false */ public boolean sameChars(String s0, String s1) {
Set<Character> set0 = new HashSet<>(); for (char c : s0.toCharArray()) { set0.add(c); } Set<Character> set1 = new HashSet<>(); for (char c : s1.toCharArray()) { set1.add(c); } return set0.equals(set1); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 */ public int fib(int n) {
if (n == 0) { return 0; } if (n == 1) { return 1; } return fib(n - 1) + fib(n - 2); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correctBracketing("<") false >>> correctBracketing("<>") true >>> correctBracketing("<<><>>") true >>> correctBracketing("><<>") false */ public boolean correctBracketing(String brackets) {
int depth = 0; for (char b : brackets.toCharArray()) { if (b == '<') { depth += 1; } else { depth -= 1; } if (depth < 0) { return false; } } return depth == 0; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return True is list elements are monotonically increasing or decreasing. >>> monotonic(Arrays.asList(1, 2, 4, 20)) true >>> monotonic(Arrays.asList(1, 20, 4, 10)) false >>> monotonic(Arrays.asList(4, 1, 0, -10)) true */ public boolean monotonic(List<Integer> l) {
List<Integer> l1 = new ArrayList<>(l), l2 = new ArrayList<>(l); Collections.sort(l1); l2.sort(Collections.reverseOrder()); return l.equals(l1) || l.equals(l2); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return sorted unique common elements for two lists. >>> common(Arrays.asList(1, 4, 3, 34, 653, 2, 5), Arrays.asList(5, 7, 1, 5, 9, 653, 121)) [1, 5, 653] >>> common(Arrays.asList(5, 3, 2, 8), Arrays.asList(3, 2)) [2, 3] */ public List<Integer> common(List<Integer> l1, List<Integer> l2) {
Set<Integer> ret = new HashSet<>(l1); ret.retainAll(new HashSet<>(l2)); List<Integer> result = new ArrayList<>(ret); Collections.sort(result); return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largestPrimeFactor(13195) 29 >>> largestPrimeFactor(2048) 2 */ public int largestPrimeFactor(int n) {
int largest = 1; for (int j = 2; j <= n; j++) { if (n % j == 0) { boolean is_prime = j >= 2; for (int i = 2; i < j - 1; i++) { if (j % i == 0) { is_prime = false; break; } } if (is_prime) { largest = Math.max(largest, j); } } } return largest; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** sumToN is a function that sums numbers from 1 to n. >>> sumToN(30) 465 >>> sumToN(100) 5050 >>> sumToN(5) 15 >>> sumToN(10) 55 >>> sumToN(1) 1 */ public int sumToN(int n) {
int result = 0; for (int i = 1; i <= n; i++) { result += i; } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correctBracketing("(") false >>> correctBracketing("()") true >>> correctBracketing("(()())") true >>> correctBracketing(")(()") false */ public boolean correctBracketing(String brackets) {
int depth = 0; for (char b : brackets.toCharArray()) { if (b == '(') { depth += 1; } else { depth -= 1; } if (depth < 0) { return false; } } return depth == 0; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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(Arrays.asList(3, 1, 2, 4, 5)) [1, 4, 12, 20] >>> derivative(Arrays.asList(1, 2, 3])) [2, 6] */ public List<Integer> derivative(List<Integer> xs) {
List<Integer> result = new ArrayList<>(); for (int i = 1; i < xs.size(); i++) { result.add(i * xs.get(i)); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public int fibfib(int n) {
if (n == 0) { return 0; } if (n == 1) { return 0; } if (n == 2) { return 1; } return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function vowelsCount 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") 2 >>> vowelsCount("ACEDY") 3 */ public int vowelsCount(String s) {
String vowels = "aeiouAEIOU"; int n_vowels = 0; for (char c : s.toCharArray()) { if (vowels.indexOf(c) != -1) { n_vowels += 1; } } if (s.charAt(s.length() - 1) == 'y' || s.charAt(s.length() - 1) == 'Y') { n_vowels += 1; } return n_vowels; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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(12, 1) "21" >>> circularShift(12, 2) "12" */ public String circularShift(int x, int shift) {
String s = String.valueOf(x); if (shift > s.length()) { return new StringBuilder(s).reverse().toString(); } else { return s.substring(s.length() - shift) + s.substring(0, s.length() - shift); } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153 */ public int digitSum(String s) {
int sum = 0; for (char c : s.toCharArray()) { if (Character.isUpperCase(c)) { sum += c; } } return sum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: fruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 */ public int fruitDistribution(String s, int n) {
List<Integer> lis = new ArrayList<>(); for (String i : s.split(" ")) { try { lis.add(Integer.parseInt(i)); } catch (NumberFormatException ignored) { } } return n - lis.stream().mapToInt(Integer::intValue).sum(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array 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 */ public List<Integer> pluck(List<Integer> arr) {
List<Integer> result = new ArrayList<>(); if (arr.size() == 0) { return result; } int min = Integer.MAX_VALUE; int minIndex = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (arr.get(i) < min) { min = arr.get(i); minIndex = i; } } } if (minIndex != -1) { result.add(min); result.add(minIndex); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: search(Arrays.asList(4, 1, 2, 2, 3, 1)) == 2 search(Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4)) == 3 search(Arrays.asList(5, 5, 4, 4, 4)) == -1 */ public int search(List<Integer> lst) {
int[] frq = new int[Collections.max(lst) + 1]; for (int i : lst) { frq[i] += 1; } int ans = -1; for (int i = 1; i < frq.length; i++) { if (frq[i] >= i) { ans = i; } } return ans; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strangeSortList(Arrays.asList(1, 2, 3, 4)) == Arrays.asList(1, 4, 2, 3) strangeSortList(Arrays.asList(5, 5, 5, 5)) == Arrays.asList(5, 5, 5, 5) strangeSortList(Arrays.asList()) == Arrays.asList() */ public List<Integer> strangeSortList(List<Integer> lst) {
List<Integer> res = new ArrayList<>(); boolean _switch = true; List<Integer> l = new ArrayList<>(lst); while (l.size() != 0) { if (_switch) { res.add(Collections.min(l)); } else { res.add(Collections.max(l)); } l.remove(res.get(res.size() - 1)); _switch = !_switch; } return res; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangleArea(3, 4, 5) == 6.00 triangleArea(1, 2, 10) == -1 */ public double triangleArea(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) { return -1; } double s = (a + b + c) / 2; double area = Math.sqrt(s * (s - a) * (s - b) * (s - c)); area = (double) Math.round(area * 100) / 100; return area; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that returns True if the object q will fly, and False otherwise. The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w. Example: willItFly(Arrays.asList(1, 2), 5) -> false # 1+2 is less than the maximum possible weight, but it's unbalanced. willItFly(Arrays.asList(3, 2, 3), 1) -> false # it's balanced, but 3+2+3 is more than the maximum possible weight. willItFly(Arrays.asList(3, 2, 3), 9) -> true # 3+2+3 is less than the maximum possible weight, and it's balanced. willItFly(Arrays.asList(3), 5) -> true # 3 is less than the maximum possible weight, and it's balanced. */ public boolean willItFly(List<Integer> q, int w) {
if (q.stream().reduce(0, Integer::sum) > w) { return false; } int i = 0, j = q.size() - 1; while (i < j) { if (!Objects.equals(q.get(i), q.get(j))) { return false; } i += 1; j -= 1; } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallestChange(Arrays.asList(1,2,3,5,4,7,9,6)) == 4 smallestChange(Arrays.asList(1, 2, 3, 4, 3, 2, 2)) == 1 smallestChange(Arrays.asList(1, 2, 3, 2, 1)) == 0 */ public int smallestChange(List<Integer> arr) {
int ans = 0; for (int i = 0; i < arr.size() / 2; i++) { if (!Objects.equals(arr.get(i), arr.get(arr.size() - i - 1))) { ans += 1; } } return ans; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples totalMatch(Arrays.asList(), Arrays.asList()) -> [] totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "Hi")) -> ["hI", "Hi"] totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hi", "hi", "admin", "project")) -> ["hi", "admin"] totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "hi", "hi")) -> ["hI", "hi", "hi"] totalMatch(Arrays.asList("4"), Arrays.asList("1", "2", "3", "4", "5")) -> ["4"] */ public List<String> totalMatch(List<String> lst1, List<String> lst2) {
int l1 = 0; for (String st : lst1) { l1 += st.length(); } int l2 = 0; for (String st : lst2) { l2 += st.length(); } if (l1 <= l2) { return lst1; } else { return lst2; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: isMultiplyPrime(30) == true 30 = 2 * 3 * 5 */ public boolean isMultiplyPrime(int a) {
class IsPrime { public static boolean is_prime(int n) { for (int j = 2; j < n; j++) { if (n % j == 0) { return false; } } return true; } } for (int i = 2; i < 101; i++) { if (!IsPrime.is_prime(i)) { continue; } for (int j = i; j < 101; j++) { if (!IsPrime.is_prime(j)) { continue; } for (int k = j; k < 101; k++) { if (!IsPrime.is_prime(k)) { continue; } if (i * j * k == a) { return true; } } } } return false; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: isSimplePower(1, 4) => true isSimplePower(2, 2) => true isSimplePower(8, 2) => true isSimplePower(3, 2) => false isSimplePower(3, 1) => false isSimplePower(5, 3) => false */ public boolean isSimplePower(int x, int n) {
if (n == 1) { return x == 1; } int power = 1; while (power < x) { power = power * n; } return power == x; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public boolean iscube(int a) {
a = Math.abs(a); return Math.round(Math.pow(Math.round(Math.pow(a, 1. / 3)), 3)) == a; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number, or a prime, is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Prime numbers are 2, 3, 5, 7, 11, 13, 17,... So you have to determine a number of the following digits: 2, 3, 5, 7, B (=decimal 11), D (=decimal 13). Note: you may assume the input is always correct or empty string, and symbols A,B,C,D,E,F are always uppercase. Examples: For num = "AB" the output should be 1. For num = "1077E" the output should be 2. For num = "ABED1A33" the output should be 4. For num = "123456789ABCDEF0" the output should be 6. For num = "2020" the output should be 2. */ public int hexKey(String num) {
String primes = "2357BD"; int total = 0; for (char c : num.toCharArray()) { if (primes.indexOf(c) != -1) { total += 1; } } return total; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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(15) // returns "db1111db" decimalToBinary(32) // returns "db100000db" */ public String decimalToBinary(int decimal) {
return "db" + Integer.toBinaryString(decimal) + "db"; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct For example: isHappy(a) => false isHappy(aa) => false isHappy(abcd) => true isHappy(aabb) => false isHappy(adb) => true isHappy(xyy) => false */ public boolean isHappy(String s) {
if (s.length() < 3) { return false; } for (int i = 0; i < s.length() - 2; i++) { if (s.charAt(i) == s.charAt(i + 1) || s.charAt(i + 1) == s.charAt(i + 2) || s.charAt(i) == s.charAt(i + 2)) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: numericalLetterGrade(Arrays.asList(4.0, 3, 1.7, 2, 3.5)) ==> ["A+", "B", "C-", "C", "A-"] */ public List<String> numericalLetterGrade(List<Double> grades) {
List<String> letter_grade = new ArrayList<>(); for (double gpa : grades) { if (gpa == 4.0) { letter_grade.add("A+"); } else if (gpa > 3.7) { letter_grade.add("A"); } else if (gpa > 3.3) { letter_grade.add("A-"); } else if (gpa > 3.0) { letter_grade.add("B+"); } else if (gpa > 2.7) { letter_grade.add("B"); } else if (gpa > 2.3) { letter_grade.add("B-"); } else if (gpa > 2.0) { letter_grade.add("C+"); } else if (gpa > 1.7) { letter_grade.add("C"); } else if (gpa > 1.3) { letter_grade.add("C-"); } else if (gpa > 1.0) { letter_grade.add("D+"); } else if (gpa > 0.7) { letter_grade.add("D"); } else if (gpa > 0.0) { letter_grade.add("D-"); } else { letter_grade.add("E"); } } return letter_grade; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that takes a string and returns true if the string length is a prime number or false otherwise Examples primeLength("Hello") == true primeLength("abcdcba") == true primeLength("kittens") == true primeLength("orange") == false */ public boolean primeLength(String string) {
int l = string.length(); if (l == 0 || l == 1) { return false; } for (int i = 2; i < l; i++) { if (l % i == 0) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1. */ public int startsOneEnds(int n) {
if (n == 1) { return 1; } return 18 * (int) Math.pow(10, n - 2); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer N, return the total sum of its digits in binary. Example For N = 1000, the sum of digits will be 1 the output should be "1". For N = 150, the sum of digits will be 6 the output should be "110". For N = 147, the sum of digits will be 12 the output should be "1100". Variables: @N integer Constraints: 0 <= N <= 10000. Output: a string of binary number */ public String solve(int N) {
int sum = 0; for (char c : String.valueOf(N).toCharArray()) { sum += (c - '0'); } return Integer.toBinaryString(sum); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add(Arrays.asList(4, 2, 6, 7)) ==> 2 */ public int add(List<Integer> lst) {
int sum = 0; for (int i = 1; i < lst.size(); i += 2) { if (lst.get(i) % 2 == 0) { sum += lst.get(i); } } return sum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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") returns "Hi" antiShuffle("hello") returns "ehllo" antiShuffle("Hello World!!!") returns "Hello !!!Wdlor" */ public String antiShuffle(String s) {
String[] strings = s.split(" "); List<String> result = new ArrayList<>(); for (String string : strings) { char[] chars = string.toCharArray(); Arrays.sort(chars); result.add(String.copyValueOf(chars)); } return String.join(" ", result); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of lists, [[x1, y1], [x2, y2] ...] such that each list is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: getRow([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]] getRow([], 1) == [] getRow([[], [1], [1, 2, 3]], 3) == [[2, 2]] */ public List<List<Integer>> getRow(List<List<Integer>> lst, int x) {
List<List<Integer>> coords = new ArrayList<>(); for (int i = 0; i < lst.size(); i++) { List<List<Integer>> row = new ArrayList<>(); for (int j = lst.get(i).size() - 1; j >= 0; j--) { if (lst.get(i).get(j) == x) { row.add(Arrays.asList(i, j)); } } coords.addAll(row); } return coords; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an array of non-negative integers, return a copy of the given array after sorting, you will sort the given array in ascending order if the sum( first index value, last index value) is odd, or sort it in descending order if the sum( first index value, last index value) is even. Note: * don't change the given array. Examples: * sortArray(Arrays.asList()) => [] * sortArray(Arrays.asList(5)) => [5] * sortArray(Arrays.asList(2, 4, 3, 0, 1, 5)) => [0, 1, 2, 3, 4, 5] * sortArray(Arrays.asList(2, 4, 3, 0, 1, 5, 6)) => [6, 5, 4, 3, 2, 1, 0] */ public List<Integer> sortArray(List<Integer> array) {
if (array.size() == 0) { return array; } List<Integer> result = new ArrayList<>(array); if ((result.get(0) + result.get(result.size() - 1)) % 2 == 1) { Collections.sort(result); } else { result.sort(Collections.reverseOrder()); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. For example: encrypt("hi") returns "lm" encrypt("asdfghjkl") returns "ewhjklnop" encrypt("gf") returns "kj" encrypt("et") returns "ix" */ public String encrypt(String s) {
StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isLetter(c)) { sb.append((char) ('a' + (c - 'a' + 2 * 2) % 26)); } else { sb.append(c); } } return sb.toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a list of integers. Write a function nextSmallest() that returns the 2nd smallest element of the list. Return null if there is no such element. <p> nextSmallest(Arrays.asList(1, 2, 3, 4, 5)) == Optional[2] nextSmallest(Arrays.asList(5, 1, 4, 3, 2)) == Optional[2] nextSmallest(Arrays.asList()) == Optional.empty nextSmallest(Arrays.asList(1, 1)) == Optional.empty */ public Optional<Integer> nextSmallest(List<Integer> lst) {
Set < Integer > set = new HashSet<>(lst); List<Integer> l = new ArrayList<>(set); Collections.sort(l); if (l.size() < 2) { return Optional.empty(); } else { return Optional.of(l.get(1)); } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For example: >>> isBored("Hello world") 0 >>> isBored("The sky is blue. The sun is shining. I love this weather") 1 */ public int isBored(String S) {
String [] sentences = S.split("[.?!]\s*"); int count = 0; for (String sentence : sentences) { if (sentence.subSequence(0, 2).equals("I ")) { count += 1; } } return count; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples anyInt(5, 2, 7) -> true anyInt(3, 2, 2) -> false anyInt(3, -2, 1) -> true anyInt(3.6, -2.2, 2) -> false */ public boolean anyInt(Object x, Object y, Object z) {
if (x instanceof Integer && y instanceof Integer && z instanceof Integer) { return (int) x + (int) y == (int) z || (int) x + (int) z == (int) y || (int) y + (int) z == (int) x; } return false; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode("test") "TGST" >>> encode("This is a message") "tHKS KS C MGSSCGG" */ public String encode(String message) {
String vowels = "aeiouAEIOU"; StringBuilder sb = new StringBuilder(); for (char c : message.toCharArray()) { char ch = c; if (Character.isUpperCase(ch)) { ch = Character.toLowerCase(ch); if (vowels.indexOf(ch) != -1) { ch = (char) ('a' + ((ch - 'a' + 28) % 26)); } } else if (Character.isLowerCase(ch)) { ch = Character.toUpperCase(ch); if (vowels.indexOf(ch) != -1) { ch = (char) ('A' + ((ch - 'A' + 28) % 26)); } } sb.append(ch); } return sb.toString(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a list of integers. You need to find the largest prime value and return the sum of its digits. Examples: For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10 For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25 For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13 For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11 For lst = [0,81,12,3,1,21] the output should be 3 For lst = [0,8,1,2,1,7] the output should be 7 */ public int skjkasdkd(List<Integer> lst) {
int maxx = 0; for (int i : lst) { if (i > maxx) { boolean isPrime = i != 1; for (int j = 2; j < Math.sqrt(i) + 1; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) { maxx = i; } } } int sum = 0; for (char c : String.valueOf(maxx).toCharArray()) { sum += (c - '0'); } return sum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a map, 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 map is empty. Examples: checkDictCase({"a":"apple", "b":"banana"}) should return True. checkDictCase({"a":"apple", "A":"banana", "B":"banana"}) should return False. checkDictCase({"a":"apple", 8:"banana", "a":"apple"}) should return False. checkDictCase({"Name":"John", "Age":"36", "City":"Houston"}) should return False. checkDictCase({"STATE":"NC", "ZIP":"12345" }) should return True. */ public boolean checkDictCase(Map<Object, Object> dict) {
if (dict.isEmpty()) { return false; } String state = "start"; for (Map.Entry entry : dict.entrySet()) { if (!(entry.getKey() instanceof String key)) { state = "mixed"; break; } boolean is_upper = true, is_lower = true; for (char c : key.toCharArray()) { if (Character.isLowerCase(c)) { is_upper = false; } else if (Character.isUpperCase(c)) { is_lower = false; } else { is_upper = false; is_lower = false; } } if (state.equals("start")) { if (is_upper) { state = "upper"; } else if (is_lower) { state = "lower"; } else { break; } } else if ((state.equals("upper") && !is_upper) || (state.equals("lower") && !is_lower)) { state = "mixed"; break; } } return state.equals("upper") || state.equals("lower"); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: countUpTo(5) => [2,3] countUpTo(11) => [2,3,5,7] countUpTo(0) => [] countUpTo(20) => [2,3,5,7,11,13,17,19] countUpTo(1) => [] countUpTo(18) => [2,3,5,7,11,13,17] */ public List<Integer> countUpTo(int n) {
List<Integer> primes = new ArrayList<>(); for (int i = 2; i < n; i++) { boolean is_prime = true; for (int j = 2; j < i; j++) { if (i % j == 0) { is_prime = false; break; } } if (is_prime) { primes.add(i); } } return primes; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Complete the function that takes two integers and returns the product of their unit digits. Assume the input is always valid. Examples: multiply(148, 412) should return 16. multiply(19, 28) should return 72. multiply(2020, 1851) should return 0. multiply(14,-15) should return 20. */ public int multiply(int a, int b) {
return Math.abs(a % 10) * Math.abs(b % 10); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a string s, count the number of uppercase vowels in even indices. For example: countUpper("aBCdEf") returns 1 countUpper("abcdefg") returns 0 countUpper("dBBE") returns 0 */ public int countUpper(String s) {
int count = 0; for (int i = 0; i < s.length(); i += 2) { if ("AEIOU".indexOf(s.charAt(i)) != -1) { count += 1; } } return count; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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. */ public int countUpper(String value) {
if (value.contains(".")) { while (value.charAt(value.length() - 1) == '0') { value = value.substring(0, value.length() - 1); } } double num = Double.parseDouble(value); int res = 0; if (value.substring(Math.max(value.length() - 2, 0)).equals(".5")) { if (num > 0) { res = (int) Math.ceil(num); } else { res = (int) Math.floor(num); } } else if(value.length() > 0) { res = (int) Math.round(num); } return res; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a list, where element at index i represents the number of stones in the level (i+1). Examples: >>> makeAPile(3) [3, 5, 7] */ public List<Integer> makeAPile(int n) {
List<Integer> result = new ArrayList<>(); for (int i = 0; i < n; i++) { result.add(n + 2 * i); } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return an array of the words. For example: words_string("Hi, my name is John").equals(Arrays.asList("Hi", "my", "name", "is", "John"] words_string("One, two, three, four, five, six").equals(Arrays.asList("One", "two", "three", "four", "five", "six"] */ public List<String> wordStrings(String s) {
if (s.length() == 0) { return List.of(); } StringBuilder sb = new StringBuilder(); for (char letter : s.toCharArray()) { if (letter == ',') { sb.append(' '); } else { sb.append(letter); } } return new ArrayList<>(Arrays.asList(sb.toString().split("\s+" ))); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: chooseNum(12, 15) = 14 chooseNum(13, 12) = -1 */ public int chooseNum(int x, int y) {
if (x > y) { return -1; } if (y % 2 == 0) { return y; } if (x == y) { return -1; } return y - 1; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer and convert that to binary. If n is greater than m, return -1. Example: roundedAvg(1, 5) => "11" roundedAvg(7, 5) => -1 roundedAvg(10, 20) => "1111" roundedAvg(20, 33) => "11011" */ public Object roundedAvg(int n, int m) {
if (n > m) { return -1; } return Integer.toBinaryString((int) Math.round((double) (m + n) / 2)); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing order. For example: >>> uniqueDigits(Arrays.asList(15, 33, 1422, 1)) [1, 15, 33] >>> uniqueDigits(Arrays.asList(152, 323, 1422, 10)) [] */ public List<Integer> uniqueDigits(List<Integer> x) {
List<Integer> odd_digit_elements = new ArrayList<>(); for (int i : x) { boolean is_unique = true; for (char c : String.valueOf(i).toCharArray()) { if ((c - '0') % 2 == 0) { is_unique = false; break; } } if (is_unique) { odd_digit_elements.add(i); } } Collections.sort(odd_digit_elements); return odd_digit_elements; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an array of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting array, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". For example: arr = [2, 1, 1, 4, 5, 8, 2, 3] -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1] return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] If the array is empty, return an empty array: arr = [] return [] If the array has any strange number ignore it: arr = [1, -1 , 55] -> sort arr -> [-1, 1, 55] -> reverse arr -> [55, 1, -1] return = ["One"] */ public List<String> byLength(List<Integer> arr) {
List<Integer> sorted_arr = new ArrayList<>(arr); sorted_arr.sort(Collections.reverseOrder()); List<String> new_arr = new ArrayList<>(); for (int var : sorted_arr) { if (var >= 1 && var <= 9) { switch (var) { case 1 -> new_arr.add("One"); case 2 -> new_arr.add("Two"); case 3 -> new_arr.add("Three"); case 4 -> new_arr.add("Four"); case 5 -> new_arr.add("Five"); case 6 -> new_arr.add("Six"); case 7 -> new_arr.add("Seven"); case 8 -> new_arr.add("Eight"); case 9 -> new_arr.add("Nine"); } } } return new_arr; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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] */ public List<Integer> f(int n) {
List<Integer> ret = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (i % 2 == 0) { int x = 1; for (int j = 1; j <= i; j++) { x *= j; } ret.add(x); } else { int x = 0; for (int j = 1; j <= i; j++) { x += j; } ret.add(x); } } return ret; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. */ public List<Integer> evenOddPalindrome(int n) {
int even_palindrome_count = 0, odd_palindrome_count = 0; for (int i = 1; i <= n; i++) { if (String.valueOf(i).equals(new StringBuilder(String.valueOf(i)).reverse().toString())) { if (i % 2 == 1) { odd_palindrome_count += 1; } else { even_palindrome_count += 1; } } } return Arrays.asList(even_palindrome_count, odd_palindrome_count); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Write a function countNums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> countNums(Arrays.asList()) == 0 >>> countNums(Arrays.asList(-1, 11, -11)) == 1 >>> countNums(Arrays.asList(1, 1, 2)) == 3 */ public int countNums(List<Integer> arr) {
int count = 0; for (int n: arr) { int neg = 1; if (n < 0) { n = -n; neg = -1; } List<Integer> digits = new ArrayList<>(); for (char digit : String.valueOf(n).toCharArray()) { digits.add(digit - '0'); } digits.set(0, digits.get(0) * neg); if (digits.stream().reduce(0, Integer::sum) > 0) { count += 1; } } return count; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The numbers in the array will be randomly ordered. Your task is to determine if it is possible to get an array sorted in non-decreasing order by performing the following operation on the given array: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the array by one position in the right direction. The last element of the array will be moved to the starting position in the array i.e. 0th index. If it is possible to obtain the sorted array by performing the above operation then return true else return False. If the given array is empty then return true. Note: The given list is guaranteed to have unique elements. For Example: moveOneBall(Arrays.asList(3, 4, 5, 1, 2))==>true Explanation: By performin 2 right shift operations, non-decreasing order can be achieved for the given array. moveOneBall(Arrays.asList(3, 5, 4, 1, 2))==>False Explanation:It is not possible to get non-decreasing order for the given array by performing any number of right shift operations. */ public boolean moveOneBall(List<Integer> arr) {
if (arr.size() == 0) { return true; } List<Integer> sorted_arr = new ArrayList<>(arr); Collections.sort(sorted_arr); int min_value = Collections.min(arr); int min_index = arr.indexOf(min_value); List<Integer> my_arr = new ArrayList<>(arr.subList(min_index, arr.size())); my_arr.addAll(arr.subList(0, min_index)); for (int i = 0; i < arr.size(); i++) { if (my_arr.get(i) != sorted_arr.get(i)) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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(Arrays.asList(1, 2, 3, 4), Arrays.asList(1, 2, 3, 4)) => "YES" exchange(Arrays.asList(1, 2, 3, 4), Arrays.asList(1, 5, 3, 4)) => "NO" It is assumed that the input lists will be non-empty. */ public String exchange(List<Integer> lst1, List<Integer> lst2) {
int odd = 0, even = 0; for (int i : lst1) { if (i % 2 == 1) { odd += 1; } } for (int i : lst2) { if (i % 2 == 0) { even += 1; } } if (even >= odd) { return "YES"; } return "NO"; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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("") == {} */ public Map<String, Integer> histogram(String test) {
Map<String, Integer> dict1 = new HashMap<>(); List<String> list1 = Arrays.asList(test.split(" " )); int t = 0; for (String i : list1) { if (Collections.frequency(list1, i) > t && !i.isEmpty()) { t = Collections.frequency(list1, i); } } if (t > 0) { for (String i : list1) { if (Collections.frequency(list1, i) == t) { dict1.put(i, t); } } } return dict1; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and true/false for the check. Example For s = "abcde", c = "ae", the result should be ("bcd",false) For s = "abcdef", c = "b" the result should be ("acdef",false) For s = "abcdedcba", c = "ab", the result should be ("cdedc",true) */ public List<Object> reverseDelete(String s, String c) {
StringBuilder sb = new StringBuilder(); for (char ch : s.toCharArray()) { if (c.indexOf(ch) == -1) { sb.append(ch); } } return Arrays.asList(sb.toString(), sb.toString().equals(sb.reverse().toString())); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i"th string of the input. >>> oddCount(Arrays.asList("1234567")) ["the number of odd elements 4n the str4ng 4 of the 4nput."] >>> oddCount(Arrays.asList("3","11111111")) ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."] */ public List<String> oddCount(List<String> lst) {
List<String> res = new ArrayList<>(); for (String arr : lst) { int n = 0; for (char d : arr.toCharArray()) { if ((d - '0') % 2 == 1) { n += 1; } } res.add("the number of odd elements " + n + "n the str" + n + "ng " + n + " of the " + n + "nput." ); } return res; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum(Arrays.asList(2, 3, 4, 1, 2, 4)) == 1 minSubArraySum(Arrays.asList(-1, -2, -3)) == -6 */ public int minSubArraySum(List<Integer> nums) {
int minSum = Integer.MAX_VALUE; int sum = 0; for (Integer num : nums) { sum += num; if (minSum > sum) { minSum = sum; } if (sum > 0) { sum = 0; } } return minSum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: Input: grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]] bucket_capacity : 1 Output: 6 Example 2: Input: grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]] bucket_capacity : 2 Output: 5 Example 3: Input: grid : [[0,0,0], [0,0,0]] bucket_capacity : 5 Output: 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid[:,1].length <= 10^2 * grid[i][j] -> 0 | 1 * 1 <= capacity <= 10 */ public int maxFill(List<List<Integer>> grid, int capacity) {
int sum = 0; for (List<Integer> arr : grid) { sum += Math.ceil((double) arr.stream().reduce(Integer::sum).get() / capacity); } return sum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** In this Kata, you have to sort an array of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. <p> It must be implemented like this: >>> sortArray(Arrays.asList(1, 5, 2, 3, 4)).equals(Arrays.asList(1, 2, 3, 4, 5)) >>> sortArray(Arrays.asList(-2, -3, -4, -5, -6)).equals(Arrays.asList(-6, -5, -4, -3, -2)) >>> sortArray(Arrays.asList(1, 0, 2, 3, 4)).equals(Arrays.asList(0, 1, 2, 3, 4)) */ public List<Integer> sortArray(List<Integer> arr) {
List < Integer > sorted_arr = new ArrayList<>(arr); sorted_arr.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { int cnt1 = (int) Integer.toBinaryString(Math.abs(o1)).chars().filter(ch -> ch == '1').count(); int cnt2 = (int) Integer.toBinaryString(Math.abs(o2)).chars().filter(ch -> ch == '1').count(); if (cnt1 > cnt2) { return 1; } else if (cnt1 < cnt2) { return -1; } else { return o1.compareTo(o2); } } }); return sorted_arr; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: selectWords("Mary had a little lamb", 4) ==> ["little"] selectWords("Mary had a little lamb", 3) ==> ["Mary", "lamb"] selectWords("simple white space", 2) ==> [] selectWords("Hello world", 4) ==> ["world"] selectWords("Uncle sam", 3) ==> ["Uncle"] */ public List<String> selectWords(String s, int n) {
List<String> result = new ArrayList<>(); for (String word : s.split(" ")) { int n_consonants = 0; for (char c : word.toCharArray()) { c = Character.toLowerCase(c); if ("aeiou".indexOf(c) == -1) { n_consonants += 1; } } if (n_consonants == n) { result.add(word); } } return result; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: getClosestVowel("yogurt") ==> "u" getClosestVowel("FULL") ==> "U" getClosestVowel("quick") ==> "" getClosestVowel("ab") ==> "" */ public String getClosestVowel(String word) {
if (word.length() < 3) { return ""; } String vowels = "aeiouAEIOU"; for (int i = word.length() - 2; i > 0; i--) { if (vowels.indexOf(word.charAt(i)) != -1 && vowels.indexOf(word.charAt(i + 1)) == -1 && vowels.indexOf(word.charAt(i - 1)) == -1) { return String.valueOf(word.charAt(i)); } } return ""; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given a list of two strings, both strings consist of open parentheses "(" or close parentheses ")" only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string "(())()" is good, while the string "())" is not. Return "Yes" if there"s a way to make a good string, and return "No" otherwise. Examples: matchParens(Arrays.asList("()(", ")")) == "Yes" matchParens(Arrays.asList(")", ")")) == "No" */ public String matchParens(List<String> lst) {
List<String> S = Arrays.asList(lst.get(0) + lst.get(1), lst.get(1) + lst.get(0)); for (String s : S) { int val = 0; for (char i : s.toCharArray()) { if (i == '(') { val += 1; } else { val -= 1; } if (val < 0) { break; } } if (val == 0) { return "Yes"; } } return "No"; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. Example 1: Input: arr = [-3, -4, 5], k = 3 Output: [-4, -3, 5] Example 2: Input: arr = [4, -4, 4], k = 2 Output: [4, 4] Example 3: Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1 Output: [2] Note: 1. The length of the array will be in the range of [1, 1000]. 2. The elements in the array will be in the range of [-1000, 1000]. 3. 0 <= k <= len(arr) */ public List<Integer> maximum(List<Integer> arr, int k) {
if (k == 0) { return List.of(); } List<Integer> arr_sort = new ArrayList<>(arr); Collections.sort(arr_sort); return arr_sort.subList(arr_sort.size() - k, arr_sort.size()); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples solution(Arrays.asList(5, 8, 7, 1)) ==> 12 solution(Arrays.asList(3, 3, 3, 3, 3)) ==> 9 solution(Arrays.asList(30, 13, 24, 321)) ==>0 */ public int solution(List<Integer> lst) {
int sum = 0; for (int i = 0; i < lst.size(); i += 2) { if ((lst.get(i) % 2) == 1) { sum += lst.get(i); } } return sum; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a non-empty array of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. Example: Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) */ public int addElements(List<Integer> arr, int k) {
arr = arr.subList(0, k); Optional<Integer> sum = arr.stream().filter(p -> String.valueOf(Math.abs(p)).length() <= 2).reduce(Integer::sum); return sum.orElse(0); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. Note: 1. Collatz(1) is [1]. 2. returned list sorted in increasing order. For example: getOddCollatz(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. */ public List<Integer> getOddCollatz(int n) {
List<Integer> odd_collatz = new ArrayList<>(); if (n % 2 == 1) { odd_collatz.add(n); } while (n > 1) { if (n % 2 == 0) { n = n / 2; } else { n = n * 3 + 1; } if (n % 2 == 1) { odd_collatz.add(n); } } Collections.sort(odd_collatz); return odd_collatz; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 for example: validDate("03-11-2000") => true validDate("15-01-2012") => false validDate("04-0-2040") => false validDate("06-04-2020") => true validDate("06/04/2020") => false */ public boolean validDate(String date) {
try { date = date.strip(); String[] dates = date.split("-" ); String m = dates[0]; while (!m.isEmpty() && m.charAt(0) == '0') { m = m.substring(1); } String d = dates[1]; while (!d.isEmpty() && d.charAt(0) == '0') { d = d.substring(1); } String y = dates[2]; while (!y.isEmpty() && y.charAt(0) == '0') { y = y.substring(1); } int month = Integer.parseInt(m), day = Integer.parseInt(d), year = Integer.parseInt(y); if (month < 1 || month > 12) { return false; } if (Arrays.asList(1, 3, 5, 7, 8, 10, 12).contains(month) && (day < 1 || day > 31)) { return false; } if (Arrays.asList(4, 6, 9, 11).contains(month) && (day < 1 || day > 30)) { return false; } if (month == 2 && (day < 1 || day > 29)) { return false; } return true; } catch (Exception e) { return false; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 splitWords("Hello world!") == ["Hello", "world!"] splitWords("Hello,world!") == ["Hello", "world!"] splitWords("abcdef") == 3 */ public Object splitWords(String txt) {
if (txt.contains(" " )) { return Arrays.asList(txt.split(" " )); } else if (txt.contains("," )) { return Arrays.asList(txt.split("[,\s]" )); } else { int count = 0; for (char c : txt.toCharArray()) { if (Character.isLowerCase(c) && (c - 'a') % 2 == 1) { count += 1; } } return count; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Given a list of numbers, return whether or not they are sorted in ascending order. If list has more than 1 duplicate of the same number, return false. Assume no negative numbers and only integers. Examples isSorted(Arrays.asList(5)) -> true isSorted(Arrays.asList(1, 2, 3, 4, 5)) -> true isSorted(Arrays.asList(1, 3, 2, 4, 5)) -> false isSorted(Arrays.asList(1, 2, 3, 4, 5, 6)) -> true isSorted(Arrays.asList(1, 2, 3, 4, 5, 6, 7)) -> true isSorted(Arrays.asList(1, 3, 2, 4, 5, 6, 7)) -> false isSorted(Arrays.asList(1, 2, 2, 3, 3, 4)) -> true isSorted(Arrays.asList(1, 2, 2, 2, 3, 4)) -> false */ public boolean isSorted(List<Integer> lst) {
List<Integer> sorted_lst = new ArrayList<>(lst); Collections.sort(sorted_lst); if (!lst.equals(sorted_lst)) { return false; } for (int i = 0; i < lst.size() - 2; i++) { if (lst.get(i) == lst.get(i + 1) && lst.get(i) == lst.get(i + 2)) { return false; } } return true; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". [input/output] samples: intersection((1, 2), (2, 3)) ==> "NO" intersection((-1, 1), (0, 4)) ==> "NO" intersection((-3, -1), (-5, 5)) ==> "YES" */ public String intersection(List<Integer> interval1, List<Integer> interval2) {
int l = Math.max(interval1.get(0), interval2.get(0)); int r = Math.min(interval1.get(1), interval2.get(1)); int length = r - l; if (length <= 0) { return "NO"; } if (length == 1) { return "NO"; } if (length == 2) { return "YES"; } for (int i = 2; i < length; i++) { if (length % i == 0) { return "NO"; } } return "YES"; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. Example: >>> prodSigns(Arrays.asList(1, 2, 2, -4)) == -9 >>> prodSigns(Arrays.asList(0, 1)) == 0 >>> prodSigns(Arrays.asList()) == None */ public Optional<Integer> prodSigns(List<Integer> arr) {
if (arr.size() == 0) { return Optional.empty(); } if (arr.contains(0)) { return Optional.of(0); } int prod = (int) (-2 * (arr.stream().filter(p -> p < 0).count() % 2) + 1); return Optional.of(prod * (arr.stream().map(Math::abs).reduce(Integer::sum)).get()); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 Output: [1, 2, 1] Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 Output: [1] */ public List<Integer> minPath(List<List<Integer>> grid, int k) {
int n = grid.size(); int val = n * n + 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (grid.get(i).get(j) == 1) { List<Integer> temp = new ArrayList<>(); if (i != 0) { temp.add(grid.get(i - 1).get(j)); } if (j != 0) { temp.add(grid.get(i).get(j - 1)); } if (i != n - 1) { temp.add(grid.get(i + 1).get(j)); } if (j != n - 1) { temp.add(grid.get(i).get(j + 1)); } val = Collections.min(temp); } } } List<Integer> ans = new ArrayList<>(); for (int i = 0; i < k; i++) { if (i % 2 == 0) { ans.add(1); } else { ans.add(val); } } return ans; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a list of the first n + 1 numbers of the Tribonacci sequence. Examples: tri(3) = [1, 3, 2, 8] */ public List<Integer> tri(int n) {
if (n == 0) { return List.of(1); } List<Integer> my_tri = new ArrayList<>(Arrays.asList(1, 3)); for (int i = 2; i <= n; i++) { if (i % 2 == 0) { my_tri.add(i / 2 + 1); } else { my_tri.add(my_tri.get(my_tri.size() - 1) + my_tri.get(my_tri.size() - 2) + (i + 3) / 2); } } return my_tri; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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 */ public int digits(int n) {
int product = 1, odd_count = 0; for (char digit : String.valueOf(n).toCharArray()) { int int_digit = digit - '0'; if (int_digit % 2 == 1) { product *= int_digit; odd_count += 1; } } if (odd_count == 0) { return 0; } else { return product; } } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Create a function that takes a string as input which contains only square brackets. The function should return true if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. isNested("[[]]") -> true isNested("[]]]]]]][[[[[]") -> false isNested("[][]") -> false isNested("[]") -> false isNested("[[][]]") -> true isNested("[[]][[") -> true */ public boolean isNested(String string) {
List<Integer> opening_bracket_index = new ArrayList<>(), closing_bracket_index = new ArrayList<>(); for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == '[') { opening_bracket_index.add(i); } else { closing_bracket_index.add(i); } } Collections.reverse(closing_bracket_index); int i = 0, l = closing_bracket_index.size(); for (int idx : opening_bracket_index) { if (i < l && idx < closing_bracket_index.get(i)) { i += 1; } } return i >= 2; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: For lst = [1,2,3] the output should be 14 For lst = [1,4,9] the output should be 98 For lst = [1,3,5,7] the output should be 84 For lst = [1.4,4.2,0] the output should be 29 For lst = [-2.4,1,1] the output should be 6 */ public int sumSquares(List<Double> lst) {
return lst.stream().map(p -> (int) Math.ceil(p)).map(p -> p * p).reduce(Integer::sum).get(); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** 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: checkIfLastCharIsALetter("apple pie") -> false checkIfLastCharIsALetter("apple pi e") -> true checkIfLastCharIsALetter("apple pi e ") -> false checkIfLastCharIsALetter("") -> false */ public boolean checkIfLastCharIsALetter(String txt) {
String[] words = txt.split(" ", -1); String check = words[words.length - 1]; return check.length() == 1 && Character.isLetter(check.charAt(0)); } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given array will not contain duplicate values. Examples: canArrange(Arrays.asList(1,2,4,3,5)) = 3 canArrange(Arrays.asList(1,2,3)) = -1 */ public int canArrange(List<Integer> arr) {
int ind = -1, i = 1; while (i < arr.size()) { if (arr.get(i) < arr.get(i - 1)) { ind = i; } i += 1; } return ind; } }
java
THUDM/humaneval-x