id
stringlengths
28
30
content
stringlengths
701
6k
humaneval-x-java_data_Java_100
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.makeAPile(3).equals(Arrays.asList(3, 5, 7)), s.makeAPile(4).equals(Arrays.asList(4, 6, 8, 10)), s.makeAPile(5).equals(Arrays.asList(5, 7, 9, 11, 13)), s.makeAPile(6).equals(Arrays.asList(6, 8, 10, 12, 14, 16)), s.makeAPile(8).equals(Arrays.asList(8, 10, 12, 14, 16, 18, 20, 22)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_101
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.wordStrings("Hi, my name is John" ).equals(Arrays.asList("Hi", "my", "name", "is", "John" )), s.wordStrings("One, two, three, four, five, six" ).equals(Arrays.asList("One", "two", "three", "four", "five", "six" )), s.wordStrings("Hi, my name" ).equals(Arrays.asList("Hi", "my", "name" )), s.wordStrings("One,, two, three, four, five, six," ).equals(Arrays.asList("One", "two", "three", "four", "five", "six" )), s.wordStrings("" ).equals(List.of()), s.wordStrings("ahmed , gamal" ).equals(Arrays.asList("ahmed", "gamal" )) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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+" ))); } }
humaneval-x-java_data_Java_102
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.chooseNum(12, 15) == 14, s.chooseNum(13, 12) == -1, s.chooseNum(33, 12354) == 12354, s.chooseNum(5234, 5233) == -1, s.chooseNum(6, 29) == 28, s.chooseNum(27, 10) == -1, s.chooseNum(7, 7) == -1, s.chooseNum(546, 546) == 546 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_103
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals((String) s.roundedAvg(1, 5), "11" ), Objects.equals((String) s.roundedAvg(7, 13), "1010" ), Objects.equals((String) s.roundedAvg(964, 977), "1111001011" ), Objects.equals((String) s.roundedAvg(996, 997), "1111100101" ), Objects.equals((String) s.roundedAvg(560, 851), "1011000010" ), Objects.equals((String) s.roundedAvg(185, 546), "101101110" ), Objects.equals((String) s.roundedAvg(362, 496), "110101101" ), Objects.equals((String) s.roundedAvg(350, 902), "1001110010" ), Objects.equals((String) s.roundedAvg(197, 233), "11010111" ), (int) s.roundedAvg(7, 5) == -1, (int) s.roundedAvg(5, 1) == -1, Objects.equals((String) s.roundedAvg(5, 5), "101" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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)); } }
humaneval-x-java_data_Java_104
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.uniqueDigits(Arrays.asList(15, 33, 1422, 1)).equals(Arrays.asList(1, 15, 33)), s.uniqueDigits(Arrays.asList(152, 323, 1422, 10)).equals(List.of()), s.uniqueDigits(Arrays.asList(12345, 2033, 111, 151)).equals(Arrays.asList(111, 151)), s.uniqueDigits(Arrays.asList(135, 103, 31)).equals(Arrays.asList(31, 135)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_105
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.byLength(new ArrayList<>(Arrays.asList(2, 1, 1, 4, 5, 8, 2, 3))).equals(Arrays.asList("Eight", "Five", "Four", "Three", "Two", "Two", "One", "One" )), s.byLength(new ArrayList<>(List.of())).equals(List.of()), s.byLength(new ArrayList<>(Arrays.asList(1, -1, 55))).equals(List.of("One" )), s.byLength(new ArrayList<>(Arrays.asList(1, -1, 3, 2))).equals(Arrays.asList("Three", "Two", "One" )), s.byLength(new ArrayList<>(Arrays.asList(9, 4, 8))).equals(Arrays.asList("Nine", "Eight", "Four" )) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_106
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.f(5).equals(Arrays.asList(1, 2, 6, 24, 15)), s.f(7).equals(Arrays.asList(1, 2, 6, 24, 15, 720, 28)), s.f(1).equals(List.of(1)), s.f(3).equals(Arrays.asList(1, 2, 6)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_107
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.evenOddPalindrome(123).equals(Arrays.asList(8, 13)), s.evenOddPalindrome(12).equals(Arrays.asList(4, 6)), s.evenOddPalindrome(3).equals(Arrays.asList(1, 2)), s.evenOddPalindrome(63).equals(Arrays.asList(6, 8)), s.evenOddPalindrome(25).equals(Arrays.asList(5, 6)), s.evenOddPalindrome(19).equals(Arrays.asList(4, 6)), s.evenOddPalindrome(9).equals(Arrays.asList(4, 5)), s.evenOddPalindrome(1).equals(Arrays.asList(0, 1)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_108
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.countNums(List.of()) == 0, s.countNums(Arrays.asList(-1, -2, 0)) == 0, s.countNums(Arrays.asList(1, 1, 2, -2, 3, 4, 5)) == 6, s.countNums(Arrays.asList(1, 6, 9, -6, 0, 1, 5)) == 5, s.countNums(Arrays.asList(1, 100, 98, -7, 1, -1)) == 4, s.countNums(Arrays.asList(12, 23, 34, -45, -56, 0)) == 5, s.countNums(Arrays.asList(-0, (int) Math.pow(1, 0))) == 1, s.countNums(List.of(1)) == 1 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_109
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.moveOneBall(new ArrayList<>(Arrays.asList(3, 4, 5, 1, 2))) == true, s.moveOneBall(new ArrayList<>(Arrays.asList(3, 5, 10, 1, 2))) == true, s.moveOneBall(new ArrayList<>(Arrays.asList(4, 3, 1, 2))) == false, s.moveOneBall(new ArrayList<>(Arrays.asList(3, 5, 4, 1, 2))) == false, s.moveOneBall(new ArrayList<>(Arrays.asList())) == true ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_110
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.exchange(Arrays.asList(1, 2, 3, 4), Arrays.asList(1, 2, 3, 4)), "YES" ), Objects.equals(s.exchange(Arrays.asList(1, 2, 3, 4), Arrays.asList(1, 5, 3, 4)), "NO" ), Objects.equals(s.exchange(Arrays.asList(1, 2, 3, 4), Arrays.asList(2, 1, 4, 3)), "YES" ), Objects.equals(s.exchange(Arrays.asList(5, 7, 3), Arrays.asList(2, 6, 4)), "YES" ), Objects.equals(s.exchange(Arrays.asList(5, 7, 3), Arrays.asList(2, 6, 3)), "NO" ), Objects.equals(s.exchange(Arrays.asList(3, 2, 6, 1, 8, 9), Arrays.asList(3, 5, 5, 1, 1, 1)), "NO" ), Objects.equals(s.exchange(Arrays.asList(100, 200), Arrays.asList(200, 200)), "YES" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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"; } }
humaneval-x-java_data_Java_111
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 class Main { public static void main(String[] args) { Solution s = new Solution(); Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 2); map1.put("b", 2); Map<String, Integer> map2 = new HashMap<>(); map2.put("a", 2); map2.put("b", 2); Map<String, Integer> map3 = new HashMap<>(); map3.put("a", 1); map3.put("b", 1); map3.put("c", 1); map3.put("d", 1); map3.put("g", 1); Map<String, Integer> map4 = new HashMap<>(); map4.put("r", 1); map4.put("t", 1); map4.put("g", 1); Map<String, Integer> map5 = new HashMap<>(); map5.put("b", 4); Map<String, Integer> map6 = new HashMap<>(); map6.put("r", 1); map6.put("t", 1); map6.put("g", 1); Map<String, Integer> map7 = new HashMap<>(); Map<String, Integer> map8 = new HashMap<>(); map8.put("a", 1); List<Boolean> correct = Arrays.asList( s.histogram("a b b a" ).equals(map1), s.histogram("a b c a b" ).equals(map2), s.histogram("a b c d g" ).equals(map3), s.histogram("r t g" ).equals(map4), s.histogram("b b b b a" ).equals(map5), s.histogram("r t g" ).equals(map6), s.histogram("" ).equals(map7), s.histogram("a" ).equals(map8) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_112
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.reverseDelete("abcde", "ae" ).equals(Arrays.asList("bcd", false)), s.reverseDelete("abcdef", "b" ).equals(Arrays.asList("acdef", false)), s.reverseDelete("abcdedcba", "ab" ).equals(Arrays.asList("cdedc", true)), s.reverseDelete("dwik", "w" ).equals(Arrays.asList("dik", false)), s.reverseDelete("a", "a" ).equals(Arrays.asList("", true)), s.reverseDelete("abcdedcba", "" ).equals(Arrays.asList("abcdedcba", true)), s.reverseDelete("abcdedcba", "v" ).equals(Arrays.asList("abcdedcba", true)), s.reverseDelete("vabba", "v" ).equals(Arrays.asList("abba", true)), s.reverseDelete("mamma", "mia" ).equals(Arrays.asList("", true)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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())); } }
humaneval-x-java_data_Java_113
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.oddCount(List.of("1234567" )).equals(List.of("the number of odd elements 4n the str4ng 4 of the 4nput." )), s.oddCount(Arrays.asList("3", "11111111" )).equals(Arrays.asList("the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput." )), s.oddCount(Arrays.asList("271", "137", "314" )).equals(Arrays.asList( "the number of odd elements 2n the str2ng 2 of the 2nput.", "the number of odd elements 3n the str3ng 3 of the 3nput.", "the number of odd elements 2n the str2ng 2 of the 2nput." )) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_114
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.minSubArraySum(Arrays.asList(2, 3, 4, 1, 2, 4)) == 1, s.minSubArraySum(Arrays.asList(-1, -2, -3)) == -6, s.minSubArraySum(Arrays.asList(-1, -2, -3, 2, -10)) == -14, s.minSubArraySum(List.of(-999999999)) == -999999999, s.minSubArraySum(Arrays.asList(0, 10, 20, 1000000)) == 0, s.minSubArraySum(Arrays.asList(-1, -2, -3, 10, -5)) == -6, s.minSubArraySum(Arrays.asList(100, -1, -2, -3, 10, -5)) == -6, s.minSubArraySum(Arrays.asList(10, 11, 13, 8, 3, 4)) == 3, s.minSubArraySum(Arrays.asList(100, -33, 32, -1, 0, -2)) == -33, s.minSubArraySum(List.of(-10)) == -10, s.minSubArraySum(List.of(7)) == 7, s.minSubArraySum(Arrays.asList(1, -1)) == -1 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_115
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.maxFill(Arrays.asList(Arrays.asList(0, 0, 1, 0), Arrays.asList(0, 1, 0, 0), Arrays.asList(1, 1, 1, 1)), 1) == 6, s.maxFill(Arrays.asList(Arrays.asList(0, 0, 1, 1), Arrays.asList(0, 0, 0, 0), Arrays.asList(1, 1, 1, 1), Arrays.asList(0, 1, 1, 1)), 2) == 5, s.maxFill(Arrays.asList(Arrays.asList(0, 0, 0), Arrays.asList(0, 0, 0)), 5) == 0, s.maxFill(Arrays.asList(Arrays.asList(1, 1, 1, 1), Arrays.asList(1, 1, 1, 1)), 2) == 4, s.maxFill(Arrays.asList(Arrays.asList(1, 1, 1, 1), Arrays.asList(1, 1, 1, 1)), 9) == 2 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_116
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.sortArray(new ArrayList<>(Arrays.asList(1, 5, 2, 3, 4))).equals(Arrays.asList(1, 2, 4, 3, 5)), s.sortArray(new ArrayList<>(Arrays.asList(-2, -3, -4, -5, -6))).equals(Arrays.asList(-4, -2, -6, -5, -3)), s.sortArray(new ArrayList<>(Arrays.asList(1, 0, 2, 3, 4))).equals(Arrays.asList(0, 1, 2, 4, 3)), s.sortArray(new ArrayList<>(List.of())).equals(List.of()), s.sortArray(new ArrayList<>(Arrays.asList(2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4))).equals(Arrays.asList(2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77)), s.sortArray(new ArrayList<>(Arrays.asList(3, 6, 44, 12, 32, 5))).equals(Arrays.asList(32, 3, 5, 6, 12, 44)), s.sortArray(new ArrayList<>(Arrays.asList(2, 4, 8, 16, 32))).equals(Arrays.asList(2, 4, 8, 16, 32)), s.sortArray(new ArrayList<>(Arrays.asList(2, 4, 8, 16, 32))).equals(Arrays.asList(2, 4, 8, 16, 32)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_117
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.selectWords("Mary had a little lamb", 4).equals(List.of("little" )), s.selectWords("Mary had a little lamb", 3).equals(Arrays.asList("Mary", "lamb")), s.selectWords("simple white space", 2).equals(List.of()), s.selectWords("Hello world", 4).equals(List.of("world" )), s.selectWords("Uncle sam", 3).equals(List.of("Uncle" )), s.selectWords("", 4).equals(List.of()), s.selectWords("a b c d e f", 1).equals(Arrays.asList("b", "c", "d", "f")) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_118
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.getClosestVowel("yogurt").equals("u"), s.getClosestVowel("full").equals("u"), s.getClosestVowel("easy").equals(""), s.getClosestVowel("eAsy").equals(""), s.getClosestVowel("ali").equals(""), s.getClosestVowel("bad").equals("a"), s.getClosestVowel("most").equals("o"), s.getClosestVowel("ab").equals(""), s.getClosestVowel("ba").equals(""), s.getClosestVowel("quick").equals(""), s.getClosestVowel("anime").equals("i"), s.getClosestVowel("Asia").equals(""), s.getClosestVowel("Above").equals("o") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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 ""; } }
humaneval-x-java_data_Java_119
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.matchParens(Arrays.asList("()(", ")")).equals("Yes"), s.matchParens(Arrays.asList(")", ")")).equals("No"), s.matchParens(Arrays.asList("(()(())", "())())")).equals("No"), s.matchParens(Arrays.asList(")())", "(()()(")).equals("Yes"), s.matchParens(Arrays.asList("(())))", "(()())((")).equals("Yes"), s.matchParens(Arrays.asList("()", "())")).equals("No"), s.matchParens(Arrays.asList("(()(", "()))()")).equals("Yes"), s.matchParens(Arrays.asList("((((", "((())")).equals("No"), s.matchParens(Arrays.asList(")(()", "(()(")).equals("No"), s.matchParens(Arrays.asList(")(", ")(")).equals("No") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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"; } }
humaneval-x-java_data_Java_120
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.maximum(new ArrayList<>(Arrays.asList(-3, -4, 5)), 3).equals(Arrays.asList(-4, -3, 5)), s.maximum(new ArrayList<>(Arrays.asList(4, -4, 4)), 2).equals(Arrays.asList(4, 4)), s.maximum(new ArrayList<>(Arrays.asList(-3, 2, 1, 2, -1, -2, 1)), 1).equals(List.of(2)), s.maximum(new ArrayList<>(Arrays.asList(123, -123, 20, 0 , 1, 2, -3)), 3).equals(Arrays.asList(2, 20, 123)), s.maximum(new ArrayList<>(Arrays.asList(-123, 20, 0 , 1, 2, -3)), 4).equals(Arrays.asList(0, 1, 2, 20)), s.maximum(new ArrayList<>(Arrays.asList(5, 15, 0, 3, -13, -8, 0)), 7).equals(Arrays.asList(-13, -8, 0, 0, 3, 5, 15)), s.maximum(new ArrayList<>(Arrays.asList(-1, 0, 2, 5, 3, -10)), 2).equals(Arrays.asList(3, 5)), s.maximum(new ArrayList<>(Arrays.asList(1, 0, 5, -7)), 1).equals(List.of(5)), s.maximum(new ArrayList<>(Arrays.asList(4, -4)), 2).equals(Arrays.asList(-4, 4)), s.maximum(new ArrayList<>(Arrays.asList(-10, 10)), 2).equals(Arrays.asList(-10, 10)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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()); } }
humaneval-x-java_data_Java_121
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.solution(Arrays.asList(5, 8, 7, 1)) == 12, s.solution(Arrays.asList(3, 3, 3, 3, 3)) == 9, s.solution(Arrays.asList(30, 13, 24, 321)) == 0, s.solution(Arrays.asList(5, 9)) == 5, s.solution(Arrays.asList(2, 4, 8)) == 0, s.solution(Arrays.asList(30, 13, 23, 32)) == 23, s.solution(Arrays.asList(3, 13, 2, 9)) == 3 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_122
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.addElements(Arrays.asList(1, -2, -3, 41, 57, 76, 87, 88, 99), 3) == -4, s.addElements(Arrays.asList(111, 121, 3, 4000, 5, 6), 2) == 0, s.addElements(Arrays.asList(11, 21, 3, 90, 5, 6, 7, 8, 9), 4) == 125, s.addElements(Arrays.asList(111, 21, 3, 4000, 5, 6, 7, 8, 9), 4) == 24, s.addElements(Arrays.asList(1), 1) == 1 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_123
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.getOddCollatz(14).equals(Arrays.asList(1, 5, 7, 11, 13, 17)), s.getOddCollatz(5).equals(Arrays.asList(1, 5)), s.getOddCollatz(12).equals(Arrays.asList(1, 3, 5)), s.getOddCollatz(1).equals(List.of(1)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_124
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.validDate("03-11-2000" ) == true, s.validDate("15-01-2012" ) == false, s.validDate("04-0-2040" ) == false, s.validDate("06-04-2020" ) == true, s.validDate("01-01-2007" ) == true, s.validDate("03-32-2011" ) == false, s.validDate("" ) == false, s.validDate("04-31-3000" ) == false, s.validDate("06-06-2005" ) == true, s.validDate("21-31-2000" ) == false, s.validDate("04-12-2003" ) == true, s.validDate("04122003" ) == false, s.validDate("20030412" ) == false, s.validDate("2003-04" ) == false, s.validDate("2003-04-12" ) == false, s.validDate("04-2003" ) == false ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } } }
humaneval-x-java_data_Java_125
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.splitWords("Hello world!" ), Arrays.asList("Hello", "world!" )), Objects.equals(s.splitWords("Hello,world!" ), Arrays.asList("Hello", "world!" )), Objects.equals(s.splitWords("Hello world,!" ), Arrays.asList("Hello", "world,!" )), Objects.equals(s.splitWords("Hello,Hello,world !" ), Arrays.asList("Hello,Hello,world", "!" )), Objects.equals(s.splitWords("abcdef" ), 3), Objects.equals(s.splitWords("aaabb" ), 2), Objects.equals(s.splitWords("aaaBb" ), 1), Objects.equals(s.splitWords("" ), 0) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } } }
humaneval-x-java_data_Java_126
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.isSorted(new ArrayList<>(List.of(5))) == true, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))) == true, s.isSorted(new ArrayList<>(Arrays.asList(1, 3, 2, 4, 5))) == false, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6))) == true, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7))) == true, s.isSorted(new ArrayList<>(Arrays.asList(1, 3, 2, 4, 5, 6, 7))) == false, s.isSorted(new ArrayList<>(List.of())) == true, s.isSorted(new ArrayList<>(List.of(1))) == true, s.isSorted(new ArrayList<>(Arrays.asList(3, 2, 1))) == false, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 2, 2, 3, 4))) == false, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 3, 3, 3, 4))) == false, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 2, 3, 3, 4))) == true, s.isSorted(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) == true ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_127
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.intersection(Arrays.asList(1, 2), Arrays.asList(2, 3)), "NO" ), Objects.equals(s.intersection(Arrays.asList(-1, 1), Arrays.asList(0, 4)), "NO" ), Objects.equals(s.intersection(Arrays.asList(-3, -1), Arrays.asList(-5, 5)), "YES" ), Objects.equals(s.intersection(Arrays.asList(-2, 2), Arrays.asList(-4, 0)), "YES" ), Objects.equals(s.intersection(Arrays.asList(-11, 2), Arrays.asList(-1, -1)), "NO" ), Objects.equals(s.intersection(Arrays.asList(1, 2), Arrays.asList(3, 5)), "NO" ), Objects.equals(s.intersection(Arrays.asList(1, 2), Arrays.asList(1, 2)), "NO" ), Objects.equals(s.intersection(Arrays.asList(-2, -2), Arrays.asList(-3, -2)), "NO" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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"; } }
humaneval-x-java_data_Java_128
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.prodSigns(Arrays.asList(1, 2, 2, -4)).get() == -9, s.prodSigns(Arrays.asList(0, 1)).get() == 0, s.prodSigns(Arrays.asList(1, 1, 1, 2, 3, -1, 1)).get() == -10, s.prodSigns(List.of()).isEmpty(), s.prodSigns(Arrays.asList(2, 4,1, 2, -1, -1, 9)).get() == 20, s.prodSigns(Arrays.asList(-1, 1, -1, 1)).get() == 4, s.prodSigns(Arrays.asList(-1, 1, 1, 1)).get() == -4, s.prodSigns(Arrays.asList(-1, 1, 1, 0)).get() == 0 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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()); } }
humaneval-x-java_data_Java_129
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.minPath(Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9)), 3).equals(Arrays.asList(1, 2, 1)), s.minPath(Arrays.asList(Arrays.asList(5, 9, 3), Arrays.asList(4, 1, 6), Arrays.asList(7, 8, 2)), 1).equals(List.of(1)), s.minPath(Arrays.asList(Arrays.asList(1, 2, 3, 4), Arrays.asList(5, 6, 7, 8), Arrays.asList(9, 10, 11, 12), Arrays.asList(13, 14, 15, 16)), 4).equals(Arrays.asList(1, 2, 1, 2)), s.minPath(Arrays.asList(Arrays.asList(6, 4, 13, 10), Arrays.asList(5, 7, 12, 1), Arrays.asList(3, 16, 11, 15), Arrays.asList(8, 14, 9, 2)), 7).equals(Arrays.asList(1, 10, 1, 10, 1, 10, 1)), s.minPath(Arrays.asList(Arrays.asList(8, 14, 9, 2), Arrays.asList(6, 4, 13, 15), Arrays.asList(5, 7, 1, 12), Arrays.asList(3, 10, 11, 16)), 5).equals(Arrays.asList(1, 7, 1, 7, 1)), s.minPath(Arrays.asList(Arrays.asList(11, 8, 7, 2), Arrays.asList(5, 16, 14, 4), Arrays.asList(9, 3, 15, 6), Arrays.asList(12, 13, 10, 1)), 9).equals(Arrays.asList(1, 6, 1, 6, 1, 6, 1, 6, 1)), s.minPath(Arrays.asList(Arrays.asList(12, 13, 10, 1), Arrays.asList(9, 3, 15, 6), Arrays.asList(5, 16, 14, 4), Arrays.asList(11, 8, 7, 2)), 12).equals(Arrays.asList(1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6)), s.minPath(Arrays.asList(Arrays.asList(2, 7, 4), Arrays.asList(3, 1, 5), Arrays.asList(6, 8, 9)), 8).equals(Arrays.asList(1, 3, 1, 3, 1, 3, 1, 3)), s.minPath(Arrays.asList(Arrays.asList(6, 1, 5), Arrays.asList(3, 8, 9), Arrays.asList(2, 7, 4)), 8).equals(Arrays.asList(1, 5, 1, 5, 1, 5, 1, 5)), s.minPath(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)), 10).equals(Arrays.asList(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)), s.minPath(Arrays.asList(Arrays.asList(1, 3), Arrays.asList(3, 2)), 10).equals(Arrays.asList(1, 3, 1, 3, 1, 3, 1, 3, 1, 3)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_130
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.tri(3).equals(Arrays.asList(1, 3, 2, 8)), s.tri(4).equals(Arrays.asList(1, 3, 2, 8, 3)), s.tri(5).equals(Arrays.asList(1, 3, 2, 8, 3, 15)), s.tri(6).equals(Arrays.asList(1, 3, 2, 8, 3, 15, 4)), s.tri(7).equals(Arrays.asList(1, 3, 2, 8, 3, 15, 4, 24)), s.tri(8).equals(Arrays.asList(1, 3, 2, 8, 3, 15, 4, 24, 5)), s.tri(9).equals(Arrays.asList(1, 3, 2, 8, 3, 15, 4, 24, 5, 35)), s.tri(20).equals(Arrays.asList(1, 3, 2, 8, 3, 15, 4, 24, 5, 35, 6, 48, 7, 63, 8, 80, 9, 99, 10, 120, 11)), s.tri(0).equals(List.of(1)), s.tri(1).equals(Arrays.asList(1, 3)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_131
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.digits(5) == 5, s.digits(54) == 5, s.digits(120) == 1, s.digits(5014) == 5, s.digits(98765) == 315, s.digits(5576543) == 2625 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } } }
humaneval-x-java_data_Java_132
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.isNested("[[]]" ), !s.isNested("[]]]]]]][[[[[]" ), !s.isNested("[][]" ), !s.isNested("[]" ), s.isNested("[[[[]]]]" ), !s.isNested("[]]]]]]]]]]" ), s.isNested("[][][[]]" ), !s.isNested("[[]" ), !s.isNested("[]]" ), s.isNested("[[]][[" ), s.isNested("[[][]]" ), !s.isNested("" ), !s.isNested("[[[[[[[[" ), !s.isNested("]]]]]]]]" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_133
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.sumSquares(Arrays.asList(1., 2., 3.)) == 14, s.sumSquares(Arrays.asList(1.0, 2., 3.)) == 14, s.sumSquares(Arrays.asList(1., 3., 5., 7.)) == 84, s.sumSquares(Arrays.asList(1.4, 4.2, 0.)) == 29, s.sumSquares(Arrays.asList(-2.4, 1., 1.)) == 6, s.sumSquares(Arrays.asList(100., 1., 15., 2.)) == 10230, s.sumSquares(Arrays.asList(10000., 10000.)) == 200000000, s.sumSquares(Arrays.asList(-1.4, 4.6, 6.3)) == 75, s.sumSquares(Arrays.asList(-1.4, 17.9, 18.9, 19.9)) == 1086, s.sumSquares(List.of(0.)) == 0, s.sumSquares(List.of(-1.)) == 1, s.sumSquares(Arrays.asList(-1., 1., 0.)) == 2 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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(); } }
humaneval-x-java_data_Java_134
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.checkIfLastCharIsALetter("apple" ) == false, s.checkIfLastCharIsALetter("apple pi e" ) == true, s.checkIfLastCharIsALetter("eeeee" ) == false, s.checkIfLastCharIsALetter("A" ) == true, s.checkIfLastCharIsALetter("Pumpkin pie " ) == false, s.checkIfLastCharIsALetter("Pumpkin pie 1" ) == false, s.checkIfLastCharIsALetter("" ) == false, s.checkIfLastCharIsALetter("eeeee e " ) == false, s.checkIfLastCharIsALetter("apple pie" ) == false, s.checkIfLastCharIsALetter("apple pi e " ) == false ); if (correct.contains(false)) { throw new AssertionError(); } } } 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)); } }
humaneval-x-java_data_Java_135
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.canArrange(Arrays.asList(1, 2, 4, 3, 5)) == 3, s.canArrange(Arrays.asList(1, 2, 4, 5)) == -1, s.canArrange(Arrays.asList(1, 4, 2, 5, 6, 7, 8, 9, 10)) == 2, s.canArrange(Arrays.asList(4, 8, 5, 7, 3)) == 4, s.canArrange(List.of()) == -1 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_136
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.largestSmallestIntegers(Arrays.asList(2, 4, 1, 3, 5, 7)).equals(Arrays.asList(Optional.empty(), Optional.of(1))), s.largestSmallestIntegers(Arrays.asList(2, 4, 1, 3, 5, 7, 0)).equals(Arrays.asList(Optional.empty(), Optional.of(1))), s.largestSmallestIntegers(Arrays.asList(1, 3, 2, 4, 5, 6, -2)).equals(Arrays.asList(Optional.of(-2), Optional.of(1))), s.largestSmallestIntegers(Arrays.asList(4, 5, 3, 6, 2, 7, -7)).equals(Arrays.asList(Optional.of(-7), Optional.of(2))), s.largestSmallestIntegers(Arrays.asList(7, 3, 8, 4, 9, 2, 5, -9)).equals(Arrays.asList(Optional.of(-9), Optional.of(2))), s.largestSmallestIntegers(List.of()).equals(Arrays.asList(Optional.empty(), Optional.empty())), s.largestSmallestIntegers(List.of(0)).equals(Arrays.asList(Optional.empty(), Optional.empty())), s.largestSmallestIntegers(Arrays.asList(-1, -3, -5, -6)).equals(Arrays.asList(Optional.of(-1), Optional.empty())), s.largestSmallestIntegers(Arrays.asList(-1, -3, -5, -6, 0)).equals(Arrays.asList(Optional.of(-1), Optional.empty())), s.largestSmallestIntegers(Arrays.asList(-6, -4, -4, -3, 1)).equals(Arrays.asList(Optional.of(-3), Optional.of(1))), s.largestSmallestIntegers(Arrays.asList(-6, -4, -4, -3, -100, 1)).equals(Arrays.asList(Optional.of(-3), Optional.of(1))) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_137
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( (int) s.compareOne(1, 2).get() == 2, (double) s.compareOne(1, 2.5).get() == 2.5, (int) s.compareOne(2, 3).get() == 3, (int) s.compareOne(5, 6).get() == 6, (String) s.compareOne(1, "2,3").get() == "2,3", (String) s.compareOne("5,1", "6").get() == "6", (String) s.compareOne("1", "2").get() == "2", s.compareOne("1", 1).isEmpty() ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } } }
humaneval-x-java_data_Java_138
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.isEqualToSumEven(4) == false, s.isEqualToSumEven(6) == false, s.isEqualToSumEven(8) == true, s.isEqualToSumEven(10) == true, s.isEqualToSumEven(11) == false, s.isEqualToSumEven(12) == true, s.isEqualToSumEven(13) == false, s.isEqualToSumEven(16) == true ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_139
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.specialFactorial(4) == 288, s.specialFactorial(5) == 34560, s.specialFactorial(7) == 125411328000L, s.specialFactorial(1) == 1 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_140
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.fixSpaces("Example" ), "Example" ), Objects.equals(s.fixSpaces("Mudasir Hanif " ), "Mudasir_Hanif_" ), Objects.equals(s.fixSpaces("Yellow Yellow Dirty Fellow" ), "Yellow_Yellow__Dirty__Fellow" ), Objects.equals(s.fixSpaces("Exa mple" ), "Exa-mple" ), Objects.equals(s.fixSpaces(" Exa 1 2 2 mple" ), "-Exa_1_2_2_mple" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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(); } }
humaneval-x-java_data_Java_141
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.filenameCheck("example.txt" ), "Yes" ), Objects.equals(s.filenameCheck("1example.dll" ), "No" ), Objects.equals(s.filenameCheck("s1sdf3.asd" ), "No" ), Objects.equals(s.filenameCheck("K.dll" ), "Yes" ), Objects.equals(s.filenameCheck("MY16FILE3.exe" ), "Yes" ), Objects.equals(s.filenameCheck("His12FILE94.exe" ), "No" ), Objects.equals(s.filenameCheck("_Y.txt" ), "No" ), Objects.equals(s.filenameCheck("?aREYA.exe" ), "No" ), Objects.equals(s.filenameCheck("/this_is_valid.dll" ), "No" ), Objects.equals(s.filenameCheck("this_is_valid.wow" ), "No" ), Objects.equals(s.filenameCheck("this_is_valid.txt" ), "Yes" ), Objects.equals(s.filenameCheck("this_is_valid.txtexe" ), "No" ), Objects.equals(s.filenameCheck("#this2_i4s_5valid.ten" ), "No" ), Objects.equals(s.filenameCheck("@this1_is6_valid.exe" ), "No" ), Objects.equals(s.filenameCheck("this_is_12valid.6exe4.txt" ), "No" ), Objects.equals(s.filenameCheck("all.exe.txt" ), "No" ), Objects.equals(s.filenameCheck("I563_No.exe" ), "Yes" ), Objects.equals(s.filenameCheck("Is3youfault.txt" ), "Yes" ), Objects.equals(s.filenameCheck("no_one#knows.dll" ), "Yes" ), Objects.equals(s.filenameCheck("1I563_Yes3.exe" ), "No" ), Objects.equals(s.filenameCheck("I563_Yes3.txtt" ), "No" ), Objects.equals(s.filenameCheck("final..txt" ), "No" ), Objects.equals(s.filenameCheck("final132" ), "No" ), Objects.equals(s.filenameCheck("_f4indsartal132." ), "No" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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"; } }
humaneval-x-java_data_Java_142
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.sumSquares(Arrays.asList(1,2,3)) == 6, s.sumSquares(Arrays.asList(1,4,9)) == 14, s.sumSquares(List.of()) == 0, s.sumSquares(Arrays.asList(1,1,1,1,1,1,1,1,1)) == 9, s.sumSquares(Arrays.asList(-1,-1,-1,-1,-1,-1,-1,-1,-1)) == -3, s.sumSquares(List.of(0)) == 0, s.sumSquares(Arrays.asList(-1,-5,2,-1,-5)) == -126, s.sumSquares(Arrays.asList(-56,-99,1,0,-2)) == 3030, s.sumSquares(Arrays.asList(-1,0,0,0,0,0,0,0,-1)) == 0, s.sumSquares(Arrays.asList(-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37)) == -14196, s.sumSquares(Arrays.asList(-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10)) == -1448 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_143
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.wordsInSentence("This is a test" ), "is" ), Objects.equals(s.wordsInSentence("lets go for swimming" ), "go for" ), Objects.equals(s.wordsInSentence("there is no place available here" ), "there is no place" ), Objects.equals(s.wordsInSentence("Hi I am Hussein" ), "Hi am Hussein" ), Objects.equals(s.wordsInSentence("go for it" ), "go for it" ), Objects.equals(s.wordsInSentence("here" ), "" ), Objects.equals(s.wordsInSentence("here is" ), "is" ) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_144
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.simplify("1/5", "5/1") == true, s.simplify("1/6", "2/1") == false, s.simplify("5/1", "3/1") == true, s.simplify("7/10", "10/2") == false, s.simplify("2/10", "50/10") == true, s.simplify("7/2", "4/2") == true, s.simplify("11/6", "6/1") == true, s.simplify("2/3", "5/2") == false, s.simplify("5/2", "3/5") == false, s.simplify("2/4", "8/4") == true, s.simplify("2/4", "4/2") == true, s.simplify("1/5", "5/1") == true, s.simplify("1/5", "1/5") == false ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_145
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.orderByPoints(new ArrayList<>(Arrays.asList(1, 11, -1, -11, -12))).equals(Arrays.asList(-1, -11, 1, -12, 11)), s.orderByPoints(new ArrayList<>(Arrays.asList(1234, 423, 463, 145, 2, 423, 423, 53, 6, 37, 3457, 3, 56, 0, 46))).equals(Arrays.asList(0, 2, 3, 6, 53, 423, 423, 423, 1234, 145, 37, 46, 56, 463, 3457)), s.orderByPoints(new ArrayList<>(List.of())).equals(List.of()), s.orderByPoints(new ArrayList<>(Arrays.asList(1, -11, -32, 43, 54, -98, 2, -3))).equals(Arrays.asList(-3, -32, -98, -11, 1, 2, 43, 54)), s.orderByPoints(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).equals(Arrays.asList(1, 10, 2, 11, 3, 4, 5, 6, 7, 8, 9)), s.orderByPoints(new ArrayList<>(Arrays.asList(0, 6, 6, -76, -21, 23, 4))).equals(Arrays.asList(-76, -21, 0, 4, 23, 6, 6)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_146
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.specialFilter(Arrays.asList(5, -2, 1, -5)) == 0, s.specialFilter(Arrays.asList(15, -73, 14, -15)) == 1, s.specialFilter(Arrays.asList(33, -2, -3, 45, 21, 109)) == 2, s.specialFilter(Arrays.asList(43, -12, 93, 125, 121, 109)) == 4, s.specialFilter(Arrays.asList(71, -2, -33, 75, 21, 19)) == 3, s.specialFilter(List.of(1)) == 0, s.specialFilter(List.of()) == 0 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_147
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.getMaxTriples(5) == 1, s.getMaxTriples(6) == 4, s.getMaxTriples(10) == 36, s.getMaxTriples(100) == 53361 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_148
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.bf("Jupiter", "Neptune").equals(Arrays.asList("Saturn", "Uranus")), s.bf("Earth", "Mercury").equals(List.of("Venus")), s.bf("Mercury", "Uranus").equals(Arrays.asList("Venus", "Earth", "Mars", "Jupiter", "Saturn")), s.bf("Neptune", "Venus").equals(Arrays.asList("Earth", "Mars", "Jupiter", "Saturn", "Uranus")), s.bf("Earth", "Earth").equals(List.of()), s.bf("Mars", "Earth").equals(List.of()), s.bf("Jupiter", "Makemake").equals(List.of()) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } } }
humaneval-x-java_data_Java_149
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.listSort(new ArrayList<>(Arrays.asList("aa", "a", "aaa"))).equals(List.of("aa")), s.listSort(new ArrayList<>(Arrays.asList("school", "AI", "asdf", "b"))).equals(Arrays.asList("AI", "asdf", "school")), s.listSort(new ArrayList<>(Arrays.asList("d", "b", "c", "a"))).equals(List.of()), s.listSort(new ArrayList<>(Arrays.asList("d", "dcba", "abcd", "a"))).equals(Arrays.asList("abcd", "dcba")), s.listSort(new ArrayList<>(Arrays.asList("AI", "ai", "au"))).equals(Arrays.asList("AI", "ai", "au")), s.listSort(new ArrayList<>(Arrays.asList("a", "b", "b", "c", "c", "a"))).equals(List.of()), s.listSort(new ArrayList<>(Arrays.asList("aaaa", "bbbb", "dd", "cc"))).equals(Arrays.asList("cc", "dd", "aaaa", "bbbb")) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_150
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.xOrY(7, 34, 12) == 34, s.xOrY(15, 8, 5) == 5, s.xOrY(3, 33, 5212) == 33, s.xOrY(1259, 3, 52) == 3, s.xOrY(7919, -1, 12) == -1, s.xOrY(3609, 1245, 583) == 583, s.xOrY(91, 56, 129) == 129, s.xOrY(6, 34, 1234) == 1234, s.xOrY(1, 2, 0) == 0, s.xOrY(2, 2, 0) == 2 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_151
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.doubleTheDifference(List.of()) == 0, s.doubleTheDifference(Arrays.asList(5, 4)) == 25, s.doubleTheDifference(Arrays.asList(0.1, 0.2, 0.3)) == 0, s.doubleTheDifference(Arrays.asList(-10, -20, -30)) == 0, s.doubleTheDifference(Arrays.asList(-1, -2, 8)) == 0, s.doubleTheDifference(Arrays.asList(0.2, 3, 5)) == 34 ); if (correct.contains(false)) { throw new AssertionError(); } List<Object> lst = new ArrayList<>(); for (int i = -99; i < 100; i += 2) { lst.add(i); } int odd_sum = lst.stream().filter(i -> i instanceof Integer p && p % 2 != 0 && p > 0).map(i -> (Integer) i * (Integer) i).reduce(Integer::sum).orElse(0); assert s.doubleTheDifference(lst) == odd_sum; } } 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); } }
humaneval-x-java_data_Java_152
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.compare(Arrays.asList(1, 2, 3, 4, 5, 1), Arrays.asList(1, 2, 3, 4, 2, -2)).equals(Arrays.asList(0, 0, 0, 0, 3, 3)), s.compare(Arrays.asList(0,5,0,0,0,4), Arrays.asList(4,1,1,0,0,-2)).equals(Arrays.asList(4,4,1,0,0,6)), s.compare(Arrays.asList(1, 2, 3, 4, 5, 1), Arrays.asList(1, 2, 3, 4, 2, -2)).equals(Arrays.asList(0, 0, 0, 0, 3, 3)), s.compare(Arrays.asList(0, 0, 0, 0, 0, 0), Arrays.asList(0, 0, 0, 0, 0, 0)).equals(Arrays.asList(0, 0, 0, 0, 0, 0)), s.compare(Arrays.asList(1, 2, 3), Arrays.asList(-1, -2, -3)).equals(Arrays.asList(2, 4, 6)), s.compare(Arrays.asList(1, 2, 3, 5), Arrays.asList(-1, 2, 3, 4)).equals(Arrays.asList(2, 0, 0, 1)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_153
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.StrongestExtension("Watashi", Arrays.asList("tEN", "niNE", "eIGHt8OKe")), "Watashi.eIGHt8OKe"), Objects.equals(s.StrongestExtension("Boku123", Arrays.asList("nani", "NazeDa", "YEs.WeCaNe", "32145tggg")), "Boku123.YEs.WeCaNe"), Objects.equals(s.StrongestExtension("__YESIMHERE", Arrays.asList("t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321")), "__YESIMHERE.NuLl__"), Objects.equals(s.StrongestExtension("K", Arrays.asList("Ta", "TAR", "t234An", "cosSo")), "K.TAR"), Objects.equals(s.StrongestExtension("__HAHA", Arrays.asList("Tab", "123", "781345", "-_-")), "__HAHA.123"), Objects.equals(s.StrongestExtension("YameRore", Arrays.asList("HhAas", "okIWILL123", "WorkOut", "Fails", "-_-")), "YameRore.okIWILL123"), Objects.equals(s.StrongestExtension("finNNalLLly", Arrays.asList("Die", "NowW", "Wow", "WoW")), "finNNalLLly.WoW"), Objects.equals(s.StrongestExtension("_", Arrays.asList("Bb", "91245")), "_.Bb"), Objects.equals(s.StrongestExtension("Sp", Arrays.asList("671235", "Bb")), "Sp.671235") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_154
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.cycpatternCheck("xyzw", "xyw") == false, s.cycpatternCheck("yello", "ell") == true, s.cycpatternCheck("whattup", "ptut") == false, s.cycpatternCheck("efef", "fee") == true, s.cycpatternCheck("abab", "aabb") == false, s.cycpatternCheck("winemtt", "tinem") == true ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_155
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.evenOddCount(7).equals(Arrays.asList(0, 1)), s.evenOddCount(-78).equals(Arrays.asList(1, 1)), s.evenOddCount(3452).equals(Arrays.asList(2, 2)), s.evenOddCount(346211).equals(Arrays.asList(3, 3)), s.evenOddCount(-345821).equals(Arrays.asList(3, 3)), s.evenOddCount(-2).equals(Arrays.asList(1, 0)), s.evenOddCount(-45347).equals(Arrays.asList(2, 3)), s.evenOddCount(0).equals(Arrays.asList(1, 0)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_156
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.intToMiniRoman(19), "xix"), Objects.equals(s.intToMiniRoman(152), "clii"), Objects.equals(s.intToMiniRoman(251), "ccli"), Objects.equals(s.intToMiniRoman(426), "cdxxvi"), Objects.equals(s.intToMiniRoman(500), "d"), Objects.equals(s.intToMiniRoman(1), "i"), Objects.equals(s.intToMiniRoman(4), "iv"), Objects.equals(s.intToMiniRoman(43), "xliii"), Objects.equals(s.intToMiniRoman(90), "xc"), Objects.equals(s.intToMiniRoman(94), "xciv"), Objects.equals(s.intToMiniRoman(532), "dxxxii"), Objects.equals(s.intToMiniRoman(900), "cm"), Objects.equals(s.intToMiniRoman(994), "cmxciv"), Objects.equals(s.intToMiniRoman(1000), "m") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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(); } }
humaneval-x-java_data_Java_157
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.rightAngleTriangle(3, 4, 5) == true, s.rightAngleTriangle(1, 2, 3) == false, s.rightAngleTriangle(10, 6, 8) == true, s.rightAngleTriangle(2, 2, 2) == false, s.rightAngleTriangle(7, 24, 25) == true, s.rightAngleTriangle(10, 5, 7) == false, s.rightAngleTriangle(5, 12, 13) == true, s.rightAngleTriangle(15, 8, 17) == true, s.rightAngleTriangle(48, 55, 73) == true, s.rightAngleTriangle(1, 1, 1) == false, s.rightAngleTriangle(2, 2, 10) == false ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }
humaneval-x-java_data_Java_158
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.findMax(new ArrayList<>(Arrays.asList("name", "of", "string"))).equals("string"), s.findMax(new ArrayList<>(Arrays.asList("name", "enam", "game"))).equals("enam"), s.findMax(new ArrayList<>(Arrays.asList("aaaaaaa", "bb", "cc"))).equals("aaaaaaa"), s.findMax(new ArrayList<>(Arrays.asList("abc", "cba"))).equals("abc"), s.findMax(new ArrayList<>(Arrays.asList("play", "this", "game", "of", "footbott"))).equals("footbott"), s.findMax(new ArrayList<>(Arrays.asList("we", "are", "gonna", "rock"))).equals("gonna"), s.findMax(new ArrayList<>(Arrays.asList("we", "are", "a", "mad", "nation"))).equals("nation"), s.findMax(new ArrayList<>(Arrays.asList("this", "is", "a", "prrk"))).equals("this"), s.findMax(new ArrayList<>(List.of("b"))).equals("b"), s.findMax(new ArrayList<>(Arrays.asList("play", "play", "play"))).equals("play") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_159
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.eat(5, 6, 10).equals(Arrays.asList(11, 4)), s.eat(4, 8, 9).equals(Arrays.asList(12, 1)), s.eat(1, 10, 10).equals(Arrays.asList(11, 0)), s.eat(2, 11, 5).equals(Arrays.asList(7, 0)), s.eat(4, 5, 7).equals(Arrays.asList(9, 2)), s.eat(4, 5, 1).equals(Arrays.asList(5, 0)) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } } }
humaneval-x-java_data_Java_160
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.doAlgebra(new ArrayList<>(Arrays.asList("**", "*", "+")), new ArrayList<>(Arrays.asList(2, 3, 4, 5))) == 37, s.doAlgebra(new ArrayList<>(Arrays.asList("+", "*", "-")), new ArrayList<>(Arrays.asList(2, 3, 4, 5))) == 9, s.doAlgebra(new ArrayList<>(Arrays.asList("/", "*")), new ArrayList<>(Arrays.asList(7, 3, 4))) == 8, s.doAlgebra(new ArrayList<>(Arrays.asList("+", "**", "**")), new ArrayList<>(Arrays.asList(7, 5, 3, 2))) == 1953132 ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_161
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( Objects.equals(s.solve("AsDf"), "aSdF"), Objects.equals(s.solve("1234"), "4321"), Objects.equals(s.solve("ab"), "AB"), Objects.equals(s.solve("#a@C"), "#A@c"), Objects.equals(s.solve("#AsdfW^45"), "#aSDFw^45"), Objects.equals(s.solve("#6@2"), "2@6#"), Objects.equals(s.solve("#$a^D"), "#$A^d"), Objects.equals(s.solve("#ccc"), "#CCC") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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(); } }
humaneval-x-java_data_Java_162
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 class Main { public static void main(String[] args) throws NoSuchAlgorithmException { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.stringToMd5("Hello world").get().equals("3e25960a79dbc69b674cd4ec67a72c62"), s.stringToMd5("").isEmpty(), s.stringToMd5("A B C").get().equals("0ef78513b0cb8cef12743f5aeb35f888"), s.stringToMd5("password").get().equals("5f4dcc3b5aa765d61d8327deb882cf99") ); if (correct.contains(false)) { throw new AssertionError(); } } } 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); } }
humaneval-x-java_data_Java_163
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 class Main { public static void main(String[] args) { Solution s = new Solution(); List<Boolean> correct = Arrays.asList( s.generateIntegers(2, 10).equals(Arrays.asList(2, 4, 6, 8)), s.generateIntegers(10, 2).equals(Arrays.asList(2, 4, 6, 8)), s.generateIntegers(132, 2).equals(Arrays.asList(2, 4, 6, 8)), s.generateIntegers(17, 89).equals(List.of()) ); if (correct.contains(false)) { throw new AssertionError(); } } } 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; } }