id
stringlengths 28
30
| content
stringlengths 701
6k
|
|---|---|
humaneval-x-java_data_Java_0
|
Check if in given list of numbers, are any two numbers closer to each other than given threshold.
>>> hasCloseElements(Arrays.asList(1.0, 2.0, 3.0), 0.5)
false
>>> hasCloseElements(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3)
true
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.hasCloseElements(new ArrayList<>(Arrays.asList(11.0, 2.0, 3.9, 4.0, 5.0, 2.2)), 0.3),
!s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.9, 4.0, 5.0, 2.2)), 0.05),
s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 5.9, 4.0, 5.0)), 0.95),
!s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 5.9, 4.0, 5.0)), 0.8),
s.hasCloseElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.0)), 0.1),
s.hasCloseElements(new ArrayList<>(Arrays.asList(1.1, 2.2, 3.1, 4.1, 5.1)), 1.0),
!s.hasCloseElements(new ArrayList<>(Arrays.asList(1.1, 2.2, 3.1, 4.1, 5.1)), 0.5)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Check if in given list of numbers, are any two numbers closer to each other than given threshold.
>>> hasCloseElements(Arrays.asList(1.0, 2.0, 3.0), 0.5)
false
>>> hasCloseElements(Arrays.asList(1.0, 2.8, 3.0, 4.0, 5.0, 2.0), 0.3)
true
*/
public boolean hasCloseElements(List<Double> numbers, double threshold) {
for (int i = 0; i < numbers.size(); i++) {
for (int j = i + 1; j < numbers.size(); j++) {
double distance = Math.abs(numbers.get(i) - numbers.get(j));
if (distance < threshold) return true;
}
}
return false;
}
}
|
humaneval-x-java_data_Java_1
|
Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separateParenGroups("( ) (( )) (( )( ))")
["()", "(())", "(()())"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.separateParenGroups("(()()) ((())) () ((())()())").equals(Arrays.asList(
"(()())", "((()))", "()", "((())()())"
)),
s.separateParenGroups("() (()) ((())) (((())))").equals(Arrays.asList(
"()", "(())", "((()))", "(((())))"
)),
s.separateParenGroups("(()(())((())))").equals(Arrays.asList(
"(()(())((())))"
)),
s.separateParenGroups("( ) (( )) (( )( ))").equals(Arrays.asList("()", "(())", "(()())"))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separateParenGroups("( ) (( )) (( )( ))")
["()", "(())", "(()())"]
*/
public List<String> separateParenGroups(String paren_string) {
List<String> result = new ArrayList<>();
StringBuilder current_string = new StringBuilder();
int current_depth = 0;
for (char c : paren_string.toCharArray()) {
if (c == '(') {
current_depth += 1;
current_string.append(c);
} else if (c == ')') {
current_depth -= 1;
current_string.append(c);
if (current_depth == 0) {
result.add(current_string.toString());
current_string.setLength(0);
}
}
}
return result;
}
}
|
humaneval-x-java_data_Java_2
|
Given a positive floating point number, it can be decomposed into
and integer part (largest integer smaller than given number) and decimals
(leftover part always smaller than 1).
Return the decimal part of the number.
>>> truncateNumber(3.5)
0.5
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.truncateNumber(3.5) == 0.5,
Math.abs(s.truncateNumber(1.33) - 0.33) < 1e-6,
Math.abs(s.truncateNumber(123.456) - 0.456) < 1e-6
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a positive floating point number, it can be decomposed into
and integer part (largest integer smaller than given number) and decimals
(leftover part always smaller than 1).
Return the decimal part of the number.
>>> truncateNumber(3.5)
0.5
*/
public double truncateNumber(double number) {
return number % 1.0;
}
}
|
humaneval-x-java_data_Java_3
|
You're given a list of deposit and withdrawal operations on a bank account that starts with
zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
at that point function should return True. Otherwise it should return False.
>>> belowZero(Arrays.asList(1, 2, 3))
false
>>> belowZero(Arrays.asList(1, 2, -4, 5))
true
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.belowZero(new ArrayList<>(Arrays.asList())),
!s.belowZero(new ArrayList<>(Arrays.asList(1, 2, -3, 1, 2, -3))),
s.belowZero(new ArrayList<>(Arrays.asList(1, 2, -4, 5, 6))),
!s.belowZero(new ArrayList<>(Arrays.asList(1, -1, 2, -2, 5, -5, 4, -4))),
s.belowZero(new ArrayList<>(Arrays.asList(1, -1, 2, -2, 5, -5, 4, -5))),
s.belowZero(new ArrayList<>(Arrays.asList(1, -2, 2, -2, 5, -5, 4, -4)))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You're given a list of deposit and withdrawal operations on a bank account that starts with
zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
at that point function should return True. Otherwise it should return False.
>>> belowZero(Arrays.asList(1, 2, 3))
false
>>> belowZero(Arrays.asList(1, 2, -4, 5))
true
*/
public boolean belowZero(List<Integer> operations) {
int balance = 0;
for (int op : operations) {
balance += op;
if (balance < 0) {
return true;
}
}
return false;
}
}
|
humaneval-x-java_data_Java_4
|
For a given list of input numbers, calculate Mean Absolute Deviation
around the mean of this dataset.
Mean Absolute Deviation is the average absolute difference between each
element and a centerpoint (mean in this case):
MAD = average | x - x_mean |
>>> meanAbsoluteDeviation(Arrays.asList(1.0, 2.0, 3.0, 4.0))
1.0
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Math.abs(s.meanAbsoluteDeviation(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0))) - 2.0/3.0) < 1e-6,
Math.abs(s.meanAbsoluteDeviation(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0))) - 1.0) < 1e-6,
Math.abs(s.meanAbsoluteDeviation(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0))) - 6.0/5.0) < 1e-6
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
For a given list of input numbers, calculate Mean Absolute Deviation
around the mean of this dataset.
Mean Absolute Deviation is the average absolute difference between each
element and a centerpoint (mean in this case):
MAD = average | x - x_mean |
>>> meanAbsoluteDeviation(Arrays.asList(1.0, 2.0, 3.0, 4.0))
1.0
*/
public double meanAbsoluteDeviation(List<Double> numbers) {
double sum = 0.0;
for (double num : numbers) {
sum += num;
}
double mean = sum / numbers.size();
double sum_abs_diff = 0.0;
for (double num : numbers) {
sum_abs_diff += Math.abs(num - mean);
}
return sum_abs_diff / numbers.size();
}
}
|
humaneval-x-java_data_Java_5
|
Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
>>> intersperse(List.of(), 4)
[]
>>> intersperse(Arrays.asList(1, 2, 3), 4)
[1, 4, 2, 4, 3]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.intersperse(new ArrayList<>(List.of()), 7).equals(List.of()),
s.intersperse(new ArrayList<>(Arrays.asList(5, 6, 3, 2)), 8).equals(Arrays.asList(5, 8, 6, 8, 3, 8, 2)),
s.intersperse(new ArrayList<>(Arrays.asList(2, 2, 2)), 2).equals(Arrays.asList(2, 2, 2, 2, 2))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
>>> intersperse(List.of(), 4)
[]
>>> intersperse(Arrays.asList(1, 2, 3), 4)
[1, 4, 2, 4, 3]
*/
public List<Integer> intersperse(List<Integer> numbers, int delimiter) {
if (numbers.size() == 0) {
return List.of();
}
List<Integer> result = new ArrayList<>(List.of());
for (int i = 0; i < numbers.size() - 1; i++) {
result.add(numbers.get(i));
result.add(delimiter);
}
result.add(numbers.get(numbers.size() - 1));
return result;
}
}
|
humaneval-x-java_data_Java_6
|
Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
For each of the group, output the deepest level of nesting of parentheses.
E.g. (()()) has maximum two levels of nesting while ((())) has three.
>>> parseNestedParens("(()()) ((())) () ((())()())")
[2, 3, 1, 3]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.parseNestedParens("(()()) ((())) () ((())()())").equals(Arrays.asList(2, 3, 1, 3)),
s.parseNestedParens("() (()) ((())) (((())))").equals(Arrays.asList(1, 2, 3, 4)),
s.parseNestedParens("(()(())((())))").equals(Arrays.asList(4))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
For each of the group, output the deepest level of nesting of parentheses.
E.g. (()()) has maximum two levels of nesting while ((())) has three.
>>> parseNestedParens("(()()) ((())) () ((())()())")
[2, 3, 1, 3]
*/
public List<Integer> parseNestedParens(String paren_string) {
String[] groups = paren_string.split(" ");
List<Integer> result = new ArrayList<>(List.of());
for (String group : groups) {
if (group.length() > 0) {
int depth = 0;
int max_depth = 0;
for (char c : group.toCharArray()) {
if (c == '(') {
depth += 1;
max_depth = Math.max(depth, max_depth);
} else {
depth -= 1;
}
}
result.add(max_depth);
}
}
return result;
}
}
|
humaneval-x-java_data_Java_7
|
Filter an input list of strings only for ones that contain given substring
>>> filterBySubstring(List.of(), "a")
[]
>>> filterBySubstring(Arrays.asList("abc", "bacd", "cde", "array"), "a")
["abc", "bacd", "array"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.filterBySubstring(new ArrayList<>(List.of()), "john").equals(List.of()),
s.filterBySubstring(new ArrayList<>(Arrays.asList("xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx")), "xxx").equals(Arrays.asList("xxx", "xxxAAA", "xxx")),
s.filterBySubstring(new ArrayList<>(Arrays.asList("xxx", "asd", "aaaxxy", "john doe", "xxxAAA", "xxx")), "xx").equals(Arrays.asList("xxx", "aaaxxy", "xxxAAA", "xxx")),
s.filterBySubstring(new ArrayList<>(Arrays.asList("grunt", "trumpet", "prune", "gruesome")), "run").equals(Arrays.asList("grunt", "prune"))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Filter an input list of strings only for ones that contain given substring
>>> filterBySubstring(List.of(), "a")
[]
>>> filterBySubstring(Arrays.asList("abc", "bacd", "cde", "array"), "a")
["abc", "bacd", "array"]
*/
public List<String> filterBySubstring(List<String> strings, String substring) {
List<String> result = new ArrayList<>();
for (String x : strings) {
if (x.contains(substring)) {
result.add(x);
}
}
return result;
}
}
|
humaneval-x-java_data_Java_8
|
For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
Empty sum should be equal to 0 and empty product should be equal to 1.
>>> sumProduct(List.of())
[0, 1]
>>> sumProduct(Arrays.asList(1, 2, 3, 4))
[10, 24]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sumProduct(new ArrayList<>(List.of())).equals(Arrays.asList(0, 1)),
s.sumProduct(new ArrayList<>(Arrays.asList(1, 1, 1))).equals(Arrays.asList(3, 1)),
s.sumProduct(new ArrayList<>(Arrays.asList(100, 0))).equals(Arrays.asList(100, 0)),
s.sumProduct(new ArrayList<>(Arrays.asList(3, 5, 7))).equals(Arrays.asList(3 + 5 + 7, 3 * 5 * 7)),
s.sumProduct(new ArrayList<>(List.of(10))).equals(Arrays.asList(10, 10))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
Empty sum should be equal to 0 and empty product should be equal to 1.
>>> sumProduct(List.of())
[0, 1]
>>> sumProduct(Arrays.asList(1, 2, 3, 4))
[10, 24]
*/
public List<Integer> sumProduct(List<Integer> numbers) {
int sum = 0;
int product = 1;
for (int n : numbers) {
sum += n;
product *= n;
}
return Arrays.asList(sum, product);
}
}
|
humaneval-x-java_data_Java_9
|
From a given list of integers, generate a list of rolling maximum element found until given moment
in the sequence.
>>> rollingMax(Arrays.asList(1, 2, 3, 2, 3, 4, 2))
[1, 2, 3, 3, 3, 4, 4]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.rollingMax(new ArrayList<>(List.of())).equals(List.of()),
s.rollingMax(new ArrayList<>(Arrays.asList(1, 2, 3, 4))).equals(Arrays.asList(1, 2, 3, 4)),
s.rollingMax(new ArrayList<>(Arrays.asList(4, 3, 2, 1))).equals(Arrays.asList(4, 4, 4, 4)),
s.rollingMax(new ArrayList<>(Arrays.asList(3, 2, 3, 100, 3))).equals(Arrays.asList(3, 3, 3, 100, 100))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
From a given list of integers, generate a list of rolling maximum element found until given moment
in the sequence.
>>> rollingMax(Arrays.asList(1, 2, 3, 2, 3, 4, 2))
[1, 2, 3, 3, 3, 4, 4]
*/
public List<Integer> rollingMax(List<Integer> numbers) {
List<Integer> result = new ArrayList<>();
if (numbers.size() == 0) {
return result;
}
int rollingMax = numbers.get(0);
result.add(rollingMax);
for (int i = 1; i < numbers.size(); i++) {
if (numbers.get(i) > rollingMax) {
rollingMax = numbers.get(i);
}
result.add(rollingMax);
}
return result;
}
}
|
humaneval-x-java_data_Java_10
|
Find the shortest palindrome that begins with a supplied string.
Algorithm idea is simple:
- Find the longest postfix of supplied string that is a palindrome.
- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
>>> makePalindrome("")
""
>>> makePalindrome("cat")
"catac"
>>> makePalindrome("cata")
"catac"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.makePalindrome(""), ""),
Objects.equals(s.makePalindrome("x"), "x"),
Objects.equals(s.makePalindrome("xyz"), "xyzyx"),
Objects.equals(s.makePalindrome("xyx"), "xyx"),
Objects.equals(s.makePalindrome("jerry"), "jerryrrej")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Test if given string is a palindrome
*/
public boolean isPalindrome(String string) {
int i = 0;
int j = string.length() - 1;
while (i < j) {
if (string.charAt(i)!= string.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
/**
Find the shortest palindrome that begins with a supplied string.
Algorithm idea is simple:
- Find the longest postfix of supplied string that is a palindrome.
- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
>>> makePalindrome("")
""
>>> makePalindrome("cat")
"catac"
>>> makePalindrome("cata")
"catac"
*/
public String makePalindrome(String string) {
if (string.length() == 0) {
return "";
}
int beginning_of_suffix = 0;
while (!isPalindrome(string.substring(beginning_of_suffix))) {
beginning_of_suffix++;
}
return string + new StringBuffer(string.substring(0, beginning_of_suffix)).reverse().toString();
}
}
|
humaneval-x-java_data_Java_11
|
Input are two strings a and b consisting only of 1s and 0s.
Perform binary XOR on these inputs and return result also as a string.
>>> stringXor("010", "110")
"100"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.stringXor("111000", "101010"), "010010"),
Objects.equals(s.stringXor("1", "1"), "0"),
Objects.equals(s.stringXor("0101", "0000"), "0101")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Input are two strings a and b consisting only of 1s and 0s.
Perform binary XOR on these inputs and return result also as a string.
>>> stringXor("010", "110")
"100"
*/
public String stringXor(String a, String b) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == b.charAt(i)) {
result.append("0");
} else {
result.append("1");
}
}
return result.toString();
}
}
|
humaneval-x-java_data_Java_12
|
Out of list of strings, return the longest one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> longest(List.of())
Optional.empty
>>> longest(Arrays.asList("a", "b", "c"))
Optional[a]
>>> longest(Arrays.asList("a", "bb", "ccc"))
Optional[ccc]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.longest(new ArrayList<>(List.of())).isEmpty(),
Objects.equals(s.longest(new ArrayList<>(Arrays.asList("x", "y", "z"))).get(), "x"),
Objects.equals(s.longest(new ArrayList<>(Arrays.asList("x", "yyy", "zzzz", "www", "kkkk", "abc"))).get(), "zzzz")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Out of list of strings, return the longest one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> longest(List.of())
Optional.empty
>>> longest(Arrays.asList("a", "b", "c"))
Optional[a]
>>> longest(Arrays.asList("a", "bb", "ccc"))
Optional[ccc]
*/
public Optional<String> longest(List<String> strings) {
if (strings.isEmpty()) {
return Optional.empty();
}
String longest = strings.get(0);
for (String s : strings) {
if (s.length() > longest.length()) {
longest = s;
}
}
return Optional.of(longest);
}
}
|
humaneval-x-java_data_Java_13
|
Return a greatest common divisor of two integers a and b
>>> greatestCommonDivisor(3, 5)
1
>>> greatestCommonDivisor(25, 15)
5
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.greatestCommonDivisor(3, 7) == 1,
s.greatestCommonDivisor(10, 15) == 5,
s.greatestCommonDivisor(49, 14) == 7,
s.greatestCommonDivisor(144, 60) == 12
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return a greatest common divisor of two integers a and b
>>> greatestCommonDivisor(3, 5)
1
>>> greatestCommonDivisor(25, 15)
5
*/
public int greatestCommonDivisor(int a, int b) {
if (a == 0 || b == 0) {
return a + b;
}
if (a == b) {
return a;
}
if (a > b) {
return greatestCommonDivisor(a % b, b);
} else {
return greatestCommonDivisor(a, b % a);
}
}
}
|
humaneval-x-java_data_Java_14
|
Return list of all prefixes from shortest to longest of the input string
>>> allPrefixes("abc")
["a", "ab", "abc"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.allPrefixes("").equals(List.of()),
s.allPrefixes("asdfgh").equals(Arrays.asList("a", "as", "asd", "asdf", "asdfg", "asdfgh")),
s.allPrefixes("WWW").equals(Arrays.asList("W", "WW", "WWW"))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return list of all prefixes from shortest to longest of the input string
>>> allPrefixes("abc")
["a", "ab", "abc"]
*/
public List<String> allPrefixes(String string) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= string.length(); i++) {
result.add(string.substring(0, i));
}
return result;
}
}
|
humaneval-x-java_data_Java_15
|
Return a string containing space-delimited numbers starting from 0 upto n inclusive.
>>> stringSequence(0)
"0"
>>> stringSequence(5)
"0 1 2 3 4 5"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.stringSequence(0).equals("0"),
s.stringSequence(3).equals("0 1 2 3"),
s.stringSequence(10).equals("0 1 2 3 4 5 6 7 8 9 10")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return a string containing space-delimited numbers starting from 0 upto n inclusive.
>>> stringSequence(0)
"0"
>>> stringSequence(5)
"0 1 2 3 4 5"
*/
public String stringSequence(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(i);
sb.append(" ");
}
sb.append(n);
return sb.toString();
}
}
|
humaneval-x-java_data_Java_16
|
Given a string, find out how many distinct characters (regardless of case) does it consist of
>>> countDistinctCharacters("xyzXYZ")
3
>>> countDistinctCharacters("Jerry")
4
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.countDistinctCharacters("") == 0,
s.countDistinctCharacters("abcde") == 5,
s.countDistinctCharacters("abcde" + "cade" + "CADE") == 5,
s.countDistinctCharacters("aaaaAAAAaaaa") == 1,
s.countDistinctCharacters("Jerry jERRY JeRRRY") == 5
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a string, find out how many distinct characters (regardless of case) does it consist of
>>> countDistinctCharacters("xyzXYZ")
3
>>> countDistinctCharacters("Jerry")
4
*/
public int countDistinctCharacters(String string) {
Set<Character> set = new HashSet<>();
for (char c : string.toLowerCase().toCharArray()) {
set.add(c);
}
return set.size();
}
}
|
humaneval-x-java_data_Java_17
|
Input to this function is a string representing musical notes in a special ASCII format.
Your task is to parse this string and return list of integers corresponding to how many beats does each
not last.
Here is a legend:
"o" - whole note, lasts four beats
"o|" - half note, lasts two beats
".|" - quater note, lasts one beat
>>> parseMusic("o o| .| o| o| .| .| .| .| o o")
[4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.parseMusic("").equals(List.of()),
s.parseMusic("o o o o").equals(Arrays.asList(4, 4, 4, 4)),
s.parseMusic(".| .| .| .|").equals(Arrays.asList(1, 1, 1, 1)),
s.parseMusic("o| o| .| .| o o o o").equals(Arrays.asList(2, 2, 1, 1, 4, 4, 4, 4)),
s.parseMusic("o| .| o| .| o o| o o|").equals(Arrays.asList(2, 1, 2, 1, 4, 2, 4, 2))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Input to this function is a string representing musical notes in a special ASCII format.
Your task is to parse this string and return list of integers corresponding to how many beats does each
not last.
Here is a legend:
"o" - whole note, lasts four beats
"o|" - half note, lasts two beats
".|" - quater note, lasts one beat
>>> parseMusic("o o| .| o| o| .| .| .| .| o o")
[4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
*/
public List<Integer> parseMusic(String string) {
String[] notes = string.split(" ");
List<Integer> result = new ArrayList<>();
for (String s : notes) {
switch (s) {
case "o" -> result.add(4);
case "o|" -> result.add(2);
case ".|" -> result.add(1);
}
}
return result;
}
}
|
humaneval-x-java_data_Java_18
|
Find how many times a given substring can be found in the original string. Count overlaping cases.
>>> howManyTimes("", "a")
0
>>> howManyTimes("aaa", "a")
3
>>> howManyTimes("aaaa", "aa")
3
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.howManyTimes("", "x") == 0,
s.howManyTimes("xyxyxyx", "x") == 4,
s.howManyTimes("cacacacac", "cac") == 4,
s.howManyTimes("john doe", "john") == 1
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Find how many times a given substring can be found in the original string. Count overlaping cases.
>>> howManyTimes("", "a")
0
>>> howManyTimes("aaa", "a")
3
>>> howManyTimes("aaaa", "aa")
3
*/
public int howManyTimes(String string, String substring) {
int times = 0;
for (int i = 0; i < string.length() - substring.length() + 1; i++) {
if (string.substring(i, i + substring.length()).equals(substring)) {
times += 1;
}
}
return times;
}
}
|
humaneval-x-java_data_Java_19
|
Input is a space-delimited string of numberals from 'zero' to 'nine'.
Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
Return the string with numbers sorted from smallest to largest
>>> sortNumbers("three one five")
"one three five"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sortNumbers("").equals(""),
s.sortNumbers("three").equals("three"),
s.sortNumbers("three five nine").equals("three five nine"),
s.sortNumbers("five zero four seven nine eight").equals("zero four five seven eight nine")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Input is a space-delimited string of numberals from 'zero' to 'nine'.
Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
Return the string with numbers sorted from smallest to largest
>>> sortNumbers("three one five")
"one three five"
*/
public String sortNumbers(String numbers) {
String[] nums = numbers.split(" ");
List<Integer> num = new ArrayList<>();
for (String string : nums) {
switch (string) {
case "zero" -> num.add(0);
case "one" -> num.add(1);
case "two" -> num.add(2);
case "three" -> num.add(3);
case "four" -> num.add(4);
case "five" -> num.add(5);
case "six" -> num.add(6);
case "seven" -> num.add(7);
case "eight" -> num.add(8);
case "nine" -> num.add(9);
}
}
Collections.sort(num);
List<String> result = new ArrayList<>();
for (int m : num) {
switch (m) {
case 0 -> result.add("zero");
case 1 -> result.add("one");
case 2 -> result.add("two");
case 3 -> result.add("three");
case 4 -> result.add("four");
case 5 -> result.add("five");
case 6 -> result.add("six");
case 7 -> result.add("seven");
case 8 -> result.add("eight");
case 9 -> result.add("nine");
}
}
return String.join(" ", result);
}
}
|
humaneval-x-java_data_Java_20
|
From a supplied list of numbers (of length at least two) select and return two that are the closest to each
other and return them in order (smaller number, larger number).
>>> findClosestElements(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.2))
[2.0, 2.2]
>>> findClosestElements(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.0))
[2.0, 2.0]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.findClosestElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.9, 4.0, 5.0, 2.2))).equals(Arrays.asList(3.9, 4.0)),
s.findClosestElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 5.9, 4.0, 5.0))).equals(Arrays.asList(5.0, 5.9)),
s.findClosestElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.2))).equals(Arrays.asList(2.0, 2.2)),
s.findClosestElements(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.0))).equals(Arrays.asList(2.0, 2.0)),
s.findClosestElements(new ArrayList<>(Arrays.asList(1.1, 2.2, 3.1, 4.1, 5.1))).equals(Arrays.asList(2.2, 3.1))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
From a supplied list of numbers (of length at least two) select and return two that are the closest to each
other and return them in order (smaller number, larger number).
>>> findClosestElements(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.2))
[2.0, 2.2]
>>> findClosestElements(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 2.0))
[2.0, 2.0]
*/
public List<Double> findClosestElements(List<Double> numbers) {
List<Double> closest_pair = new ArrayList<>();
closest_pair.add(numbers.get(0));
closest_pair.add(numbers.get(1));
double distance = Math.abs(numbers.get(1) - numbers.get(0));
for (int i = 0; i < numbers.size(); i++) {
for (int j = i + 1; j < numbers.size(); j++) {
if (Math.abs(numbers.get(i) - numbers.get(j)) < distance) {
closest_pair.clear();
closest_pair.add(numbers.get(i));
closest_pair.add(numbers.get(j));
distance = Math.abs(numbers.get(i) - numbers.get(j));
}
}
}
Collections.sort(closest_pair);
return closest_pair;
}
}
|
humaneval-x-java_data_Java_21
|
Given list of numbers (of at least two elements), apply a linear transform to that list,
such that the smallest number will become 0 and the largest will become 1
>>> rescaleToUnit(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0))
[0.0, 0.25, 0.5, 0.75, 1.0]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.rescaleToUnit(new ArrayList<>(Arrays.asList(2.0, 49.9))).equals(Arrays.asList(0.0, 1.0)),
s.rescaleToUnit(new ArrayList<>(Arrays.asList(100.0, 49.9))).equals(Arrays.asList(1.0, 0.0)),
s.rescaleToUnit(new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0))).equals(Arrays.asList(0.0, 0.25, 0.5, 0.75, 1.0)),
s.rescaleToUnit(new ArrayList<>(Arrays.asList(2.0, 1.0, 5.0, 3.0, 4.0))).equals(Arrays.asList(0.25, 0.0, 1.0, 0.5, 0.75)),
s.rescaleToUnit(new ArrayList<>(Arrays.asList(12.0, 11.0, 15.0, 13.0, 14.0))).equals(Arrays.asList(0.25, 0.0, 1.0, 0.5, 0.75))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given list of numbers (of at least two elements), apply a linear transform to that list,
such that the smallest number will become 0 and the largest will become 1
>>> rescaleToUnit(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0))
[0.0, 0.25, 0.5, 0.75, 1.0]
*/
public List<Double> rescaleToUnit(List<Double> numbers) {
double min_number = Collections.min(numbers);
double max_number = Collections.max(numbers);
List<Double> result = new ArrayList<>();
for (double x : numbers) {
result.add((x - min_number) / (max_number - min_number));
}
return result;
}
}
|
humaneval-x-java_data_Java_22
|
Filter given list of any values only for integers
>>> filter_integers(Arrays.asList('a', 3.14, 5))
[5]
>>> filter_integers(Arrays.asList(1, 2, 3, "abc", Map.of(), List.of()))
[1, 2, 3]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.filterIntergers(new ArrayList<>(List.of())).equals(List.of()),
s.filterIntergers(new ArrayList<>(Arrays.asList(4, Map.of(), List.of(), 23.2, 9, "adasd"))).equals(Arrays.asList(4, 9)),
s.filterIntergers(new ArrayList<>(Arrays.asList(3, 'c', 3, 3, 'a', 'b'))).equals(Arrays.asList(3, 3, 3))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Filter given list of any values only for integers
>>> filter_integers(Arrays.asList('a', 3.14, 5))
[5]
>>> filter_integers(Arrays.asList(1, 2, 3, "abc", Map.of(), List.of()))
[1, 2, 3]
*/
public List<Integer> filterIntergers(List<Object> values) {
List<Integer> result = new ArrayList<>();
for (Object x : values) {
if (x instanceof Integer) {
result.add((Integer) x);
}
}
return result;
}
}
|
humaneval-x-java_data_Java_23
|
Return length of given string
>>> strlen("")
0
>>> strlen("abc")
3
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.strlen("") == 0,
s.strlen("x") == 1,
s.strlen("asdasnakj") == 9
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return length of given string
>>> strlen("")
0
>>> strlen("abc")
3
*/
public int strlen(String string) {
return string.length();
}
}
|
humaneval-x-java_data_Java_24
|
For a given number n, find the largest number that divides n evenly, smaller than n
>>> largestDivisor(15)
5
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.largestDivisor(3) == 1,
s.largestDivisor(7) == 1,
s.largestDivisor(10) == 5,
s.largestDivisor(100) == 50,
s.largestDivisor(49) == 7
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
For a given number n, find the largest number that divides n evenly, smaller than n
>>> largestDivisor(15)
5
*/
public int largestDivisor(int n) {
for (int i = n - 1; i > 0; i--) {
if (n % i == 0) {
return i;
}
}
return 1;
}
}
|
humaneval-x-java_data_Java_25
|
Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the product of all factors
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.factorize(2).equals(List.of(2)),
s.factorize(4).equals(Arrays.asList(2, 2)),
s.factorize(8).equals(Arrays.asList(2, 2, 2)),
s.factorize(3 * 19).equals(Arrays.asList(3, 19)),
s.factorize(3 * 19 * 3 * 19).equals(Arrays.asList(3, 3, 19, 19)),
s.factorize(3 * 19 * 3 * 19 * 3 * 19).equals(Arrays.asList(3, 3, 3, 19, 19, 19)),
s.factorize(3 * 19 * 19 * 19).equals(Arrays.asList(3, 19, 19, 19)),
s.factorize(3 * 2 * 3).equals(Arrays.asList(2, 3, 3))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the product of all factors
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
*/
public List<Integer> factorize(int n) {
List<Integer> fact = new ArrayList<>();
int i = 2;
while (n > 1) {
if (n % i == 0) {
fact.add(i);
n /= i;
} else {
i++;
}
}
return fact;
}
}
|
humaneval-x-java_data_Java_26
|
From a list of integers, remove all elements that occur more than once.
Keep order of elements left the same as in the input.
>>> removeDuplicates(Array.asList(1, 2, 3, 2, 4))
[1, 3, 4]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.removeDuplicates(new ArrayList<>(List.of())).equals(List.of()),
s.removeDuplicates(new ArrayList<>(Arrays.asList(1, 2, 3, 4))).equals(Arrays.asList(1, 2, 3, 4)),
s.removeDuplicates(new ArrayList<>(Arrays.asList(1, 2, 3, 2, 4, 3, 5))).equals(Arrays.asList(1, 4, 5))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;
class Solution {
/**
From a list of integers, remove all elements that occur more than once.
Keep order of elements left the same as in the input.
>>> removeDuplicates(Array.asList(1, 2, 3, 2, 4))
[1, 3, 4]
*/
public List<Integer> removeDuplicates(List<Integer> numbers) {
Map<Integer, Integer> c = new HashMap<>();
for (int i : numbers) {
c.put(i, c.getOrDefault(i, 0) + 1);
}
return numbers.stream().filter(i -> c.get(i) == 1).collect(Collectors.toList());
}
}
|
humaneval-x-java_data_Java_27
|
For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
>>> flipCase("Hello")
"hELLO"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.flipCase(""), ""),
Objects.equals(s.flipCase("Hello!"), "hELLO!"),
Objects.equals(s.flipCase("These violent delights have violent ends"), "tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
>>> flipCase("Hello")
"hELLO"
*/
public String flipCase(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
if (Character.isLowerCase(string.charAt(i))) {
sb.append(Character.toUpperCase(string.charAt(i)));
} else {
sb.append(Character.toLowerCase(string.charAt(i)));
}
}
return sb.toString();
}
}
|
humaneval-x-java_data_Java_28
|
Concatenate list of strings into a single string
>>> concatenate(List.of())
""
>>> concatenate(Arrays.asList("a", "b", "c"))
"abc"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.concatenate(new ArrayList<>(List.of())), ""),
Objects.equals(s.concatenate(new ArrayList<>(Arrays.asList("x", "y", "z"))), "xyz"),
Objects.equals(s.concatenate(new ArrayList<>(Arrays.asList("x", "y", "z", "w", "k"))), "xyzwk")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Concatenate list of strings into a single string
>>> concatenate(List.of())
""
>>> concatenate(Arrays.asList("a", "b", "c"))
"abc"
*/
public String concatenate(List<String> strings) {
return String.join("", strings);
}
}
|
humaneval-x-java_data_Java_29
|
Filter an input list of strings only for ones that start with a given prefix.
>>> filterByPrefix(List.of(), "a")
[]
>>> filterByPrefix(Arrays.asList("abc", "bcd", "cde", "array"), "a")
["abc", "array"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.filterByPrefix(new ArrayList<>(List.of()), "john").equals(List.of()),
s.filterByPrefix(new ArrayList<>(Arrays.asList("xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx")), "xxx").equals(Arrays.asList("xxx", "xxxAAA", "xxx"))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;
class Solution {
/**
Filter an input list of strings only for ones that start with a given prefix.
>>> filterByPrefix(List.of(), "a")
[]
>>> filterByPrefix(Arrays.asList("abc", "bcd", "cde", "array"), "a")
["abc", "array"]
*/
public List<String> filterByPrefix(List<String> strings, String prefix) {
return strings.stream().filter(p -> p.startsWith(prefix)).collect(Collectors.toList());
}
}
|
humaneval-x-java_data_Java_30
|
Return only positive numbers in the list.
>>> getPositive(Arrays.asList(-1, 2, -4, 5, 6))
[2, 5, 6]
>>> getPositive(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))
[5, 3, 2, 3, 9, 123, 1]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.getPositive(new ArrayList<>(Arrays.asList(-1, -2, 4, 5, 6))).equals(Arrays.asList(4, 5, 6)),
s.getPositive(new ArrayList<>(Arrays.asList(5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10))).equals(Arrays.asList(5, 3, 2, 3, 3, 9, 123, 1)),
s.getPositive(new ArrayList<>(Arrays.asList(-1, -2))).equals(List.of()),
s.getPositive(List.of()).equals(List.of())
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;
class Solution {
/**
Return only positive numbers in the list.
>>> getPositive(Arrays.asList(-1, 2, -4, 5, 6))
[2, 5, 6]
>>> getPositive(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))
[5, 3, 2, 3, 9, 123, 1]
*/
public List<Integer> getPositive(List<Integer> l) {
return l.stream().filter(p -> p > 0).collect(Collectors.toList());
}
}
|
humaneval-x-java_data_Java_31
|
Return true if a given number is prime, and false otherwise.
>>> isPrime(6)
false
>>> isPrime(101)
true
>>> isPrime(11)
true
>>> isPrime(13441)
true
>>> isPrime(61)
true
>>> isPrime(4)
false
>>> isPrime(1)
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.isPrime(6),
s.isPrime(101),
s.isPrime(11),
s.isPrime(13441),
s.isPrime(61),
!s.isPrime(4),
!s.isPrime(1),
s.isPrime(5),
s.isPrime(11),
s.isPrime(17),
!s.isPrime(5 * 17),
!s.isPrime(11 * 7),
!s.isPrime(13441 * 19)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return true if a given number is prime, and false otherwise.
>>> isPrime(6)
false
>>> isPrime(101)
true
>>> isPrime(11)
true
>>> isPrime(13441)
true
>>> isPrime(61)
true
>>> isPrime(4)
false
>>> isPrime(1)
false
*/
public boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int k = 2; k < n; k++) {
if (n % k == 0) {
return false;
}
}
return true;
}
}
|
humaneval-x-java_data_Java_32
|
xs are coefficients of a polynomial.
findZero find x such that poly(x) = 0.
findZero returns only only zero point, even if there are many.
Moreover, findZero only takes list xs having even number of coefficients
and largest non zero coefficient as it guarantees
a solution.
>>> findZero(Arrays.asList(1, 2)) // f(x) = 1 + 2x
-0.5
>>> findZero(Arrays.asList(-6, 11, -6, 1)) // (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3
1.0
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
Random rand = new Random(42);
for (int i = 0; i < 100; i++) {
int ncoeff = 2 * (rand.nextInt(3) + 1);
List<Double> coeffs = new ArrayList<>();
for (int j = 0; j < ncoeff; j++) {
int coeff = rand.nextInt(20) - 10;
if (coeff == 0) {
coeff = 1;
}
coeffs.add((double) coeff);
}
double solution = s.findZero(coeffs);
if (Math.abs(s.poly(coeffs, solution)) > 1e-4) {
throw new AssertionError();
}
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Evaluates polynomial with coefficients xs at point x.
return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n
*/
public double poly(List<Double> xs, double x) {
double result = 0;
for (int i = 0; i < xs.size(); i++) {
result += xs.get(i) * Math.pow(x, i);
}
return result;
}
/**
xs are coefficients of a polynomial.
findZero find x such that poly(x) = 0.
findZero returns only only zero point, even if there are many.
Moreover, findZero only takes list xs having even number of coefficients
and largest non zero coefficient as it guarantees
a solution.
>>> findZero(Arrays.asList(1, 2)) // f(x) = 1 + 2x
-0.5
>>> findZero(Arrays.asList(-6, 11, -6, 1)) // (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3
1.0
*/
public double findZero(List<Double> xs) {
double begin = -1, end = 1;
while (poly(xs, begin) * poly(xs, end) > 0) {
begin *= 2;
end *= 2;
}
while (end - begin > 1e-10) {
double center = (begin + end) / 2;
if (poly(xs, begin) * poly(xs, center) > 0) {
begin = center;
} else {
end = center;
}
}
return begin;
}
}
|
humaneval-x-java_data_Java_33
|
This function takes a list l and returns a list l' such that
l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
to the values of the corresponding indicies of l, but sorted.
>>> sortThird(Arrays.asList(1, 2, 3))
[1, 2, 3]
>>> sortThird(Arrays.asList(5, 6, 3, 4, 8, 9, 2))
[2, 6, 3, 4, 8, 9, 5]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sortThird(new ArrayList<>(Arrays.asList(5, 6, 3, 4, 8, 9, 2))).equals(Arrays.asList(2, 6, 3, 4, 8, 9, 5)),
s.sortThird(new ArrayList<>(Arrays.asList(5, 8, 3, 4, 6, 9, 2))).equals(Arrays.asList(2, 8, 3, 4, 6, 9, 5)),
s.sortThird(new ArrayList<>(Arrays.asList(5, 6, 9, 4, 8, 3, 2))).equals(Arrays.asList(2, 6, 9, 4, 8, 3, 5)),
s.sortThird(new ArrayList<>(Arrays.asList(5, 6, 3, 4, 8, 9, 2, 1))).equals(Arrays.asList(2, 6, 3, 4, 8, 9, 5, 1))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
This function takes a list l and returns a list l' such that
l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
to the values of the corresponding indicies of l, but sorted.
>>> sortThird(Arrays.asList(1, 2, 3))
[1, 2, 3]
>>> sortThird(Arrays.asList(5, 6, 3, 4, 8, 9, 2))
[2, 6, 3, 4, 8, 9, 5]
*/
public List<Integer> sortThird(List<Integer> l) {
List<Integer> thirds = new ArrayList<>();
for (int i = 0; i < l.size(); i += 3) {
thirds.add(l.get(i));
}
Collections.sort(thirds);
List<Integer> result = l;
for (int i = 0; i < l.size(); i += 3) {
result.set(i, thirds.get(i / 3));
}
return result;
}
}
|
humaneval-x-java_data_Java_34
|
Return sorted unique elements in a list
>>> unique(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123))
[0, 2, 3, 5, 9, 123]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.unique(new ArrayList<>(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123))).equals(Arrays.asList(0, 2, 3, 5, 9, 123))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return sorted unique elements in a list
>>> unique(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123))
[0, 2, 3, 5, 9, 123]
*/
public List<Integer> unique(List<Integer> l) {
List<Integer> result = new ArrayList<>(new HashSet<>(l));
Collections.sort(result);
return result;
}
}
|
humaneval-x-java_data_Java_35
|
Return maximum element in the list.
>>> maxElement(Arrays.asList(1, 2, 3))
3
>>> maxElement(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))
123
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.maxElement(new ArrayList<>(Arrays.asList(1, 2, 3))) == 3,
s.maxElement(new ArrayList<>(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10))) == 124
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return maximum element in the list.
>>> maxElement(Arrays.asList(1, 2, 3))
3
>>> maxElement(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))
123
*/
public int maxElement(List<Integer> l) {
return Collections.max(l);
}
}
|
humaneval-x-java_data_Java_36
|
Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
>>> fizzBuzz(50)
0
>>> fizzBuzz(78)
2
>>> fizzBuzz(79)
3
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.fizzBuzz(50) == 0,
s.fizzBuzz(78) == 2,
s.fizzBuzz(79) == 3,
s.fizzBuzz(100) == 3,
s.fizzBuzz(200) == 6,
s.fizzBuzz(4000) == 192,
s.fizzBuzz(10000) == 639,
s.fizzBuzz(100000) == 8026
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
>>> fizzBuzz(50)
0
>>> fizzBuzz(78)
2
>>> fizzBuzz(79)
3
*/
public int fizzBuzz(int n) {
int result = 0;
for (int i = 1; i < n; i++) {
if (i % 11 == 0 || i % 13 == 0) {
char[] digits = String.valueOf(i).toCharArray();
for (char c : digits) {
if (c == '7') {
result += 1;
}
}
}
}
return result;
}
}
|
humaneval-x-java_data_Java_37
|
This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sorted.
>>> sortEven(Arrays.asList(1, 2, 3))
[1, 2, 3]
>>> sortEven(Arrays.asList(5, 6, 3, 4))
[3, 6, 5, 4]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sortEven(new ArrayList<>(Arrays.asList(1, 2, 3))).equals(Arrays.asList(1, 2, 3)),
s.sortEven(new ArrayList<>(Arrays.asList(5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10))).equals(Arrays.asList(-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123)),
s.sortEven(new ArrayList<>(Arrays.asList(5, 8, -12, 4, 23, 2, 3, 11, 12, -10))).equals(Arrays.asList(-12, 8, 3, 4, 5, 2, 12, 11, 23, -10))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sorted.
>>> sortEven(Arrays.asList(1, 2, 3))
[1, 2, 3]
>>> sortEven(Arrays.asList(5, 6, 3, 4))
[3, 6, 5, 4]
*/
public List<Integer> sortEven(List<Integer> l) {
List<Integer> even = new ArrayList<>();
for (int i = 0; i < l.size(); i += 2) {
even.add(l.get(i));
}
Collections.sort(even);
List<Integer> result = l;
for (int i = 0; i < l.size(); i += 2) {
result.set(i, even.get(i / 2));
}
return result;
}
}
|
humaneval-x-java_data_Java_38
|
takes as input string encoded with encodeCyclic function. Returns decoded string.
public class Main {
static char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();
static Random rand = new Random(42);
public static String random_string(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(letters[rand.nextInt(26)]);
}
return sb.toString();
}
public static void main(String[] args) {
Solution s = new Solution();
for (int i = 0; i < 100; i++) {
String str = random_string(rand.nextInt(10) + 10);
String encode_str = s.encodeCyclic(str);
if (!s.decodeCyclic(encode_str).equals(str)) {
throw new AssertionError();
}
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
returns encoded string by cycling groups of three characters.
*/
public String encodeCyclic(String s) {
// split string to groups. Each of length 3.
List<String> groups = new ArrayList<>();
for (int i = 0; i < s.length(); i += 3) {
groups.add(s.substring(i, Math.min(i + 3, s.length())));
}
// cycle elements in each group. Unless group has fewer elements than 3.
for (int i = 0; i < groups.size(); i++) {
if (groups.get(i).length() == 3) {
groups.set(i, groups.get(i).substring(1) + groups.get(i).charAt(0));
}
}
return String.join("", groups);
}
/**
takes as input string encoded with encodeCyclic function. Returns decoded string.
*/
public String decodeCyclic(String s) {
return encodeCyclic(encodeCyclic(s));
}
}
|
humaneval-x-java_data_Java_39
|
primeFib returns n-th number that is a Fibonacci number and it's also prime.
>>> primeFib(1)
2
>>> primeFib(2)
3
>>> primeFib(3)
5
>>> primeFib(4)
13
>>> primeFib(5)
89
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.primeFib(1) == 2,
s.primeFib(2) == 3,
s.primeFib(3) == 5,
s.primeFib(4) == 13,
s.primeFib(5) == 89,
s.primeFib(6) == 233,
s.primeFib(7) == 1597,
s.primeFib(8) == 28657,
s.primeFib(9) == 514229,
s.primeFib(10) == 433494437
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
primeFib returns n-th number that is a Fibonacci number and it's also prime.
>>> primeFib(1)
2
>>> primeFib(2)
3
>>> primeFib(3)
5
>>> primeFib(4)
13
>>> primeFib(5)
89
*/
public int primeFib(int n) {
int f0 = 0, f1 = 1;
while (true) {
int p = f0 + f1;
boolean is_prime = p >= 2;
for (int k = 2; k < Math.min(Math.sqrt(p) + 1, p - 1); k++) {
if (p % k == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
n -= 1;
}
if (n == 0) {
return p;
}
f0 = f1;
f1 = p;
}
}
}
|
humaneval-x-java_data_Java_40
|
triplesSumToZero takes a list of integers as an input.
it returns True if there are three distinct elements in the list that
sum to zero, and False otherwise.
>>> triplesSumToZero(Arrays.asList(1, 3, 5, 0))
false
>>> triplesSumToZero(Arrays.asList(1, 3, -2, 1))
true
>>> triplesSumToZero(Arrays.asList(1, 2, 3, 7))
false
>>> triplesSumToZero(Arrays.asList(2, 4, -5, 3, 9, 7))
true
>>> triplesSumToZero(Arrays.asList(1))
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 3, 5, 0))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 3, 5, -1))),
s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 3, -2, 1))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 2, 3, 7))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 2, 5, 7))),
s.triplesSumToZero(new ArrayList<>(Arrays.asList(2, 4, -5, 3, 9, 7))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(1, 3, 5, -100))),
!s.triplesSumToZero(new ArrayList<>(Arrays.asList(100, 3, 5, -100)))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
triplesSumToZero takes a list of integers as an input.
it returns True if there are three distinct elements in the list that
sum to zero, and False otherwise.
>>> triplesSumToZero(Arrays.asList(1, 3, 5, 0))
false
>>> triplesSumToZero(Arrays.asList(1, 3, -2, 1))
true
>>> triplesSumToZero(Arrays.asList(1, 2, 3, 7))
false
>>> triplesSumToZero(Arrays.asList(2, 4, -5, 3, 9, 7))
true
>>> triplesSumToZero(Arrays.asList(1))
false
*/
public boolean triplesSumToZero(List<Integer> l) {
for (int i = 0; i < l.size(); i++) {
for (int j = i + 1; j < l.size(); j++) {
for (int k = j + 1; k < l.size(); k++) {
if (l.get(i) + l.get(j) + l.get(k) == 0) {
return true;
}
}
}
}
return false;
}
}
|
humaneval-x-java_data_Java_41
|
Imagine a road that's a perfectly straight infinitely long line.
n cars are driving left to right; simultaneously, a different set of n cars
are driving right to left. The two sets of cars start out being very far from
each other. All cars move in the same speed. Two cars are said to collide
when a car that's moving left to right hits a car that's moving right to left.
However, the cars are infinitely sturdy and strong; as a result, they continue moving
in their trajectory as if they did not collide.
This function outputs the number of such collisions.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.carRaceCollision(2) == 4,
s.carRaceCollision(3) == 9,
s.carRaceCollision(4) == 16,
s.carRaceCollision(8) == 64,
s.carRaceCollision(10) == 100
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Imagine a road that's a perfectly straight infinitely long line.
n cars are driving left to right; simultaneously, a different set of n cars
are driving right to left. The two sets of cars start out being very far from
each other. All cars move in the same speed. Two cars are said to collide
when a car that's moving left to right hits a car that's moving right to left.
However, the cars are infinitely sturdy and strong; as a result, they continue moving
in their trajectory as if they did not collide.
This function outputs the number of such collisions.
*/
public int carRaceCollision(int n) {
return n * n;
}
}
|
humaneval-x-java_data_Java_42
|
Return list with elements incremented by 1.
>>> incrList(Arrays.asList(1, 2, 3))
[2, 3, 4]
>>> incrList(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123))
[6, 4, 6, 3, 4, 4, 10, 1, 124]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.incrList(new ArrayList<>(Arrays.asList())).equals(List.of()),
s.incrList(new ArrayList<>(Arrays.asList(3, 2, 1))).equals(Arrays.asList(4, 3, 2)),
s.incrList(new ArrayList<>(Arrays.asList(5, 2, 5, 2, 3, 3, 9, 0, 123))).equals(Arrays.asList(6, 3, 6, 3, 4, 4, 10, 1, 124))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;
class Solution {
/**
Return list with elements incremented by 1.
>>> incrList(Arrays.asList(1, 2, 3))
[2, 3, 4]
>>> incrList(Arrays.asList(5, 3, 5, 2, 3, 3, 9, 0, 123))
[6, 4, 6, 3, 4, 4, 10, 1, 124]
*/
public List<Integer> incrList(List<Integer> l) {
return l.stream().map(p -> p + 1).collect(Collectors.toList());
}
}
|
humaneval-x-java_data_Java_43
|
pairsSumToZero takes a list of integers as an input.
it returns True if there are two distinct elements in the list that
sum to zero, and False otherwise.
>>> pairsSumToZero(Arrays.asList(1, 3, 5, 0))
false
>>> pairsSumToZero(Arrays.asList(1, 3, -2, 1))
false
>>> pairsSumToZero(Arrays.asList(1, 2, 3, 7))
false
>>> pairsSumToZero(Arrays.asList(2, 4, -5, 3, 5, 7))
true
>>> pairsSumToZero(Arrays.asList(1))
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.pairsSumToZero(new ArrayList<>(Arrays.asList(1, 3, 5, 0))),
!s.pairsSumToZero(new ArrayList<>(Arrays.asList(1, 3, -2, 1))),
!s.pairsSumToZero(new ArrayList<>(Arrays.asList(1, 2, 3, 7))),
s.pairsSumToZero(new ArrayList<>(Arrays.asList(2, 4, -5, 3, 5, 7))),
!s.pairsSumToZero(new ArrayList<>(List.of(1))),
s.pairsSumToZero(new ArrayList<>(Arrays.asList(-3, 9, -1, 3, 2, 30))),
s.pairsSumToZero(new ArrayList<>(Arrays.asList(-3, 9, -1, 3, 2, 31))),
!s.pairsSumToZero(new ArrayList<>(Arrays.asList(-3, 9, -1, 4, 2, 30))),
!s.pairsSumToZero(new ArrayList<>(Arrays.asList(-3, 9, -1, 4, 2, 31)))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
pairsSumToZero takes a list of integers as an input.
it returns True if there are two distinct elements in the list that
sum to zero, and False otherwise.
>>> pairsSumToZero(Arrays.asList(1, 3, 5, 0))
false
>>> pairsSumToZero(Arrays.asList(1, 3, -2, 1))
false
>>> pairsSumToZero(Arrays.asList(1, 2, 3, 7))
false
>>> pairsSumToZero(Arrays.asList(2, 4, -5, 3, 5, 7))
true
>>> pairsSumToZero(Arrays.asList(1))
false
*/
public boolean pairsSumToZero(List<Integer> l) {
for (int i = 0; i < l.size(); i++) {
for (int j = i + 1; j < l.size(); j++) {
if (l.get(i) + l.get(j) == 0) {
return true;
}
}
}
return false;
}
}
|
humaneval-x-java_data_Java_44
|
Change numerical base of input number x to base.
return string representation after the conversion.
base numbers are less than 10.
>>> changeBase(8, 3)
"22"
>>> changeBase(8, 2)
"1000"
>>> changeBase(7, 2)
"111"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.changeBase(8, 3), "22"),
Objects.equals(s.changeBase(9, 3), "100"),
Objects.equals(s.changeBase(234, 2), "11101010"),
Objects.equals(s.changeBase(16, 2), "10000"),
Objects.equals(s.changeBase(8, 2), "1000"),
Objects.equals(s.changeBase(7, 2), "111")
);
if (correct.contains(false)) {
throw new AssertionError();
}
for (int x = 2; x < 8; x++) {
if (!Objects.equals(s.changeBase(x, x + 1), String.valueOf(x))) {
throw new AssertionError();
}
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Change numerical base of input number x to base.
return string representation after the conversion.
base numbers are less than 10.
>>> changeBase(8, 3)
"22"
>>> changeBase(8, 2)
"1000"
>>> changeBase(7, 2)
"111"
*/
public String changeBase(int x, int base) {
StringBuilder ret = new StringBuilder();
while (x > 0) {
ret.append(String.valueOf(x % base));
x /= base;
}
return ret.reverse().toString();
}
}
|
humaneval-x-java_data_Java_45
|
Given length of a side and high return area for a triangle.
>>> triangleArea(5, 3)
7.5
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.triangleArea(5, 3) == 7.5,
s.triangleArea(2, 2) == 2.0,
s.triangleArea(10, 8) == 40.0
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given length of a side and high return area for a triangle.
>>> triangleArea(5, 3)
7.5
*/
public double triangleArea(double a, double h) {
return a * h / 2;
}
}
|
humaneval-x-java_data_Java_46
|
The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
fib4(0) -> 0
fib4(1) -> 0
fib4(2) -> 2
fib4(3) -> 0
fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
>>> fib4(5)
4
>>> fib4(6)
8
>>> fib4(7)
14
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.fib4(5) == 4,
s.fib4(8) == 28,
s.fib4(10) == 104,
s.fib4(12) == 386
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
fib4(0) -> 0
fib4(1) -> 0
fib4(2) -> 2
fib4(3) -> 0
fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
>>> fib4(5)
4
>>> fib4(6)
8
>>> fib4(7)
14
*/
public int fib4(int n) {
List<Integer> results = new ArrayList<>();
results.add(0);
results.add(0);
results.add(2);
results.add(0);
if (n < 4) {
return results.get(n);
}
for (int i = 4; i <= n; i++) {
results.add(results.get(0) + results.get(1) + results.get(2) + results.get(3));
results.remove(0);
}
return results.get(3);
}
}
|
humaneval-x-java_data_Java_47
|
Return median of elements in the list l.
>>> median(Arrays.asList(3, 1, 2, 4, 5))
3
>>> median(Arrays.asList(-10, 4, 6, 1000, 10, 20))
15.0
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.median(new ArrayList<>(Arrays.asList(3, 1, 2, 4, 5))) == 3,
s.median(new ArrayList<>(Arrays.asList(-10, 4, 6, 1000, 10, 20))) == 8.0,
s.median(new ArrayList<>(Arrays.asList(5))) == 5,
s.median(new ArrayList<>(Arrays.asList(6, 5))) == 5.5
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return median of elements in the list l.
>>> median(Arrays.asList(3, 1, 2, 4, 5))
3
>>> median(Arrays.asList(-10, 4, 6, 1000, 10, 20))
15.0
*/
public double median(List<Integer> l) {
List<Integer> list = l;
Collections.sort(list);
if (l.size() % 2 == 1) {
return l.get(l.size() / 2);
} else {
return (l.get(l.size() / 2 - 1) + l.get(l.size() / 2)) / 2.0;
}
}
}
|
humaneval-x-java_data_Java_48
|
Checks if given string is a palindrome
>>> isPalindrome("")
true
>>> isPalindrome("aba")
true
>>> isPalindrome("aaaaa")
true
>>> isPalindrome("zbcd")
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.isPalindrome(""),
s.isPalindrome("aba"),
s.isPalindrome("aaaaa"),
!s.isPalindrome("zbcd"),
s.isPalindrome("xywyx"),
!s.isPalindrome("xywyz"),
!s.isPalindrome("xywzx")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Checks if given string is a palindrome
>>> isPalindrome("")
true
>>> isPalindrome("aba")
true
>>> isPalindrome("aaaaa")
true
>>> isPalindrome("zbcd")
false
*/
public boolean isPalindrome(String text) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != text.charAt(text.length() - 1 - i)) {
return false;
}
}
return true;
}
}
|
humaneval-x-java_data_Java_49
|
Return 2^n modulo p (be aware of numerics).
>>> modp(3, 5)
3
>>> modp(1101, 101)
2
>>> modp(0, 101)
1
>>> modp(3, 11)
8
>>> modp(100, 101)
1
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.modp(3, 5) == 3,
s.modp(1101, 101) == 2,
s.modp(0, 101) == 1,
s.modp(3, 11) == 8,
s.modp(100, 101) == 1,
s.modp(30, 5) == 4,
s.modp(31, 5) == 3
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return 2^n modulo p (be aware of numerics).
>>> modp(3, 5)
3
>>> modp(1101, 101)
2
>>> modp(0, 101)
1
>>> modp(3, 11)
8
>>> modp(100, 101)
1
*/
public int modp(int n, int p) {
int ret = 1;
for (int i = 0; i < n; i++) {
ret = (ret * 2) % p;
}
return ret;
}
}
|
humaneval-x-java_data_Java_50
|
takes as input string encoded with encodeShift function. Returns decoded string.
public class Main {
static char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();
static Random rand = new Random(42);
public static String random_string(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(letters[rand.nextInt(26)]);
}
return sb.toString();
}
public static void main(String[] args) {
Solution s = new Solution();
for (int i = 0; i < 100; i++) {
String str = random_string(rand.nextInt(10) + 10);
String encode_str = s.encodeShift(str);
if (!s.decodeShift(encode_str).equals(str)) {
throw new AssertionError();
}
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
returns encoded string by shifting every character by 5 in the alphabet.
*/
public String encodeShift(String s) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
sb.append((char) ('a' + ((ch + 5 - 'a') % 26)));
}
return sb.toString();
}
/**
takes as input string encoded with encodeShift function. Returns decoded string.
*/
public String decodeShift(String s) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
sb.append((char) ('a' + ((ch + 21 - 'a') % 26)));
}
return sb.toString();
}
}
|
humaneval-x-java_data_Java_51
|
removeVowels is a function that takes string and returns string without vowels.
>>> removeVowels("")
""
>>> removeVowels("abcdef\nghijklm")
"bcdf\nghjklm"
>>> removeVowels("abcdef")
"bcdf"
>>> removeVowels("aaaaa")
""
>>> removeVowels("aaBAA")
"B"
>>> removeVowels("zbcd")
"zbcd"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.removeVowels(""), ""),
Objects.equals(s.removeVowels("abcdef\nghijklm"), "bcdf\nghjklm"),
Objects.equals(s.removeVowels("fedcba"), "fdcb"),
Objects.equals(s.removeVowels("eeeee"), ""),
Objects.equals(s.removeVowels("acBAA"), "cB"),
Objects.equals(s.removeVowels("EcBOO"), "cB"),
Objects.equals(s.removeVowels("ybcd"), "ybcd")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
removeVowels is a function that takes string and returns string without vowels.
>>> removeVowels("")
""
>>> removeVowels("abcdef\nghijklm")
"bcdf\nghjklm"
>>> removeVowels("abcdef")
"bcdf"
>>> removeVowels("aaaaa")
""
>>> removeVowels("aaBAA")
"B"
>>> removeVowels("zbcd")
"zbcd"
*/
public String removeVowels(String text) {
StringBuilder sb = new StringBuilder();
for (char ch : text.toCharArray()) {
if ("aeiou".indexOf(Character.toLowerCase(ch)) == -1) {
sb.append(ch);
}
}
return sb.toString();
}
}
|
humaneval-x-java_data_Java_52
|
Return True if all numbers in the list l are below threshold t.
>>> belowThreshold(Arrays.asList(1, 2, 4, 10), 100)
true
>>> belowThreshold(Arrays.asList(1, 20, 4, 10), 5)
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.belowThreshold(new ArrayList<>(Arrays.asList(1, 2, 4, 10)), 100),
!s.belowThreshold(new ArrayList<>(Arrays.asList(1, 20, 4, 10)), 5),
s.belowThreshold(new ArrayList<>(Arrays.asList(1, 20, 4, 10)), 21),
s.belowThreshold(new ArrayList<>(Arrays.asList(1, 20, 4, 10)), 22),
s.belowThreshold(new ArrayList<>(Arrays.asList(1, 8, 4, 10)), 11),
!s.belowThreshold(new ArrayList<>(Arrays.asList(1, 8, 4, 10)), 10)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return True if all numbers in the list l are below threshold t.
>>> belowThreshold(Arrays.asList(1, 2, 4, 10), 100)
true
>>> belowThreshold(Arrays.asList(1, 20, 4, 10), 5)
false
*/
public boolean belowThreshold(List<Integer> l, int t) {
for (int e : l) {
if (e >= t) {
return false;
}
}
return true;
}
}
|
humaneval-x-java_data_Java_53
|
Add two numbers x and y
>>> add(2, 3)
5
>>> add(5, 7)
12
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
Random rand = new Random(42);
List<Boolean> correct = Arrays.asList(
s.add(0, 1) == 1,
s.add(1, 0) == 1,
s.add(2, 3) == 5,
s.add(5, 7) == 12,
s.add(7, 5) == 12
);
if (correct.contains(false)) {
throw new AssertionError();
}
for (int i = 0; i < 100; i++) {
int x = rand.nextInt(1000), y = rand.nextInt(1000);
if (s.add(x, y) != x + y) {
throw new AssertionError();
}
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Add two numbers x and y
>>> add(2, 3)
5
>>> add(5, 7)
12
*/
public int add(int x, int y) {
return x + y;
}
}
|
humaneval-x-java_data_Java_54
|
Check if two words have the same characters.
>>> sameChars("eabcdzzzz", "dddzzzzzzzddeddabc")
true
>>> sameChars("abcd", "dddddddabc")
true
>>> sameChars("dddddddabc", "abcd")
true
>>> sameChars("eabcd", "dddddddabc")
false
>>> sameChars("abcd", "dddddddabce")
false
>>> sameChars("eabcdzzzz", "dddzzzzzzzddddabc")
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sameChars("eabcdzzzz", "dddzzzzzzzddeddabc"),
s.sameChars("abcd", "dddddddabc"),
s.sameChars("dddddddabc", "abcd"),
!s.sameChars("eabcd", "dddddddabc"),
!s.sameChars("abcd", "dddddddabcf"),
!s.sameChars("eabcdzzzz", "dddzzzzzzzddddabc"),
!s.sameChars("aabb", "aaccc")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Check if two words have the same characters.
>>> sameChars("eabcdzzzz", "dddzzzzzzzddeddabc")
true
>>> sameChars("abcd", "dddddddabc")
true
>>> sameChars("dddddddabc", "abcd")
true
>>> sameChars("eabcd", "dddddddabc")
false
>>> sameChars("abcd", "dddddddabce")
false
>>> sameChars("eabcdzzzz", "dddzzzzzzzddddabc")
false
*/
public boolean sameChars(String s0, String s1) {
Set<Character> set0 = new HashSet<>();
for (char c : s0.toCharArray()) {
set0.add(c);
}
Set<Character> set1 = new HashSet<>();
for (char c : s1.toCharArray()) {
set1.add(c);
}
return set0.equals(set1);
}
}
|
humaneval-x-java_data_Java_55
|
Return n-th Fibonacci number.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.fib(10) == 55,
s.fib(1) == 1,
s.fib(8) == 21,
s.fib(11) == 89,
s.fib(12) == 144
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return n-th Fibonacci number.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
*/
public int fib(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
}
|
humaneval-x-java_data_Java_56
|
brackets is a string of "<" and ">".
return True if every opening bracket has a corresponding closing bracket.
>>> correctBracketing("<")
false
>>> correctBracketing("<>")
true
>>> correctBracketing("<<><>>")
true
>>> correctBracketing("><<>")
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.correctBracketing("<>"),
s.correctBracketing("<<><>>"),
s.correctBracketing("<><><<><>><>"),
s.correctBracketing("<><><<<><><>><>><<><><<>>>"),
!s.correctBracketing("<<<><>>>>"),
!s.correctBracketing("><<>"),
!s.correctBracketing("<"),
!s.correctBracketing("<<<<"),
!s.correctBracketing(">"),
!s.correctBracketing("<<>"),
!s.correctBracketing("<><><<><>><>><<>"),
!s.correctBracketing("<><><<><>><>>><>")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
brackets is a string of "<" and ">".
return True if every opening bracket has a corresponding closing bracket.
>>> correctBracketing("<")
false
>>> correctBracketing("<>")
true
>>> correctBracketing("<<><>>")
true
>>> correctBracketing("><<>")
false
*/
public boolean correctBracketing(String brackets) {
int depth = 0;
for (char b : brackets.toCharArray()) {
if (b == '<') {
depth += 1;
} else {
depth -= 1;
}
if (depth < 0) {
return false;
}
}
return depth == 0;
}
}
|
humaneval-x-java_data_Java_57
|
Return True is list elements are monotonically increasing or decreasing.
>>> monotonic(Arrays.asList(1, 2, 4, 20))
true
>>> monotonic(Arrays.asList(1, 20, 4, 10))
false
>>> monotonic(Arrays.asList(4, 1, 0, -10))
true
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.monotonic(new ArrayList<>(Arrays.asList(1, 2, 4, 10))),
s.monotonic(new ArrayList<>(Arrays.asList(1, 2, 4, 20))),
!s.monotonic(new ArrayList<>(Arrays.asList(1, 20, 4, 10))),
s.monotonic(new ArrayList<>(Arrays.asList(4, 1, 0, -10))),
s.monotonic(new ArrayList<>(Arrays.asList(4, 1, 1, 0))),
!s.monotonic(new ArrayList<>(Arrays.asList(1, 2, 3, 2, 5, 60))),
s.monotonic(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 60))),
s.monotonic(new ArrayList<>(Arrays.asList(9, 9, 9, 9)))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return True is list elements are monotonically increasing or decreasing.
>>> monotonic(Arrays.asList(1, 2, 4, 20))
true
>>> monotonic(Arrays.asList(1, 20, 4, 10))
false
>>> monotonic(Arrays.asList(4, 1, 0, -10))
true
*/
public boolean monotonic(List<Integer> l) {
List<Integer> l1 = new ArrayList<>(l), l2 = new ArrayList<>(l);
Collections.sort(l1);
l2.sort(Collections.reverseOrder());
return l.equals(l1) || l.equals(l2);
}
}
|
humaneval-x-java_data_Java_58
|
Return sorted unique common elements for two lists.
>>> common(Arrays.asList(1, 4, 3, 34, 653, 2, 5), Arrays.asList(5, 7, 1, 5, 9, 653, 121))
[1, 5, 653]
>>> common(Arrays.asList(5, 3, 2, 8), Arrays.asList(3, 2))
[2, 3]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.common(new ArrayList<>(Arrays.asList(1, 4, 3, 34, 653, 2, 5)), new ArrayList<>(Arrays.asList(5, 7, 1, 5, 9, 653, 121))).equals(Arrays.asList(1, 5, 653)),
s.common(new ArrayList<>(Arrays.asList(5, 3, 2, 8)), new ArrayList<>(Arrays.asList(3, 2))).equals(Arrays.asList(2, 3)),
s.common(new ArrayList<>(Arrays.asList(4, 3, 2, 8)), new ArrayList<>(Arrays.asList(3, 2, 4))).equals(Arrays.asList(2, 3, 4)),
s.common(new ArrayList<>(Arrays.asList(4, 3, 2, 8)), new ArrayList<>(List.of())).equals(List.of())
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return sorted unique common elements for two lists.
>>> common(Arrays.asList(1, 4, 3, 34, 653, 2, 5), Arrays.asList(5, 7, 1, 5, 9, 653, 121))
[1, 5, 653]
>>> common(Arrays.asList(5, 3, 2, 8), Arrays.asList(3, 2))
[2, 3]
*/
public List<Integer> common(List<Integer> l1, List<Integer> l2) {
Set<Integer> ret = new HashSet<>(l1);
ret.retainAll(new HashSet<>(l2));
List<Integer> result = new ArrayList<>(ret);
Collections.sort(result);
return result;
}
}
|
humaneval-x-java_data_Java_59
|
Return the largest prime factor of n. Assume n > 1 and is not a prime.
>>> largestPrimeFactor(13195)
29
>>> largestPrimeFactor(2048)
2
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.largestPrimeFactor(15) == 5,
s.largestPrimeFactor(27) == 3,
s.largestPrimeFactor(63) == 7,
s.largestPrimeFactor(330) == 11,
s.largestPrimeFactor(13195) == 29
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Return the largest prime factor of n. Assume n > 1 and is not a prime.
>>> largestPrimeFactor(13195)
29
>>> largestPrimeFactor(2048)
2
*/
public int largestPrimeFactor(int n) {
int largest = 1;
for (int j = 2; j <= n; j++) {
if (n % j == 0) {
boolean is_prime = j >= 2;
for (int i = 2; i < j - 1; i++) {
if (j % i == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
largest = Math.max(largest, j);
}
}
}
return largest;
}
}
|
humaneval-x-java_data_Java_60
|
sumToN is a function that sums numbers from 1 to n.
>>> sumToN(30)
465
>>> sumToN(100)
5050
>>> sumToN(5)
15
>>> sumToN(10)
55
>>> sumToN(1)
1
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sumToN(1) == 1,
s.sumToN(6) == 21,
s.sumToN(11) == 66,
s.sumToN(30) == 465,
s.sumToN(100) == 5050
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
sumToN is a function that sums numbers from 1 to n.
>>> sumToN(30)
465
>>> sumToN(100)
5050
>>> sumToN(5)
15
>>> sumToN(10)
55
>>> sumToN(1)
1
*/
public int sumToN(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
result += i;
}
return result;
}
}
|
humaneval-x-java_data_Java_61
|
brackets is a string of "(" and ")".
return True if every opening bracket has a corresponding closing bracket.
>>> correctBracketing("(")
false
>>> correctBracketing("()")
true
>>> correctBracketing("(()())")
true
>>> correctBracketing(")(()")
false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.correctBracketing("()"),
s.correctBracketing("(()())"),
s.correctBracketing("()()(()())()"),
s.correctBracketing("()()((()()())())(()()(()))"),
!s.correctBracketing("((()())))"),
!s.correctBracketing(")(()"),
!s.correctBracketing("("),
!s.correctBracketing("(((("),
!s.correctBracketing(")"),
!s.correctBracketing("(()"),
!s.correctBracketing("()()(()())())(()"),
!s.correctBracketing("()()(()())()))()")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
brackets is a string of "(" and ")".
return True if every opening bracket has a corresponding closing bracket.
>>> correctBracketing("(")
false
>>> correctBracketing("()")
true
>>> correctBracketing("(()())")
true
>>> correctBracketing(")(()")
false
*/
public boolean correctBracketing(String brackets) {
int depth = 0;
for (char b : brackets.toCharArray()) {
if (b == '(') {
depth += 1;
} else {
depth -= 1;
}
if (depth < 0) {
return false;
}
}
return depth == 0;
}
}
|
humaneval-x-java_data_Java_62
|
xs represent coefficients of a polynomial.
xs[0] + xs[1] * x + xs[2] * x^2 + ....
Return derivative of this polynomial in the same form.
>>> derivative(Arrays.asList(3, 1, 2, 4, 5))
[1, 4, 12, 20]
>>> derivative(Arrays.asList(1, 2, 3]))
[2, 6]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.derivative(new ArrayList<>(Arrays.asList(3, 1, 2, 4, 5))).equals(Arrays.asList(1, 4, 12, 20)),
s.derivative(new ArrayList<>(Arrays.asList(1, 2, 3))).equals(Arrays.asList(2, 6)),
s.derivative(new ArrayList<>(Arrays.asList(3, 2, 1))).equals(Arrays.asList(2, 2)),
s.derivative(new ArrayList<>(Arrays.asList(3, 2, 1, 0, 4))).equals(Arrays.asList(2, 2, 0, 16)),
s.derivative(List.of(1)).equals(List.of())
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
xs represent coefficients of a polynomial.
xs[0] + xs[1] * x + xs[2] * x^2 + ....
Return derivative of this polynomial in the same form.
>>> derivative(Arrays.asList(3, 1, 2, 4, 5))
[1, 4, 12, 20]
>>> derivative(Arrays.asList(1, 2, 3]))
[2, 6]
*/
public List<Integer> derivative(List<Integer> xs) {
List<Integer> result = new ArrayList<>();
for (int i = 1; i < xs.size(); i++) {
result.add(i * xs.get(i));
}
return result;
}
}
|
humaneval-x-java_data_Java_63
|
The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
fibfib(0) == 0
fibfib(1) == 0
fibfib(2) == 1
fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
Please write a function to efficiently compute the n-th element of the fibfib number sequence.
>>> fibfib(1)
0
>>> fibfib(5)
4
>>> fibfib(8)
24
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.fibfib(2) == 1,
s.fibfib(1) == 0,
s.fibfib(5) == 4,
s.fibfib(8) == 24,
s.fibfib(10) == 81,
s.fibfib(12) == 274,
s.fibfib(14) == 927
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
fibfib(0) == 0
fibfib(1) == 0
fibfib(2) == 1
fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
Please write a function to efficiently compute the n-th element of the fibfib number sequence.
>>> fibfib(1)
0
>>> fibfib(5)
4
>>> fibfib(8)
24
*/
public int fibfib(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 0;
}
if (n == 2) {
return 1;
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3);
}
}
|
humaneval-x-java_data_Java_64
|
Write a function vowelsCount which takes a string representing
a word as input and returns the number of vowels in the string.
Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
vowel, but only when it is at the end of the given word.
Example:
>>> vowelsCount("abcde")
2
>>> vowelsCount("ACEDY")
3
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.vowelsCount("abcde") == 2,
s.vowelsCount("Alone") == 3,
s.vowelsCount("key") == 2,
s.vowelsCount("bye") == 1,
s.vowelsCount("keY") == 2,
s.vowelsCount("bYe") == 1,
s.vowelsCount("ACEDY") == 3
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function vowelsCount which takes a string representing
a word as input and returns the number of vowels in the string.
Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
vowel, but only when it is at the end of the given word.
Example:
>>> vowelsCount("abcde")
2
>>> vowelsCount("ACEDY")
3
*/
public int vowelsCount(String s) {
String vowels = "aeiouAEIOU";
int n_vowels = 0;
for (char c : s.toCharArray()) {
if (vowels.indexOf(c) != -1) {
n_vowels += 1;
}
}
if (s.charAt(s.length() - 1) == 'y' || s.charAt(s.length() - 1) == 'Y') {
n_vowels += 1;
}
return n_vowels;
}
}
|
humaneval-x-java_data_Java_65
|
Circular shift the digits of the integer x, shift the digits right by shift
and return the result as a string.
If shift > number of digits, return digits reversed.
>>> circularShift(12, 1)
"21"
>>> circularShift(12, 2)
"12"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.circularShift(100, 2).equals("001"),
s.circularShift(12, 2).equals("12"),
s.circularShift(97, 8).equals("79"),
s.circularShift(12, 1).equals("21"),
s.circularShift(11, 101).equals("11")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Circular shift the digits of the integer x, shift the digits right by shift
and return the result as a string.
If shift > number of digits, return digits reversed.
>>> circularShift(12, 1)
"21"
>>> circularShift(12, 2)
"12"
*/
public String circularShift(int x, int shift) {
String s = String.valueOf(x);
if (shift > s.length()) {
return new StringBuilder(s).reverse().toString();
} else {
return s.substring(s.length() - shift) + s.substring(0, s.length() - shift);
}
}
}
|
humaneval-x-java_data_Java_66
|
Write a function that takes a string as input and returns the sum of the upper characters only'
ASCII codes.
Examples:
digitSum("") => 0
digitSum("abAB") => 131
digitSum("abcCd") => 67
digitSum("helloE") => 69
digitSum("woArBld") => 131
digitSum("aAaaaXa") => 153
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.digitSum("") == 0,
s.digitSum("abAB") == 131,
s.digitSum("abcCd") == 67,
s.digitSum("helloE") == 69,
s.digitSum("woArBld") == 131,
s.digitSum("aAaaaXa") == 153,
s.digitSum(" How are yOu?") == 151,
s.digitSum("You arE Very Smart") == 327
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that takes a string as input and returns the sum of the upper characters only'
ASCII codes.
Examples:
digitSum("") => 0
digitSum("abAB") => 131
digitSum("abcCd") => 67
digitSum("helloE") => 69
digitSum("woArBld") => 131
digitSum("aAaaaXa") => 153
*/
public int digitSum(String s) {
int sum = 0;
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) {
sum += c;
}
}
return sum;
}
}
|
humaneval-x-java_data_Java_67
|
In this task, you will be given a string that represents a number of apples and oranges
that are distributed in a basket of fruit this basket contains
apples, oranges, and mango fruits. Given the string that represents the total number of
the oranges and apples and an integer that represent the total number of the fruits
in the basket return the number of the mango fruits in the basket.
for examble:
fruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8
fruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2
fruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95
fruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.fruitDistribution("5 apples and 6 oranges",19) == 8,
s.fruitDistribution("5 apples and 6 oranges",21) == 10,
s.fruitDistribution("0 apples and 1 oranges",3) == 2,
s.fruitDistribution("1 apples and 0 oranges",3) == 2,
s.fruitDistribution("2 apples and 3 oranges",100) == 95,
s.fruitDistribution("2 apples and 3 oranges",5) == 0,
s.fruitDistribution("1 apples and 100 oranges",120) == 19
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
In this task, you will be given a string that represents a number of apples and oranges
that are distributed in a basket of fruit this basket contains
apples, oranges, and mango fruits. Given the string that represents the total number of
the oranges and apples and an integer that represent the total number of the fruits
in the basket return the number of the mango fruits in the basket.
for examble:
fruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8
fruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2
fruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95
fruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19
*/
public int fruitDistribution(String s, int n) {
List<Integer> lis = new ArrayList<>();
for (String i : s.split(" ")) {
try {
lis.add(Integer.parseInt(i));
} catch (NumberFormatException ignored) {
}
}
return n - lis.stream().mapToInt(Integer::intValue).sum();
}
}
|
humaneval-x-java_data_Java_68
|
"Given an array representing a branch of a tree that has non-negative integer nodes
your task is to pluck one of the nodes and return it.
The plucked node should be the node with the smallest even value.
If multiple nodes with the same smallest even value are found return the node that has smallest index.
The plucked node should be returned in a list, [ smalest_value, its index ],
If there are no even values or the given array is empty, return [].
Example 1:
Input: [4,2,3]
Output: [2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 2:
Input: [1,2,3]
Output: [2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 3:
Input: []
Output: []
Example 4:
Input: [5, 0, 3, 0, 4, 2]
Output: [0, 1]
Explanation: 0 is the smallest value, but there are two zeros,
so we will choose the first zero, which has the smallest index.
Constraints:
* 1 <= nodes.length <= 10000
* 0 <= node.value
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.pluck(new ArrayList<>(Arrays.asList(4, 2, 3))).equals(Arrays.asList(2, 1)),
s.pluck(new ArrayList<>(Arrays.asList(1, 2, 3))).equals(Arrays.asList(2, 1)),
s.pluck(new ArrayList<>(List.of())).equals(List.of()),
s.pluck(new ArrayList<>(Arrays.asList(5, 0, 3, 0, 4, 2))).equals(Arrays.asList(0, 1)),
s.pluck(new ArrayList<>(Arrays.asList(1, 2, 3, 0, 5, 3))).equals(Arrays.asList(0, 3)),
s.pluck(new ArrayList<>(Arrays.asList(5, 4, 8, 4, 8))).equals(Arrays.asList(4, 1)),
s.pluck(new ArrayList<>(Arrays.asList(7, 6, 7, 1))).equals(Arrays.asList(6, 1)),
s.pluck(new ArrayList<>(Arrays.asList(7, 9, 7, 1))).equals(List.of())
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
"Given an array representing a branch of a tree that has non-negative integer nodes
your task is to pluck one of the nodes and return it.
The plucked node should be the node with the smallest even value.
If multiple nodes with the same smallest even value are found return the node that has smallest index.
The plucked node should be returned in a list, [ smalest_value, its index ],
If there are no even values or the given array is empty, return [].
Example 1:
Input: [4,2,3]
Output: [2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 2:
Input: [1,2,3]
Output: [2, 1]
Explanation: 2 has the smallest even value, and 2 has the smallest index.
Example 3:
Input: []
Output: []
Example 4:
Input: [5, 0, 3, 0, 4, 2]
Output: [0, 1]
Explanation: 0 is the smallest value, but there are two zeros,
so we will choose the first zero, which has the smallest index.
Constraints:
* 1 <= nodes.length <= 10000
* 0 <= node.value
*/
public List<Integer> pluck(List<Integer> arr) {
List<Integer> result = new ArrayList<>();
if (arr.size() == 0) {
return result;
}
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) % 2 == 0) {
if (arr.get(i) < min) {
min = arr.get(i);
minIndex = i;
}
}
}
if (minIndex != -1) {
result.add(min);
result.add(minIndex);
}
return result;
}
}
|
humaneval-x-java_data_Java_69
|
You are given a non-empty list of positive integers. Return the greatest integer that is greater than
zero, and has a frequency greater than or equal to the value of the integer itself.
The frequency of an integer is the number of times it appears in the list.
If no such a value exist, return -1.
Examples:
search(Arrays.asList(4, 1, 2, 2, 3, 1)) == 2
search(Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4)) == 3
search(Arrays.asList(5, 5, 4, 4, 4)) == -1
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.search(new ArrayList<>(Arrays.asList(5, 5, 5, 5, 1))) == 1,
s.search(new ArrayList<>(Arrays.asList(4, 1, 4, 1, 4, 4))) == 4,
s.search(new ArrayList<>(Arrays.asList(3, 3))) == -1,
s.search(new ArrayList<>(Arrays.asList(8, 8, 8, 8, 8, 8, 8, 8))) == 8,
s.search(new ArrayList<>(Arrays.asList(2, 3, 3, 2, 2))) == 2,
s.search(new ArrayList<>(Arrays.asList(2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1))) == 1,
s.search(new ArrayList<>(Arrays.asList(3, 2, 8, 2))) == 2,
s.search(new ArrayList<>(Arrays.asList(6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10))) == 1,
s.search(new ArrayList<>(Arrays.asList(8, 8, 3, 6, 5, 6, 4))) == -1,
s.search(new ArrayList<>(Arrays.asList(6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9))) == 1,
s.search(new ArrayList<>(Arrays.asList(1, 9, 10, 1, 3))) == 1,
s.search(new ArrayList<>(Arrays.asList(6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10))) == 5,
s.search(new ArrayList<>(List.of(1))) == 1,
s.search(new ArrayList<>(Arrays.asList(8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5))) == 4,
s.search(new ArrayList<>(Arrays.asList(2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10))) == 2,
s.search(new ArrayList<>(Arrays.asList(1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3))) == 1,
s.search(new ArrayList<>(Arrays.asList(9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4))) == 4,
s.search(new ArrayList<>(Arrays.asList(2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7))) == 4,
s.search(new ArrayList<>(Arrays.asList(9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1))) == 2,
s.search(new ArrayList<>(Arrays.asList(5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8))) == -1,
s.search(new ArrayList<>(List.of(10))) == -1,
s.search(new ArrayList<>(Arrays.asList(9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2))) == 2,
s.search(new ArrayList<>(Arrays.asList(5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8))) == 1,
s.search(new ArrayList<>(Arrays.asList(7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6))) == 1,
s.search(new ArrayList<>(Arrays.asList(3, 10, 10, 9, 2))) == -1
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You are given a non-empty list of positive integers. Return the greatest integer that is greater than
zero, and has a frequency greater than or equal to the value of the integer itself.
The frequency of an integer is the number of times it appears in the list.
If no such a value exist, return -1.
Examples:
search(Arrays.asList(4, 1, 2, 2, 3, 1)) == 2
search(Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4)) == 3
search(Arrays.asList(5, 5, 4, 4, 4)) == -1
*/
public int search(List<Integer> lst) {
int[] frq = new int[Collections.max(lst) + 1];
for (int i : lst) {
frq[i] += 1;
}
int ans = -1;
for (int i = 1; i < frq.length; i++) {
if (frq[i] >= i) {
ans = i;
}
}
return ans;
}
}
|
humaneval-x-java_data_Java_70
|
Given list of integers, return list in strange order.
Strange sorting, is when you start with the minimum value,
then maximum of the remaining integers, then minimum and so on.
Examples:
strangeSortList(Arrays.asList(1, 2, 3, 4)) == Arrays.asList(1, 4, 2, 3)
strangeSortList(Arrays.asList(5, 5, 5, 5)) == Arrays.asList(5, 5, 5, 5)
strangeSortList(Arrays.asList()) == Arrays.asList()
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.strangeSortList(new ArrayList<>(Arrays.asList(1, 2, 3, 4))).equals(Arrays.asList(1, 4, 2, 3)),
s.strangeSortList(new ArrayList<>(Arrays.asList(5, 6, 7, 8, 9))).equals(Arrays.asList(5, 9, 6, 8, 7)),
s.strangeSortList(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))).equals(Arrays.asList(1, 5, 2, 4, 3)),
s.strangeSortList(new ArrayList<>(Arrays.asList(5, 6, 7, 8, 9, 1))).equals(Arrays.asList(1, 9, 5, 8, 6, 7)),
s.strangeSortList(new ArrayList<>(Arrays.asList(5, 5, 5, 5))).equals(Arrays.asList(5, 5, 5, 5)),
s.strangeSortList(new ArrayList<>(List.of())).equals(List.of()),
s.strangeSortList(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8))).equals(Arrays.asList(1, 8, 2, 7, 3, 6, 4, 5)),
s.strangeSortList(new ArrayList<>(Arrays.asList(0, 2, 2, 2, 5, 5, -5, -5))).equals(Arrays.asList(-5, 5, -5, 5, 0, 2, 2, 2)),
s.strangeSortList(new ArrayList<>(List.of(111111))).equals(List.of(111111))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given list of integers, return list in strange order.
Strange sorting, is when you start with the minimum value,
then maximum of the remaining integers, then minimum and so on.
Examples:
strangeSortList(Arrays.asList(1, 2, 3, 4)) == Arrays.asList(1, 4, 2, 3)
strangeSortList(Arrays.asList(5, 5, 5, 5)) == Arrays.asList(5, 5, 5, 5)
strangeSortList(Arrays.asList()) == Arrays.asList()
*/
public List<Integer> strangeSortList(List<Integer> lst) {
List<Integer> res = new ArrayList<>();
boolean _switch = true;
List<Integer> l = new ArrayList<>(lst);
while (l.size() != 0) {
if (_switch) {
res.add(Collections.min(l));
} else {
res.add(Collections.max(l));
}
l.remove(res.get(res.size() - 1));
_switch = !_switch;
}
return res;
}
}
|
humaneval-x-java_data_Java_71
|
Given the lengths of the three sides of a triangle. Return the area of
the triangle rounded to 2 decimal points if the three sides form a valid triangle.
Otherwise return -1
Three sides make a valid triangle when the sum of any two sides is greater
than the third side.
Example:
triangleArea(3, 4, 5) == 6.00
triangleArea(1, 2, 10) == -1
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.triangleArea(3, 4, 5) == 6.00,
s.triangleArea(1, 2, 10) == -1,
s.triangleArea(4, 8, 5) == 8.18,
s.triangleArea(2, 2, 2) == 1.73,
s.triangleArea(1, 2, 3) == -1,
s.triangleArea(10, 5, 7) == 16.25,
s.triangleArea(2, 6, 3) == -1,
s.triangleArea(1, 1, 1) == 0.43,
s.triangleArea(2, 2, 10) == -1
);
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 the area of
the triangle rounded to 2 decimal points if the three sides form a valid triangle.
Otherwise return -1
Three sides make a valid triangle when the sum of any two sides is greater
than the third side.
Example:
triangleArea(3, 4, 5) == 6.00
triangleArea(1, 2, 10) == -1
*/
public double triangleArea(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
return -1;
}
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
area = (double) Math.round(area * 100) / 100;
return area;
}
}
|
humaneval-x-java_data_Java_72
|
Write a function that returns True if the object q will fly, and False otherwise.
The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
Example:
willItFly(Arrays.asList(1, 2), 5) -> false
# 1+2 is less than the maximum possible weight, but it's unbalanced.
willItFly(Arrays.asList(3, 2, 3), 1) -> false
# it's balanced, but 3+2+3 is more than the maximum possible weight.
willItFly(Arrays.asList(3, 2, 3), 9) -> true
# 3+2+3 is less than the maximum possible weight, and it's balanced.
willItFly(Arrays.asList(3), 5) -> true
# 3 is less than the maximum possible weight, and it's balanced.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.willItFly(new ArrayList<>(Arrays.asList(3, 2, 3)), 9),
!s.willItFly(new ArrayList<>(Arrays.asList(1, 2)), 5),
s.willItFly(new ArrayList<>(List.of(3)), 5),
!s.willItFly(new ArrayList<>(Arrays.asList(3, 2, 3)), 1),
!s.willItFly(new ArrayList<>(Arrays.asList(1, 2, 3)), 6),
s.willItFly(new ArrayList<>(List.of(5)), 5)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that returns True if the object q will fly, and False otherwise.
The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
Example:
willItFly(Arrays.asList(1, 2), 5) -> false
# 1+2 is less than the maximum possible weight, but it's unbalanced.
willItFly(Arrays.asList(3, 2, 3), 1) -> false
# it's balanced, but 3+2+3 is more than the maximum possible weight.
willItFly(Arrays.asList(3, 2, 3), 9) -> true
# 3+2+3 is less than the maximum possible weight, and it's balanced.
willItFly(Arrays.asList(3), 5) -> true
# 3 is less than the maximum possible weight, and it's balanced.
*/
public boolean willItFly(List<Integer> q, int w) {
if (q.stream().reduce(0, Integer::sum) > w) {
return false;
}
int i = 0, j = q.size() - 1;
while (i < j) {
if (!Objects.equals(q.get(i), q.get(j))) {
return false;
}
i += 1;
j -= 1;
}
return true;
}
}
|
humaneval-x-java_data_Java_73
|
Given an array arr of integers, find the minimum number of elements that
need to be changed to make the array palindromic. A palindromic array is an array that
is read the same backwards and forwards. In one change, you can change one element to any other element.
For example:
smallestChange(Arrays.asList(1,2,3,5,4,7,9,6)) == 4
smallestChange(Arrays.asList(1, 2, 3, 4, 3, 2, 2)) == 1
smallestChange(Arrays.asList(1, 2, 3, 2, 1)) == 0
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.smallestChange(new ArrayList<>(Arrays.asList(1, 2, 3, 5, 4, 7, 9, 6))) == 4,
s.smallestChange(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 3, 2, 2))) == 1,
s.smallestChange(new ArrayList<>(Arrays.asList(1, 4, 2))) == 1,
s.smallestChange(new ArrayList<>(Arrays.asList(1, 4, 4, 2))) == 1,
s.smallestChange(new ArrayList<>(Arrays.asList(1, 2, 3, 2, 1))) == 0,
s.smallestChange(new ArrayList<>(Arrays.asList(3, 1, 1, 3))) == 0,
s.smallestChange(new ArrayList<>(List.of(1))) == 0,
s.smallestChange(new ArrayList<>(Arrays.asList(0, 1))) == 1
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given an array arr of integers, find the minimum number of elements that
need to be changed to make the array palindromic. A palindromic array is an array that
is read the same backwards and forwards. In one change, you can change one element to any other element.
For example:
smallestChange(Arrays.asList(1,2,3,5,4,7,9,6)) == 4
smallestChange(Arrays.asList(1, 2, 3, 4, 3, 2, 2)) == 1
smallestChange(Arrays.asList(1, 2, 3, 2, 1)) == 0
*/
public int smallestChange(List<Integer> arr) {
int ans = 0;
for (int i = 0; i < arr.size() / 2; i++) {
if (!Objects.equals(arr.get(i), arr.get(arr.size() - i - 1))) {
ans += 1;
}
}
return ans;
}
}
|
humaneval-x-java_data_Java_74
|
Write a function that accepts two lists of strings and returns the list that has
total number of chars in the all strings of the list less than the other list.
if the two lists have the same number of chars, return the first list.
Examples
totalMatch(Arrays.asList(), Arrays.asList()) -> []
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "Hi")) -> ["hI", "Hi"]
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hi", "hi", "admin", "project")) -> ["hi", "admin"]
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "hi", "hi")) -> ["hI", "hi", "hi"]
totalMatch(Arrays.asList("4"), Arrays.asList("1", "2", "3", "4", "5")) -> ["4"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.totalMatch(new ArrayList<>(List.of()), new ArrayList<>(List.of())).equals(List.of()),
s.totalMatch(new ArrayList<>(Arrays.asList("hi", "admin")), new ArrayList<>(Arrays.asList("hi", "hi"))).equals(Arrays.asList("hi", "hi")),
s.totalMatch(new ArrayList<>(Arrays.asList("hi", "admin")), new ArrayList<>(Arrays.asList("hi", "hi", "admin", "project"))).equals(Arrays.asList("hi", "admin")),
s.totalMatch(new ArrayList<>(List.of("4")), new ArrayList<>(Arrays.asList("1", "2", "3", "4", "5"))).equals(List.of("4")),
s.totalMatch(new ArrayList<>(Arrays.asList("hi", "admin")), new ArrayList<>(Arrays.asList("hI", "Hi"))).equals(Arrays.asList("hI", "Hi")),
s.totalMatch(new ArrayList<>(Arrays.asList("hi", "admin")), new ArrayList<>(Arrays.asList("hI", "hi", "hi"))).equals(Arrays.asList("hI", "hi", "hi")),
s.totalMatch(new ArrayList<>(Arrays.asList("hi", "admin")), new ArrayList<>(Arrays.asList("hI", "hi", "hii"))).equals(Arrays.asList("hi", "admin")),
s.totalMatch(new ArrayList<>(List.of()), new ArrayList<>(List.of("this"))).equals(List.of()),
s.totalMatch(new ArrayList<>(List.of("this")), new ArrayList<>(List.of())).equals(List.of())
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that accepts two lists of strings and returns the list that has
total number of chars in the all strings of the list less than the other list.
if the two lists have the same number of chars, return the first list.
Examples
totalMatch(Arrays.asList(), Arrays.asList()) -> []
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "Hi")) -> ["hI", "Hi"]
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hi", "hi", "admin", "project")) -> ["hi", "admin"]
totalMatch(Arrays.asList("hi", "admin"), Arrays.asList("hI", "hi", "hi")) -> ["hI", "hi", "hi"]
totalMatch(Arrays.asList("4"), Arrays.asList("1", "2", "3", "4", "5")) -> ["4"]
*/
public List<String> totalMatch(List<String> lst1, List<String> lst2) {
int l1 = 0;
for (String st : lst1) {
l1 += st.length();
}
int l2 = 0;
for (String st : lst2) {
l2 += st.length();
}
if (l1 <= l2) {
return lst1;
} else {
return lst2;
}
}
}
|
humaneval-x-java_data_Java_75
|
Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
isMultiplyPrime(30) == true
30 = 2 * 3 * 5
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.isMultiplyPrime(5),
s.isMultiplyPrime(30),
s.isMultiplyPrime(8),
!s.isMultiplyPrime(10),
s.isMultiplyPrime(125),
s.isMultiplyPrime(3 * 5 * 7),
!s.isMultiplyPrime(3 * 6 * 7),
!s.isMultiplyPrime(9 * 9 * 9),
!s.isMultiplyPrime(11 * 9 * 9),
s.isMultiplyPrime(11 * 13 * 7)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
isMultiplyPrime(30) == true
30 = 2 * 3 * 5
*/
public boolean isMultiplyPrime(int a) {
class IsPrime {
public static boolean is_prime(int n) {
for (int j = 2; j < n; j++) {
if (n % j == 0) {
return false;
}
}
return true;
}
}
for (int i = 2; i < 101; i++) {
if (!IsPrime.is_prime(i)) {
continue;
}
for (int j = i; j < 101; j++) {
if (!IsPrime.is_prime(j)) {
continue;
}
for (int k = j; k < 101; k++) {
if (!IsPrime.is_prime(k)) {
continue;
}
if (i * j * k == a) {
return true;
}
}
}
}
return false;
}
}
|
humaneval-x-java_data_Java_76
|
Your task is to write a function that returns true if a number x is a simple
power of n and false in other cases.
x is a simple power of n if n**int=x
For example:
isSimplePower(1, 4) => true
isSimplePower(2, 2) => true
isSimplePower(8, 2) => true
isSimplePower(3, 2) => false
isSimplePower(3, 1) => false
isSimplePower(5, 3) => false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.isSimplePower(1, 4),
s.isSimplePower(2, 2),
s.isSimplePower(8, 2),
!s.isSimplePower(3, 2),
!s.isSimplePower(3, 1),
!s.isSimplePower(5, 3),
s.isSimplePower(16, 2),
!s.isSimplePower(143214, 16),
s.isSimplePower(4, 2),
s.isSimplePower(9, 3),
s.isSimplePower(16, 4),
!s.isSimplePower(24, 2),
!s.isSimplePower(128, 4),
!s.isSimplePower(12, 6),
s.isSimplePower(1, 1),
s.isSimplePower(1, 12)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Your task is to write a function that returns true if a number x is a simple
power of n and false in other cases.
x is a simple power of n if n**int=x
For example:
isSimplePower(1, 4) => true
isSimplePower(2, 2) => true
isSimplePower(8, 2) => true
isSimplePower(3, 2) => false
isSimplePower(3, 1) => false
isSimplePower(5, 3) => false
*/
public boolean isSimplePower(int x, int n) {
if (n == 1) {
return x == 1;
}
int power = 1;
while (power < x) {
power = power * n;
}
return power == x;
}
}
|
humaneval-x-java_data_Java_77
|
Write a function that takes an integer a and returns true
if this ingeger is a cube of some integer number.
Note: you may assume the input is always valid.
Examples:
iscube(1) ==> true
iscube(2) ==> false
iscube(-1) ==> true
iscube(64) ==> true
iscube(0) ==> true
iscube(180) ==> false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.iscube(1),
!s.iscube(2),
s.iscube(-1),
s.iscube(64),
!s.iscube(180),
s.iscube(1000),
s.iscube(0),
!s.iscube(1729)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that takes an integer a and returns true
if this ingeger is a cube of some integer number.
Note: you may assume the input is always valid.
Examples:
iscube(1) ==> true
iscube(2) ==> false
iscube(-1) ==> true
iscube(64) ==> true
iscube(0) ==> true
iscube(180) ==> false
*/
public boolean iscube(int a) {
a = Math.abs(a);
return Math.round(Math.pow(Math.round(Math.pow(a, 1. / 3)), 3)) == a;
}
}
|
humaneval-x-java_data_Java_78
|
You have been tasked to write a function that receives
a hexadecimal number as a string and counts the number of hexadecimal
digits that are primes (prime number, or a prime, is a natural number
greater than 1 that is not a product of two smaller natural numbers).
Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
So you have to determine a number of the following digits: 2, 3, 5, 7,
B (=decimal 11), D (=decimal 13).
Note: you may assume the input is always correct or empty string,
and symbols A,B,C,D,E,F are always uppercase.
Examples:
For num = "AB" the output should be 1.
For num = "1077E" the output should be 2.
For num = "ABED1A33" the output should be 4.
For num = "123456789ABCDEF0" the output should be 6.
For num = "2020" the output should be 2.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.hexKey("AB") == 1,
s.hexKey("1077E") == 2,
s.hexKey("ABED1A33") == 4,
s.hexKey("2020") == 2,
s.hexKey("123456789ABCDEF0") == 6,
s.hexKey("112233445566778899AABBCCDDEEFF00") == 12,
s.hexKey("") == 0
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You have been tasked to write a function that receives
a hexadecimal number as a string and counts the number of hexadecimal
digits that are primes (prime number, or a prime, is a natural number
greater than 1 that is not a product of two smaller natural numbers).
Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
So you have to determine a number of the following digits: 2, 3, 5, 7,
B (=decimal 11), D (=decimal 13).
Note: you may assume the input is always correct or empty string,
and symbols A,B,C,D,E,F are always uppercase.
Examples:
For num = "AB" the output should be 1.
For num = "1077E" the output should be 2.
For num = "ABED1A33" the output should be 4.
For num = "123456789ABCDEF0" the output should be 6.
For num = "2020" the output should be 2.
*/
public int hexKey(String num) {
String primes = "2357BD";
int total = 0;
for (char c : num.toCharArray()) {
if (primes.indexOf(c) != -1) {
total += 1;
}
}
return total;
}
}
|
humaneval-x-java_data_Java_79
|
You will be given a number in decimal form and your task is to convert it to
binary format. The function should return a string, with each character representing a binary
number. Each character in the string will be '0' or '1'.
There will be an extra couple of characters 'db' at the beginning and at the end of the string.
The extra characters are there to help with the format.
Examples:
decimalToBinary(15) // returns "db1111db"
decimalToBinary(32) // returns "db100000db"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.decimalToBinary(0), "db0db"),
Objects.equals(s.decimalToBinary(32), "db100000db"),
Objects.equals(s.decimalToBinary(103), "db1100111db"),
Objects.equals(s.decimalToBinary(15), "db1111db")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You will be given a number in decimal form and your task is to convert it to
binary format. The function should return a string, with each character representing a binary
number. Each character in the string will be '0' or '1'.
There will be an extra couple of characters 'db' at the beginning and at the end of the string.
The extra characters are there to help with the format.
Examples:
decimalToBinary(15) // returns "db1111db"
decimalToBinary(32) // returns "db100000db"
*/
public String decimalToBinary(int decimal) {
return "db" + Integer.toBinaryString(decimal) + "db";
}
}
|
humaneval-x-java_data_Java_80
|
You are given a string s.
Your task is to check if the string is happy or not.
A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
For example:
isHappy(a) => false
isHappy(aa) => false
isHappy(abcd) => true
isHappy(aabb) => false
isHappy(adb) => true
isHappy(xyy) => false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
!s.isHappy("a"),
!s.isHappy("aa"),
s.isHappy("abcd"),
!s.isHappy("aabb"),
s.isHappy("adb"),
!s.isHappy("xyy"),
s.isHappy("iopaxpoi"),
!s.isHappy("iopaxioi")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You are given a string s.
Your task is to check if the string is happy or not.
A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
For example:
isHappy(a) => false
isHappy(aa) => false
isHappy(abcd) => true
isHappy(aabb) => false
isHappy(adb) => true
isHappy(xyy) => false
*/
public boolean isHappy(String s) {
if (s.length() < 3) {
return false;
}
for (int i = 0; i < s.length() - 2; i++) {
if (s.charAt(i) == s.charAt(i + 1) || s.charAt(i + 1) == s.charAt(i + 2) || s.charAt(i) == s.charAt(i + 2)) {
return false;
}
}
return true;
}
}
|
humaneval-x-java_data_Java_81
|
It is the last week of the semester and the teacher has to give the grades
to students. The teacher has been making her own algorithm for grading.
The only problem is, she has lost the code she used for grading.
She has given you a list of GPAs for some students and you have to write
a function that can output a list of letter grades using the following table:
GPA | Letter grade
4.0 A+
> 3.7 A
> 3.3 A-
> 3.0 B+
> 2.7 B
> 2.3 B-
> 2.0 C+
> 1.7 C
> 1.3 C-
> 1.0 D+
> 0.7 D
> 0.0 D-
0.0 E
Example:
numericalLetterGrade(Arrays.asList(4.0, 3, 1.7, 2, 3.5)) ==> ["A+", "B", "C-", "C", "A-"]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.numericalLetterGrade(new ArrayList<>(Arrays.asList(4.0, 3.0, 1.7, 2.0, 3.5))).equals(Arrays.asList("A+", "B", "C-", "C", "A-")),
s.numericalLetterGrade(new ArrayList<>(List.of(1.2))).equals(List.of("D+")),
s.numericalLetterGrade(new ArrayList<>(List.of(0.5))).equals(List.of("D-")),
s.numericalLetterGrade(new ArrayList<>(List.of(0.0))).equals(List.of("E")),
s.numericalLetterGrade(new ArrayList<>(Arrays.asList(1.0, 0.3, 1.5, 2.8, 3.3))).equals(Arrays.asList("D", "D-", "C-", "B", "B+")),
s.numericalLetterGrade(new ArrayList<>(Arrays.asList(0.0, 0.7))).equals(Arrays.asList("E", "D-"))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
It is the last week of the semester and the teacher has to give the grades
to students. The teacher has been making her own algorithm for grading.
The only problem is, she has lost the code she used for grading.
She has given you a list of GPAs for some students and you have to write
a function that can output a list of letter grades using the following table:
GPA | Letter grade
4.0 A+
> 3.7 A
> 3.3 A-
> 3.0 B+
> 2.7 B
> 2.3 B-
> 2.0 C+
> 1.7 C
> 1.3 C-
> 1.0 D+
> 0.7 D
> 0.0 D-
0.0 E
Example:
numericalLetterGrade(Arrays.asList(4.0, 3, 1.7, 2, 3.5)) ==> ["A+", "B", "C-", "C", "A-"]
*/
public List<String> numericalLetterGrade(List<Double> grades) {
List<String> letter_grade = new ArrayList<>();
for (double gpa : grades) {
if (gpa == 4.0) {
letter_grade.add("A+");
} else if (gpa > 3.7) {
letter_grade.add("A");
} else if (gpa > 3.3) {
letter_grade.add("A-");
} else if (gpa > 3.0) {
letter_grade.add("B+");
} else if (gpa > 2.7) {
letter_grade.add("B");
} else if (gpa > 2.3) {
letter_grade.add("B-");
} else if (gpa > 2.0) {
letter_grade.add("C+");
} else if (gpa > 1.7) {
letter_grade.add("C");
} else if (gpa > 1.3) {
letter_grade.add("C-");
} else if (gpa > 1.0) {
letter_grade.add("D+");
} else if (gpa > 0.7) {
letter_grade.add("D");
} else if (gpa > 0.0) {
letter_grade.add("D-");
} else {
letter_grade.add("E");
}
}
return letter_grade;
}
}
|
humaneval-x-java_data_Java_82
|
Write a function that takes a string and returns true if the string
length is a prime number or false otherwise
Examples
primeLength("Hello") == true
primeLength("abcdcba") == true
primeLength("kittens") == true
primeLength("orange") == false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.primeLength("Hello") == true,
s.primeLength("abcdcba") == true,
s.primeLength("kittens") == true,
s.primeLength("orange") == false,
s.primeLength("wow") == true,
s.primeLength("world") == true,
s.primeLength("MadaM") == true,
s.primeLength("Wow") == true,
s.primeLength("") == false,
s.primeLength("HI") == true,
s.primeLength("go") == true,
s.primeLength("gogo") == false,
s.primeLength("aaaaaaaaaaaaaaa") == false,
s.primeLength("Madam") == true,
s.primeLength("M") == false,
s.primeLength("0") == false
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that takes a string and returns true if the string
length is a prime number or false otherwise
Examples
primeLength("Hello") == true
primeLength("abcdcba") == true
primeLength("kittens") == true
primeLength("orange") == false
*/
public boolean primeLength(String string) {
int l = string.length();
if (l == 0 || l == 1) {
return false;
}
for (int i = 2; i < l; i++) {
if (l % i == 0) {
return false;
}
}
return true;
}
}
|
humaneval-x-java_data_Java_83
|
Given a positive integer n, return the count of the numbers of n-digit
positive integers that start or end with 1.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.startsOneEnds(1) == 1,
s.startsOneEnds(2) == 18,
s.startsOneEnds(3) == 180,
s.startsOneEnds(4) == 1800,
s.startsOneEnds(5) == 18000
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a positive integer n, return the count of the numbers of n-digit
positive integers that start or end with 1.
*/
public int startsOneEnds(int n) {
if (n == 1) {
return 1;
}
return 18 * (int) Math.pow(10, n - 2);
}
}
|
humaneval-x-java_data_Java_84
|
Given a positive integer N, return the total sum of its digits in binary.
Example
For N = 1000, the sum of digits will be 1 the output should be "1".
For N = 150, the sum of digits will be 6 the output should be "110".
For N = 147, the sum of digits will be 12 the output should be "1100".
Variables:
@N integer
Constraints: 0 <= N <= 10000.
Output:
a string of binary number
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.solve(1000), "1"),
Objects.equals(s.solve(150), "110"),
Objects.equals(s.solve(147), "1100"),
Objects.equals(s.solve(333), "1001"),
Objects.equals(s.solve(963), "10010")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a positive integer N, return the total sum of its digits in binary.
Example
For N = 1000, the sum of digits will be 1 the output should be "1".
For N = 150, the sum of digits will be 6 the output should be "110".
For N = 147, the sum of digits will be 12 the output should be "1100".
Variables:
@N integer
Constraints: 0 <= N <= 10000.
Output:
a string of binary number
*/
public String solve(int N) {
int sum = 0;
for (char c : String.valueOf(N).toCharArray()) {
sum += (c - '0');
}
return Integer.toBinaryString(sum);
}
}
|
humaneval-x-java_data_Java_85
|
Given a non-empty list of integers lst. add the even elements that are at odd indices..
Examples:
add(Arrays.asList(4, 2, 6, 7)) ==> 2
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.add(new ArrayList<>(Arrays.asList(4, 88))) == 88,
s.add(new ArrayList<>(Arrays.asList(4, 5, 6, 7, 2, 122))) == 122,
s.add(new ArrayList<>(Arrays.asList(4, 0, 6, 7))) == 0,
s.add(new ArrayList<>(Arrays.asList(4, 4, 6, 8))) == 12
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a non-empty list of integers lst. add the even elements that are at odd indices..
Examples:
add(Arrays.asList(4, 2, 6, 7)) ==> 2
*/
public int add(List<Integer> lst) {
int sum = 0;
for (int i = 1; i < lst.size(); i += 2) {
if (lst.get(i) % 2 == 0) {
sum += lst.get(i);
}
}
return sum;
}
}
|
humaneval-x-java_data_Java_86
|
Write a function that takes a string and returns an ordered version of it.
Ordered version of string, is a string where all words (separated by space)
are replaced by a new word where all the characters arranged in
ascending order based on ascii value.
Note: You should keep the order of words and blank spaces in the sentence.
For example:
antiShuffle("Hi") returns "Hi"
antiShuffle("hello") returns "ehllo"
antiShuffle("Hello World!!!") returns "Hello !!!Wdlor"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.antiShuffle("Hi"), "Hi"),
Objects.equals(s.antiShuffle("hello"), "ehllo"),
Objects.equals(s.antiShuffle("number"), "bemnru"),
Objects.equals(s.antiShuffle("abcd"), "abcd"),
Objects.equals(s.antiShuffle("Hello World!!!"), "Hello !!!Wdlor"),
Objects.equals(s.antiShuffle(""), ""),
Objects.equals(s.antiShuffle("Hi. My name is Mister Robot. How are you?"), ".Hi My aemn is Meirst .Rboot How aer ?ouy")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that takes a string and returns an ordered version of it.
Ordered version of string, is a string where all words (separated by space)
are replaced by a new word where all the characters arranged in
ascending order based on ascii value.
Note: You should keep the order of words and blank spaces in the sentence.
For example:
antiShuffle("Hi") returns "Hi"
antiShuffle("hello") returns "ehllo"
antiShuffle("Hello World!!!") returns "Hello !!!Wdlor"
*/
public String antiShuffle(String s) {
String[] strings = s.split(" ");
List<String> result = new ArrayList<>();
for (String string : strings) {
char[] chars = string.toCharArray();
Arrays.sort(chars);
result.add(String.copyValueOf(chars));
}
return String.join(" ", result);
}
}
|
humaneval-x-java_data_Java_87
|
You are given a 2 dimensional data, as a nested lists,
which is similar to matrix, however, unlike matrices,
each row may contain a different number of columns.
Given lst, and integer x, find integers x in the list,
and return list of lists, [[x1, y1], [x2, y2] ...] such that
each list is a coordinate - (row, columns), starting with 0.
Sort coordinates initially by rows in ascending order.
Also, sort coordinates of the row by columns in descending order.
Examples:
getRow([
[1,2,3,4,5,6],
[1,2,3,4,1,6],
[1,2,3,4,5,1]
], 1) == [[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]]
getRow([], 1) == []
getRow([[], [1], [1, 2, 3]], 3) == [[2, 2]]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.getRow(Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 1, 6),
Arrays.asList(1, 2, 3, 4, 5, 1)
), 1).equals(Arrays.asList(Arrays.asList(0, 0), Arrays.asList(1, 4), Arrays.asList(1, 0), Arrays.asList(2, 5), Arrays.asList(2, 0))),
s.getRow(Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6)
), 2).equals(Arrays.asList(Arrays.asList(0, 1), Arrays.asList(1, 1), Arrays.asList(2, 1), Arrays.asList(3, 1), Arrays.asList(4, 1), Arrays.asList(5, 1))),
s.getRow(Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(1, 1, 3, 4, 5, 6),
Arrays.asList(1, 2, 1, 4, 5, 6),
Arrays.asList(1, 2, 3, 1, 5, 6),
Arrays.asList(1, 2, 3, 4, 1, 6),
Arrays.asList(1, 2, 3, 4, 5, 1)
), 1).equals(Arrays.asList(Arrays.asList(0, 0), Arrays.asList(1, 0), Arrays.asList(2, 1), Arrays.asList(2, 0), Arrays.asList(3, 2), Arrays.asList(3, 0), Arrays.asList(4, 3), Arrays.asList(4, 0), Arrays.asList(5, 4), Arrays.asList(5, 0), Arrays.asList(6, 5), Arrays.asList(6, 0))),
s.getRow(List.of(), 1).equals(List.of()),
s.getRow(List.of(List.of(1)), 2).equals(List.of()),
s.getRow(Arrays.asList(List.of(), List.of(1), Arrays.asList(1, 2, 3)), 3).equals(List.of(Arrays.asList(2, 2)))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You are given a 2 dimensional data, as a nested lists,
which is similar to matrix, however, unlike matrices,
each row may contain a different number of columns.
Given lst, and integer x, find integers x in the list,
and return list of lists, [[x1, y1], [x2, y2] ...] such that
each list is a coordinate - (row, columns), starting with 0.
Sort coordinates initially by rows in ascending order.
Also, sort coordinates of the row by columns in descending order.
Examples:
getRow([
[1,2,3,4,5,6],
[1,2,3,4,1,6],
[1,2,3,4,5,1]
], 1) == [[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]]
getRow([], 1) == []
getRow([[], [1], [1, 2, 3]], 3) == [[2, 2]]
*/
public List<List<Integer>> getRow(List<List<Integer>> lst, int x) {
List<List<Integer>> coords = new ArrayList<>();
for (int i = 0; i < lst.size(); i++) {
List<List<Integer>> row = new ArrayList<>();
for (int j = lst.get(i).size() - 1; j >= 0; j--) {
if (lst.get(i).get(j) == x) {
row.add(Arrays.asList(i, j));
}
}
coords.addAll(row);
}
return coords;
}
}
|
humaneval-x-java_data_Java_88
|
Given an array of non-negative integers, return a copy of the given array after sorting,
you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
or sort it in descending order if the sum( first index value, last index value) is even.
Note:
* don't change the given array.
Examples:
* sortArray(Arrays.asList()) => []
* sortArray(Arrays.asList(5)) => [5]
* sortArray(Arrays.asList(2, 4, 3, 0, 1, 5)) => [0, 1, 2, 3, 4, 5]
* sortArray(Arrays.asList(2, 4, 3, 0, 1, 5, 6)) => [6, 5, 4, 3, 2, 1, 0]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.sortArray(new ArrayList<>(List.of())).equals(List.of()),
s.sortArray(new ArrayList<>(List.of(5))).equals(List.of(5)),
s.sortArray(new ArrayList<>(Arrays.asList(2, 4, 3, 0, 1, 5))).equals(Arrays.asList(0, 1, 2, 3, 4, 5)),
s.sortArray(new ArrayList<>(Arrays.asList(2, 4, 3, 0, 1, 5, 6))).equals(Arrays.asList(6, 5, 4, 3, 2, 1, 0)),
s.sortArray(new ArrayList<>(Arrays.asList(2, 1))).equals(Arrays.asList(1, 2)),
s.sortArray(new ArrayList<>(Arrays.asList(15, 42, 87, 32 ,11, 0))).equals(Arrays.asList(0, 11, 15, 32, 42, 87)),
s.sortArray(new ArrayList<>(Arrays.asList(21, 14, 23, 11))).equals(Arrays.asList(23, 21, 14, 11))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given an array of non-negative integers, return a copy of the given array after sorting,
you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
or sort it in descending order if the sum( first index value, last index value) is even.
Note:
* don't change the given array.
Examples:
* sortArray(Arrays.asList()) => []
* sortArray(Arrays.asList(5)) => [5]
* sortArray(Arrays.asList(2, 4, 3, 0, 1, 5)) => [0, 1, 2, 3, 4, 5]
* sortArray(Arrays.asList(2, 4, 3, 0, 1, 5, 6)) => [6, 5, 4, 3, 2, 1, 0]
*/
public List<Integer> sortArray(List<Integer> array) {
if (array.size() == 0) {
return array;
}
List<Integer> result = new ArrayList<>(array);
if ((result.get(0) + result.get(result.size() - 1)) % 2 == 1) {
Collections.sort(result);
} else {
result.sort(Collections.reverseOrder());
}
return result;
}
}
|
humaneval-x-java_data_Java_89
|
Create a function encrypt that takes a string as an argument and
returns a string encrypted with the alphabet being rotated.
The alphabet should be rotated in a manner such that the letters
shift down by two multiplied to two places.
For example:
encrypt("hi") returns "lm"
encrypt("asdfghjkl") returns "ewhjklnop"
encrypt("gf") returns "kj"
encrypt("et") returns "ix"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.encrypt("hi"), "lm"),
Objects.equals(s.encrypt("asdfghjkl"), "ewhjklnop"),
Objects.equals(s.encrypt("gf"), "kj"),
Objects.equals(s.encrypt("et"), "ix"),
Objects.equals(s.encrypt("faewfawefaewg"), "jeiajeaijeiak"),
Objects.equals(s.encrypt("hellomyfriend"), "lippsqcjvmirh"),
Objects.equals(s.encrypt("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh"), "hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"),
Objects.equals(s.encrypt("a"), "e")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Create a function encrypt that takes a string as an argument and
returns a string encrypted with the alphabet being rotated.
The alphabet should be rotated in a manner such that the letters
shift down by two multiplied to two places.
For example:
encrypt("hi") returns "lm"
encrypt("asdfghjkl") returns "ewhjklnop"
encrypt("gf") returns "kj"
encrypt("et") returns "ix"
*/
public String encrypt(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
sb.append((char) ('a' + (c - 'a' + 2 * 2) % 26));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
|
humaneval-x-java_data_Java_90
|
You are given a list of integers.
Write a function nextSmallest() that returns the 2nd smallest element of the list.
Return null if there is no such element.
<p>
nextSmallest(Arrays.asList(1, 2, 3, 4, 5)) == Optional[2]
nextSmallest(Arrays.asList(5, 1, 4, 3, 2)) == Optional[2]
nextSmallest(Arrays.asList()) == Optional.empty
nextSmallest(Arrays.asList(1, 1)) == Optional.empty
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.nextSmallest(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))).get() == 2,
s.nextSmallest(new ArrayList<>(Arrays.asList(5, 1, 4, 3, 2))).get() == 2,
s.nextSmallest(new ArrayList<>(List.of())).isEmpty(),
s.nextSmallest(new ArrayList<>(Arrays.asList(1, 1))).isEmpty(),
s.nextSmallest(new ArrayList<>(Arrays.asList(1, 1, 1, 1, 0))).get() == 1,
s.nextSmallest(new ArrayList<>(Arrays.asList(1, (int) Math.pow(0.0, 0.0)))).isEmpty(),
s.nextSmallest(new ArrayList<>(Arrays.asList(-35, 34, 12, -45))).get() == -35
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You are given a list of integers.
Write a function nextSmallest() that returns the 2nd smallest element of the list.
Return null if there is no such element.
<p>
nextSmallest(Arrays.asList(1, 2, 3, 4, 5)) == Optional[2]
nextSmallest(Arrays.asList(5, 1, 4, 3, 2)) == Optional[2]
nextSmallest(Arrays.asList()) == Optional.empty
nextSmallest(Arrays.asList(1, 1)) == Optional.empty
*/
public Optional<Integer> nextSmallest(List<Integer> lst) {
Set < Integer > set = new HashSet<>(lst);
List<Integer> l = new ArrayList<>(set);
Collections.sort(l);
if (l.size() < 2) {
return Optional.empty();
} else {
return Optional.of(l.get(1));
}
}
}
|
humaneval-x-java_data_Java_91
|
You'll be given a string of words, and your task is to count the number
of boredoms. A boredom is a sentence that starts with the word "I".
Sentences are delimited by '.', '?' or '!'.
For example:
>>> isBored("Hello world")
0
>>> isBored("The sky is blue. The sun is shining. I love this weather")
1
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.isBored("Hello world") == 0,
s.isBored("Is the sky blue?") == 0,
s.isBored("I love It !") == 1,
s.isBored("bIt") == 0,
s.isBored("I feel good today. I will be productive. will kill It") == 2,
s.isBored("You and I are going for a walk") == 0
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You'll be given a string of words, and your task is to count the number
of boredoms. A boredom is a sentence that starts with the word "I".
Sentences are delimited by '.', '?' or '!'.
For example:
>>> isBored("Hello world")
0
>>> isBored("The sky is blue. The sun is shining. I love this weather")
1
*/
public int isBored(String S) {
String [] sentences = S.split("[.?!]\s*");
int count = 0;
for (String sentence : sentences) {
if (sentence.subSequence(0, 2).equals("I ")) {
count += 1;
}
}
return count;
}
}
|
humaneval-x-java_data_Java_92
|
Create a function that takes 3 numbers.
Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
Returns false in any other cases.
Examples
anyInt(5, 2, 7) -> true
anyInt(3, 2, 2) -> false
anyInt(3, -2, 1) -> true
anyInt(3.6, -2.2, 2) -> false
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.anyInt(2, 3, 1) == true,
s.anyInt(2.5, 2, 3) == false,
s.anyInt(1.5, 5, 3.5) == false,
s.anyInt(2, 6, 2) == false,
s.anyInt(4, 2, 2) == true,
s.anyInt(2.2, 2.2, 2.2) == false,
s.anyInt(-4, 6, 2) == true,
s.anyInt(2, 1, 1) == true,
s.anyInt(3, 4, 7) == true,
s.anyInt(3.0, 4, 7) == false
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Create a function that takes 3 numbers.
Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
Returns false in any other cases.
Examples
anyInt(5, 2, 7) -> true
anyInt(3, 2, 2) -> false
anyInt(3, -2, 1) -> true
anyInt(3.6, -2.2, 2) -> false
*/
public boolean anyInt(Object x, Object y, Object z) {
if (x instanceof Integer && y instanceof Integer && z instanceof Integer) {
return (int) x + (int) y == (int) z || (int) x + (int) z == (int) y || (int) y + (int) z == (int) x;
}
return false;
}
}
|
humaneval-x-java_data_Java_93
|
Write a function that takes a message, and encodes in such a
way that it swaps case of all letters, replaces all vowels in
the message with the letter that appears 2 places ahead of that
vowel in the english alphabet.
Assume only letters.
Examples:
>>> encode("test")
"TGST"
>>> encode("This is a message")
"tHKS KS C MGSSCGG"
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
Objects.equals(s.encode("TEST"), "tgst"),
Objects.equals(s.encode("Mudasir"), "mWDCSKR"),
Objects.equals(s.encode("YES"), "ygs"),
Objects.equals(s.encode("This is a message"), "tHKS KS C MGSSCGG"),
Objects.equals(s.encode("I DoNt KnOw WhAt tO WrItE"), "k dQnT kNqW wHcT Tq wRkTg")
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Write a function that takes a message, and encodes in such a
way that it swaps case of all letters, replaces all vowels in
the message with the letter that appears 2 places ahead of that
vowel in the english alphabet.
Assume only letters.
Examples:
>>> encode("test")
"TGST"
>>> encode("This is a message")
"tHKS KS C MGSSCGG"
*/
public String encode(String message) {
String vowels = "aeiouAEIOU";
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
char ch = c;
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
if (vowels.indexOf(ch) != -1) {
ch = (char) ('a' + ((ch - 'a' + 28) % 26));
}
} else if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
if (vowels.indexOf(ch) != -1) {
ch = (char) ('A' + ((ch - 'A' + 28) % 26));
}
}
sb.append(ch);
}
return sb.toString();
}
}
|
humaneval-x-java_data_Java_94
|
You are given a list of integers.
You need to find the largest prime value and return the sum of its digits.
Examples:
For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10
For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25
For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13
For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11
For lst = [0,81,12,3,1,21] the output should be 3
For lst = [0,8,1,2,1,7] the output should be 7
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.skjkasdkd(Arrays.asList(0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3)) == 10,
s.skjkasdkd(Arrays.asList(1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1)) == 25,
s.skjkasdkd(Arrays.asList(1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3)) == 13,
s.skjkasdkd(Arrays.asList(0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6)) == 11,
s.skjkasdkd(Arrays.asList(0, 81, 12, 3, 1, 21)) == 3,
s.skjkasdkd(Arrays.asList(0, 8, 1, 2, 1, 7)) == 7,
s.skjkasdkd(List.of(8191)) == 19,
s.skjkasdkd(Arrays.asList(8191, 123456, 127, 7)) == 19,
s.skjkasdkd(Arrays.asList(127, 97, 8192)) == 10
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
You are given a list of integers.
You need to find the largest prime value and return the sum of its digits.
Examples:
For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10
For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25
For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13
For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11
For lst = [0,81,12,3,1,21] the output should be 3
For lst = [0,8,1,2,1,7] the output should be 7
*/
public int skjkasdkd(List<Integer> lst) {
int maxx = 0;
for (int i : lst) {
if (i > maxx) {
boolean isPrime = i != 1;
for (int j = 2; j < Math.sqrt(i) + 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
maxx = i;
}
}
}
int sum = 0;
for (char c : String.valueOf(maxx).toCharArray()) {
sum += (c - '0');
}
return sum;
}
}
|
humaneval-x-java_data_Java_95
|
Given a map, return True if all keys are strings in lower
case or all keys are strings in upper case, else return False.
The function should return False is the given map is empty.
Examples:
checkDictCase({"a":"apple", "b":"banana"}) should return True.
checkDictCase({"a":"apple", "A":"banana", "B":"banana"}) should return False.
checkDictCase({"a":"apple", 8:"banana", "a":"apple"}) should return False.
checkDictCase({"Name":"John", "Age":"36", "City":"Houston"}) should return False.
checkDictCase({"STATE":"NC", "ZIP":"12345" }) should return True.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
Map<Object, Object> map1 = new HashMap<>();
map1.put("p", "pineapple");
map1.put("b", "banana");
Map<Object, Object> map2 = new HashMap<>();
map2.put("p", "pineapple");
map2.put("A", "banana");
map2.put("B", "banana");
Map<Object, Object> map3 = new HashMap<>();
map3.put("p", "pineapple");
map3.put(5, "banana");
map3.put("a", "banana");
Map<Object, Object> map4 = new HashMap<>();
map4.put("Name", "John");
map4.put("Age", "36");
map4.put("City", "Houston");
Map<Object, Object> map5 = new HashMap<>();
map5.put("STATE", "NC");
map5.put("ZIP", "12345");
Map<Object, Object> map6 = new HashMap<>();
map6.put("fruit", "Orange");
map6.put("taste", "Sweet");
Map<Object, Object> map7 = new HashMap<>();
List<Boolean> correct = Arrays.asList(
s.checkDictCase(map1),
!s.checkDictCase(map2),
!s.checkDictCase(map3),
!s.checkDictCase(map4),
s.checkDictCase(map5),
s.checkDictCase(map6),
!s.checkDictCase(map7)
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a map, return True if all keys are strings in lower
case or all keys are strings in upper case, else return False.
The function should return False is the given map is empty.
Examples:
checkDictCase({"a":"apple", "b":"banana"}) should return True.
checkDictCase({"a":"apple", "A":"banana", "B":"banana"}) should return False.
checkDictCase({"a":"apple", 8:"banana", "a":"apple"}) should return False.
checkDictCase({"Name":"John", "Age":"36", "City":"Houston"}) should return False.
checkDictCase({"STATE":"NC", "ZIP":"12345" }) should return True.
*/
public boolean checkDictCase(Map<Object, Object> dict) {
if (dict.isEmpty()) {
return false;
}
String state = "start";
for (Map.Entry entry : dict.entrySet()) {
if (!(entry.getKey() instanceof String key)) {
state = "mixed";
break;
}
boolean is_upper = true, is_lower = true;
for (char c : key.toCharArray()) {
if (Character.isLowerCase(c)) {
is_upper = false;
} else if (Character.isUpperCase(c)) {
is_lower = false;
} else {
is_upper = false;
is_lower = false;
}
}
if (state.equals("start")) {
if (is_upper) {
state = "upper";
} else if (is_lower) {
state = "lower";
} else {
break;
}
} else if ((state.equals("upper") && !is_upper) || (state.equals("lower") && !is_lower)) {
state = "mixed";
break;
}
}
return state.equals("upper") || state.equals("lower");
}
}
|
humaneval-x-java_data_Java_96
|
Implement a function that takes an non-negative integer and returns an array of the first n
integers that are prime numbers and less than n.
for example:
countUpTo(5) => [2,3]
countUpTo(11) => [2,3,5,7]
countUpTo(0) => []
countUpTo(20) => [2,3,5,7,11,13,17,19]
countUpTo(1) => []
countUpTo(18) => [2,3,5,7,11,13,17]
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.countUpTo(5).equals(Arrays.asList(2, 3)),
s.countUpTo(6).equals(Arrays.asList(2, 3, 5)),
s.countUpTo(7).equals(Arrays.asList(2, 3, 5)),
s.countUpTo(10).equals(Arrays.asList(2, 3, 5, 7)),
s.countUpTo(0).equals(List.of()),
s.countUpTo(22).equals(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19)),
s.countUpTo(1).equals(List.of()),
s.countUpTo(18).equals(Arrays.asList(2, 3, 5, 7, 11, 13, 17)),
s.countUpTo(47).equals(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43)),
s.countUpTo(101).equals(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97))
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Implement a function that takes an non-negative integer and returns an array of the first n
integers that are prime numbers and less than n.
for example:
countUpTo(5) => [2,3]
countUpTo(11) => [2,3,5,7]
countUpTo(0) => []
countUpTo(20) => [2,3,5,7,11,13,17,19]
countUpTo(1) => []
countUpTo(18) => [2,3,5,7,11,13,17]
*/
public List<Integer> countUpTo(int n) {
List<Integer> primes = new ArrayList<>();
for (int i = 2; i < n; i++) {
boolean is_prime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primes.add(i);
}
}
return primes;
}
}
|
humaneval-x-java_data_Java_97
|
Complete the function that takes two integers and returns
the product of their unit digits.
Assume the input is always valid.
Examples:
multiply(148, 412) should return 16.
multiply(19, 28) should return 72.
multiply(2020, 1851) should return 0.
multiply(14,-15) should return 20.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.multiply(148, 412) == 16,
s.multiply(19, 28) == 72,
s.multiply(2020, 1851) == 0,
s.multiply(14,-15) == 20,
s.multiply(76, 67) == 42,
s.multiply(17, 27) == 49,
s.multiply(0, 1) == 0,
s.multiply(0, 0) == 0
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Complete the function that takes two integers and returns
the product of their unit digits.
Assume the input is always valid.
Examples:
multiply(148, 412) should return 16.
multiply(19, 28) should return 72.
multiply(2020, 1851) should return 0.
multiply(14,-15) should return 20.
*/
public int multiply(int a, int b) {
return Math.abs(a % 10) * Math.abs(b % 10);
}
}
|
humaneval-x-java_data_Java_98
|
Given a string s, count the number of uppercase vowels in even indices.
For example:
countUpper("aBCdEf") returns 1
countUpper("abcdefg") returns 0
countUpper("dBBE") returns 0
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.countUpper("aBCdEf") == 1,
s.countUpper("abcdefg") == 0,
s.countUpper("dBBE") == 0,
s.countUpper("B") == 0,
s.countUpper("U") == 1,
s.countUpper("") == 0,
s.countUpper("EEEE") == 2
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Given a string s, count the number of uppercase vowels in even indices.
For example:
countUpper("aBCdEf") returns 1
countUpper("abcdefg") returns 0
countUpper("dBBE") returns 0
*/
public int countUpper(String s) {
int count = 0;
for (int i = 0; i < s.length(); i += 2) {
if ("AEIOU".indexOf(s.charAt(i)) != -1) {
count += 1;
}
}
return count;
}
}
|
humaneval-x-java_data_Java_99
|
Create a function that takes a value (string) representing a number
and returns the closest integer to it. If the number is equidistant
from two integers, round it away from zero.
Examples
>>> closest_integer("10")
10
>>> closest_integer("15.3")
15
Note:
Rounding away from zero means that if the given number is equidistant
from two integers, the one you should return is the one that is the
farthest from zero. For example closest_integer("14.5") should
return 15 and closest_integer("-14.5") should return -15.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
List<Boolean> correct = Arrays.asList(
s.countUpper("10") == 10,
s.countUpper("14.5") == 15,
s.countUpper("-15.5") == -16,
s.countUpper("15.3") == 15,
s.countUpper("0") == 0
);
if (correct.contains(false)) {
throw new AssertionError();
}
}
}
import java.util.*;
import java.lang.*;
class Solution {
/**
Create a function that takes a value (string) representing a number
and returns the closest integer to it. If the number is equidistant
from two integers, round it away from zero.
Examples
>>> closest_integer("10")
10
>>> closest_integer("15.3")
15
Note:
Rounding away from zero means that if the given number is equidistant
from two integers, the one you should return is the one that is the
farthest from zero. For example closest_integer("14.5") should
return 15 and closest_integer("-14.5") should return -15.
*/
public int countUpper(String value) {
if (value.contains(".")) {
while (value.charAt(value.length() - 1) == '0') {
value = value.substring(0, value.length() - 1);
}
}
double num = Double.parseDouble(value);
int res = 0;
if (value.substring(Math.max(value.length() - 2, 0)).equals(".5")) {
if (num > 0) {
res = (int) Math.ceil(num);
} else {
res = (int) Math.floor(num);
}
} else if(value.length() > 0) {
res = (int) Math.round(num);
}
return res;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.