prompt
stringlengths
96
1.46k
canonical_solution
stringlengths
16
1.4k
lang
stringclasses
5 values
source
stringclasses
1 value
// Given a positive integer n, you have to make a pile of n levels of stones. // The first level has n stones. // The number of stones in the next level is: // - the next odd number if n is odd. // - the next even number if n is even. // Return the number of stones in each level in a list, where element at index // i represents the number of stones in the level (i+1). // // Examples: // >>> MakeAPile(3) // [3, 5, 7] func MakeAPile(n int) []int {
result := make([]int, 0, n) for i := 0; i < n; i++ { result = append(result, n+2*i) } return result }
go
THUDM/humaneval-x
import ( "strings" ) // You will be given a string of words separated by commas or spaces. Your task is // to split the string into words and return an array of the words. // // For example: // WordsString("Hi, my name is John") == ["Hi", "my", "name", "is", "John"] // WordsString("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"] func WordsString(s string) []string {
s_list := make([]rune, 0) for _, c := range s { if c == ',' { s_list = append(s_list, ' ') } else { s_list = append(s_list, c) } } return strings.Fields(string(s_list)) }
go
THUDM/humaneval-x
// This function takes two positive numbers x and y and returns the // biggest even integer number that is in the range [x, y] inclusive. If // there's no such number, then the function should return -1. // // For example: // ChooseNum(12, 15) = 14 // ChooseNum(13, 12) = -1 func ChooseNum(x, y int) int {
if x > y { return -1 } if y % 2 == 0 { return y } if x == y { return -1 } return y - 1 }
go
THUDM/humaneval-x
import ( "fmt" "math" ) // You are given two positive integers n and m, and your task is to compute the // average of the integers from n through m (including n and m). // Round the answer to the nearest integer and convert that to binary. // If n is greater than m, return -1. // Example: // RoundedAvg(1, 5) => "0b11" // RoundedAvg(7, 5) => -1 // RoundedAvg(10, 20) => "0b1111" // RoundedAvg(20, 33) => "0b11010" func RoundedAvg(n, m int) interface{} {
if m < n { return -1 } summation := 0 for i := n;i < m+1;i++{ summation += i } return fmt.Sprintf("0b%b", int(math.Round(float64(summation)/float64(m - n + 1)))) }
go
THUDM/humaneval-x
import ( "sort" "strconv" ) // Given a list of positive integers x. return a sorted list of all // elements that hasn't any even digit. // // Note: Returned list should be sorted in increasing order. // // For example: // >>> UniqueDigits([15, 33, 1422, 1]) // [1, 15, 33] // >>> UniqueDigits([152, 323, 1422, 10]) // [] func UniqueDigits(x []int) []int {
odd_digit_elements := make([]int, 0) OUTER: for _, i := range x { for _, c := range strconv.Itoa(i) { if (c - '0') % 2 == 0 { continue OUTER } } odd_digit_elements = append(odd_digit_elements, i) } sort.Slice(odd_digit_elements, func(i, j int) bool { return odd_digit_elements[i] < odd_digit_elements[j] }) return odd_digit_elements }
go
THUDM/humaneval-x
import ( "sort" ) // Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // // For example: // arr = [2, 1, 1, 4, 5, 8, 2, 3] // -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] // -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1] // return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // // If the array is empty, return an empty array: // arr = [] // return [] // // If the array has any strange number ignore it: // arr = [1, -1 , 55] // -> sort arr -> [-1, 1, 55] // -> reverse arr -> [55, 1, -1] // return = ['One'] func ByLength(arr []int)[]string {
dic := map[int]string{ 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", } sort.Slice(arr, func(i, j int) bool { return arr[i] > arr[j] }) new_arr := make([]string, 0) for _, item := range arr { if v, ok := dic[item]; ok { new_arr = append(new_arr, v) } } return new_arr }
go
THUDM/humaneval-x
// Implement the Function F that takes n as a parameter, // and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // F(5) == [1, 2, 6, 24, 15] func F(n int) []int {
ret := make([]int, 0, 5) for i:=1;i<n+1;i++{ if i%2 == 0 { x := 1 for j:=1;j<i+1;j++{ x*=j } ret = append(ret, x) }else { x := 0 for j:=1;j<i+1;j++{ x+=j } ret = append(ret, x) } } return ret }
go
THUDM/humaneval-x
import ( "strconv" ) // Given a positive integer n, return a tuple that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // // Example 1: // // Input: 3 // Output: (1, 2) // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // // Example 2: // // Input: 12 // Output: (4, 6) // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // // Note: // 1. 1 <= n <= 10^3 // 2. returned tuple has the number of even and odd integer palindromes respectively. func EvenOddPalindrome(n int) [2]int {
is_palindrome := func (n int) bool { s := strconv.Itoa(n) for i := 0;i < len(s)>>1;i++ { if s[i] != s[len(s)-i-1] { return false } } return true } even_palindrome_count := 0 odd_palindrome_count := 0 for i :=1;i<n+1;i++ { if i%2 == 1 && is_palindrome(i){ odd_palindrome_count ++ } else if i%2 == 0 && is_palindrome(i) { even_palindrome_count ++ } } return [2]int{even_palindrome_count, odd_palindrome_count} }
go
THUDM/humaneval-x
import ( "math" "strconv" ) // Write a function CountNums which takes an array of integers and returns // the number of elements which has a sum of digits > 0. // If a number is negative, then its first signed digit will be negative: // e.g. -123 has signed digits -1, 2, and 3. // >>> CountNums([]) == 0 // >>> CountNums([-1, 11, -11]) == 1 // >>> CountNums([1, 1, 2]) == 3 func CountNums(arr []int) int {
digits_sum:= func (n int) int { neg := 1 if n < 0 { n, neg = -1 * n, -1 } r := make([]int,0) for _, c := range strconv.Itoa(n) { r = append(r, int(c-'0')) } r[0] *= neg sum := 0 for _, i := range r { sum += i } return sum } count := 0 for _, i := range arr { x := digits_sum(i) if x > 0 { count++ } } return count }
go
THUDM/humaneval-x
import ( "math" "sort" ) // We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array will be randomly ordered. Your task is to determine if // it is possible to get an array sorted in non-decreasing order by performing // the following operation on the given array: // You are allowed to perform right shift operation any number of times. // // One right shift operation means shifting all elements of the array by one // position in the right direction. The last element of the array will be moved to // the starting position in the array i.e. 0th index. // // If it is possible to obtain the sorted array by performing the above operation // then return true else return false. // If the given array is empty then return true. // // Note: The given list is guaranteed to have unique elements. // // For Example: // // MoveOneBall([3, 4, 5, 1, 2])==>true // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array. // MoveOneBall([3, 5, 4, 1, 2])==>false // Explanation:It is not possible to get non-decreasing order for the given // array by performing any number of right shift operations. func MoveOneBall(arr []int) bool {
if len(arr)==0 { return true } sorted_array := make([]int, len(arr)) copy(sorted_array, arr) sort.Slice(sorted_array, func(i, j int) bool { return sorted_array[i] < sorted_array[j] }) min_value := math.MaxInt min_index := -1 for i, x := range arr { if i < min_value { min_index, min_value = i, x } } my_arr := make([]int, len(arr[min_index:])) copy(my_arr, arr[min_index:]) my_arr = append(my_arr, arr[0:min_index]...) for i :=0;i<len(arr);i++ { if my_arr[i]!=sorted_array[i]{ return false } } return true }
go
THUDM/humaneval-x
// In this problem, you will implement a function that takes two lists of numbers, // and determines whether it is possible to perform an Exchange of elements // between them to make lst1 a list of only even numbers. // There is no limit on the number of Exchanged elements between lst1 and lst2. // If it is possible to Exchange elements between the lst1 and lst2 to make // all the elements of lst1 to be even, return "YES". // Otherwise, return "NO". // For example: // Exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES" // Exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO" // It is assumed that the input lists will be non-empty. func Exchange(lst1, lst2 []int) string {
odd := 0 even := 0 for _, i := range lst1 { if i%2 == 1 { odd++ } } for _, i := range lst2 { if i%2 == 0 { even++ } } if even >= odd { return "YES" } return "NO" }
go
THUDM/humaneval-x
import ( "strings" ) // Given a string representing a space separated lowercase letters, return a dictionary // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // // Example: // Histogram('a b c') == {'a': 1, 'b': 1, 'c': 1} // Histogram('a b b a') == {'a': 2, 'b': 2} // Histogram('a b c a b') == {'a': 2, 'b': 2} // Histogram('b b b b a') == {'b': 4} // Histogram('') == {} func Histogram(test string) map[rune]int {
dict1 := make(map[rune]int) list1 := strings.Fields(test) t := 0 count := func(lst []string, v string) int { cnt := 0 for _, i := range lst { if i == v { cnt++ } } return cnt } for _, i := range list1 { if c := count(list1, i); c>t && i!="" { t=c } } if t>0 { for _, i := range list1 { if count(list1, i)==t { dict1[[]rune(i)[0]]=t } } } return dict1 }
go
THUDM/humaneval-x
import ( "strings" ) // Task // We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c // then check if the result string is palindrome. // A string is called palindrome if it reads the same backward as forward. // You should return a tuple containing the result string and true/false for the check. // Example // For s = "abcde", c = "ae", the result should be ('bcd',false) // For s = "abcdef", c = "b" the result should be ('acdef',false) // For s = "abcdedcba", c = "ab", the result should be ('cdedc',true) func ReverseDelete(s,c string) [2]interface{} {
rs := make([]rune, 0) for _, r := range s { if !strings.ContainsRune(c, r) { rs = append(rs, r) } } t := true for i := 0;i < len(rs)>>1;i++ { if rs[i] != rs[len(rs)-i-1] { t=false break } } return [2]interface{}{string(rs), t} }
go
THUDM/humaneval-x
import ( "fmt" ) // Given a list of strings, where each string consists of only digits, return a list. // Each element i of the output should be "the number of odd elements in the // string i of the input." where all the i's should be replaced by the number // of odd digits in the i'th string of the input. // // >>> OddCount(['1234567']) // ["the number of odd elements 4n the str4ng 4 of the 4nput."] // >>> OddCount(['3',"11111111"]) // ["the number of odd elements 1n the str1ng 1 of the 1nput.", // "the number of odd elements 8n the str8ng 8 of the 8nput."] func OddCount(lst []string) []string {
res := make([]string, 0, len(lst)) for _, arr := range lst { n := 0 for _, d := range arr { if (d - '0') % 2 == 1 { n++ } } res = append(res, fmt.Sprintf("the number of odd elements %dn the str%dng %d of the %dnput.", n,n,n,n)) } return res }
go
THUDM/humaneval-x
import ( "math" ) // Given an array of integers nums, find the minimum sum of any non-empty sub-array // of nums. // Example // Minsubarraysum([2, 3, 4, 1, 2, 4]) == 1 // Minsubarraysum([-1, -2, -3]) == -6 func Minsubarraysum(nums []int) int {
max_sum := 0 s := 0 for _, num := range nums { s += -num if s < 0 { s = 0 } if s > max_sum { max_sum = s } } if max_sum == 0 { max_sum = math.MinInt for _, i := range nums { if -i > max_sum { max_sum = -i } } } return -max_sum }
go
THUDM/humaneval-x
import ( "math" ) // You are given a rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // // Example 1: // Input: // grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]] // bucket_capacity : 1 // Output: 6 // // Example 2: // Input: // grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]] // bucket_capacity : 2 // Output: 5 // // Example 3: // Input: // grid : [[0,0,0], [0,0,0]] // bucket_capacity : 5 // Output: 0 // // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 func MaxFill(grid [][]int, capacity int) int {
result := 0 for _, arr := range grid { sum := 0 for _, i := range arr { sum += i } result += int(math.Ceil(float64(sum) / float64(capacity))) } return result }
go
THUDM/humaneval-x
import ( "fmt" "sort" ) // In this Kata, you have to sort an array of non-negative integers according to // number of ones in their binary representation in ascending order. // For similar number of ones, sort based on decimal value. // // It must be implemented like this: // >>> SortArray([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5] // >>> SortArray([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2] // >>> SortArray([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4] func SortArray(arr []int) []int {
sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] }) sort.Slice(arr, func(i, j int) bool { key := func(x int) int { b := fmt.Sprintf("%b", x) cnt := 0 for _, r := range b { if r == '1' { cnt++ } } return cnt } return key(arr[i]) < key(arr[j]) }) return arr }
go
THUDM/humaneval-x
import ( "bytes" "strings" ) // Given a string s and a natural number n, you have been tasked to implement // a function that returns a list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty list. // Note: you may assume the input string contains only letters and spaces. // Examples: // SelectWords("Mary had a little lamb", 4) ==> ["little"] // SelectWords("Mary had a little lamb", 3) ==> ["Mary", "lamb"] // SelectWords("simple white space", 2) ==> [] // SelectWords("Hello world", 4) ==> ["world"] // SelectWords("Uncle sam", 3) ==> ["Uncle"] func SelectWords(s string, n int) []string {
result := make([]string, 0) for _, word := range strings.Fields(s) { n_consonants := 0 lower := strings.ToLower(word) for i := 0;i < len(word); i++ { if !bytes.Contains([]byte("aeiou"), []byte{lower[i]}) { n_consonants++ } } if n_consonants == n{ result = append(result, word) } } return result }
go
THUDM/humaneval-x
import ( "bytes" ) // You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // // You may assume that the given string contains English letter only. // // Example: // GetClosestVowel("yogurt") ==> "u" // GetClosestVowel("FULL") ==> "U" // GetClosestVowel("quick") ==> "" // GetClosestVowel("ab") ==> "" func GetClosestVowel(word string) string {
if len(word) < 3 { return "" } vowels := []byte("aeiouAEOUI") for i := len(word)-2; i > 0; i-- { if bytes.Contains(vowels, []byte{word[i]}) { if !bytes.Contains(vowels, []byte{word[i+1]}) && !bytes.Contains(vowels, []byte{word[i-1]}) { return string(word[i]) } } } return "" }
go
THUDM/humaneval-x
// You are given a list of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // // Examples: // MatchParens(['()(', ')']) == 'Yes' // MatchParens([')', ')']) == 'No' func MatchParens(lst []string) string {
check := func(s string) bool { val := 0 for _, i := range s { if i == '(' { val++ } else { val-- } if val < 0 { return false } } return val == 0 } S1 := lst[0] + lst[1] S2 := lst[1] + lst[0] if check(S1) || check(S2) { return "Yes" } return "No" }
go
THUDM/humaneval-x
import ( "sort" ) // Given an array arr of integers and a positive integer k, return a sorted list // of length k with the Maximum k numbers in arr. // // Example 1: // // Input: arr = [-3, -4, 5], k = 3 // Output: [-4, -3, 5] // // Example 2: // // Input: arr = [4, -4, 4], k = 2 // Output: [4, 4] // // Example 3: // // Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1 // Output: [2] // // Note: // 1. The length of the array will be in the range of [1, 1000]. // 2. The elements in the array will be in the range of [-1000, 1000]. // 3. 0 <= k <= len(arr) func Maximum(arr []int, k int) []int {
if k == 0 { return []int{} } sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] }) return arr[len(arr)-k:] }
go
THUDM/humaneval-x
// Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. // // Examples // Solution([5, 8, 7, 1]) ==> 12 // Solution([3, 3, 3, 3, 3]) ==> 9 // Solution([30, 13, 24, 321]) ==>0 func Solution(lst []int) int {
sum:=0 for i, x := range lst { if i&1==0&&x&1==1 { sum+=x } } return sum }
go
THUDM/humaneval-x
import ( "strconv" ) // Given a non-empty array of integers arr and an integer k, return // the sum of the elements with at most two digits from the first k elements of arr. // // Example: // // Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4 // Output: 24 # sum of 21 + 3 // // Constraints: // 1. 1 <= len(arr) <= 100 // 2. 1 <= k <= len(arr) func AddElements(arr []int, k int) int {
sum := 0 for _, elem := range arr[:k] { if len(strconv.Itoa(elem)) <= 2 { sum += elem } } return sum }
go
THUDM/humaneval-x
import ( "sort" ) // Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence. // // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // // Note: // 1. Collatz(1) is [1]. // 2. returned list sorted in increasing order. // // For example: // GetOddCollatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. func GetOddCollatz(n int) []int {
odd_collatz := make([]int, 0) if n&1==1 { odd_collatz = append(odd_collatz, n) } for n > 1 { if n &1==0 { n>>=1 } else { n = n*3 + 1 } if n&1 == 1 { odd_collatz = append(odd_collatz, n) } } sort.Slice(odd_collatz, func(i, j int) bool { return odd_collatz[i] < odd_collatz[j] }) return odd_collatz }
go
THUDM/humaneval-x
import ( "strconv" "strings" ) // You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // // for example: // ValidDate('03-11-2000') => true // // ValidDate('15-01-2012') => false // // ValidDate('04-0-2040') => false // // ValidDate('06-04-2020') => true // // ValidDate('06/04/2020') => false func ValidDate(date string) bool {
isInArray := func(arr []int, i int) bool { for _, x := range arr { if i == x { return true } } return false } date = strings.TrimSpace(date) split := strings.SplitN(date, "-", 3) if len(split) != 3 { return false } month, err := strconv.Atoi(split[0]) if err != nil { return false } day, err := strconv.Atoi(split[1]) if err != nil { return false } _, err = strconv.Atoi(split[2]) if err != nil { return false } if month < 1 || month > 12 { return false } if isInArray([]int{1,3,5,7,8,10,12}, month) && day < 1 || day > 31 { return false } if isInArray([]int{4,6,9,11}, month) && day < 1 || day > 30 { return false } if month == 2 && day < 1 || day > 29 { return false } return true }
go
THUDM/humaneval-x
import ( "strings" ) // Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // SplitWords("Hello world!") ➞ ["Hello", "world!"] // SplitWords("Hello,world!") ➞ ["Hello", "world!"] // SplitWords("abcdef") == 3 func SplitWords(txt string) interface{} {
if strings.Contains(txt, " ") { return strings.Fields(txt) } else if strings.Contains(txt, ",") { return strings.Split(txt, ",") } cnt := 0 for _, r := range txt { if 'a' <= r && r <= 'z' && (r-'a')&1==1 { cnt++ } } return cnt }
go
THUDM/humaneval-x
// Given a list of numbers, return whether or not they are sorted // in ascending order. If list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // // Examples // IsSorted([5]) ➞ true // IsSorted([1, 2, 3, 4, 5]) ➞ true // IsSorted([1, 3, 2, 4, 5]) ➞ false // IsSorted([1, 2, 3, 4, 5, 6]) ➞ true // IsSorted([1, 2, 3, 4, 5, 6, 7]) ➞ true // IsSorted([1, 3, 2, 4, 5, 6, 7]) ➞ false // IsSorted([1, 2, 2, 3, 3, 4]) ➞ true // IsSorted([1, 2, 2, 2, 3, 4]) ➞ false func IsSorted(lst []int) bool {
count_digit := make(map[int]int) for _, i := range lst { count_digit[i] = 0 } for _, i := range lst { count_digit[i]++ } for _, i := range lst { if count_digit[i] > 2 { return false } } for i := 1;i < len(lst);i++ { if lst[i-1] > lst[i] { return false } } return true }
go
THUDM/humaneval-x
// You are given two intervals, // where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). // The given intervals are closed which means that the interval (start, end) // includes both start and end. // For each given interval, it is assumed that its start is less or equal its end. // Your task is to determine whether the length of Intersection of these two // intervals is a prime number. // Example, the Intersection of the intervals (1, 3), (2, 4) is (2, 3) // which its length is 1, which not a prime number. // If the length of the Intersection is a prime number, return "YES", // otherwise, return "NO". // If the two intervals don't intersect, return "NO". // // // [input/output] samples: // Intersection((1, 2), (2, 3)) ==> "NO" // Intersection((-1, 1), (0, 4)) ==> "NO" // Intersection((-3, -1), (-5, 5)) ==> "YES" func Intersection(interval1 [2]int, interval2 [2]int) string {
is_prime := func(num int) bool { if num == 1 || num == 0 { return false } if num == 2 { return true } for i := 2;i < num;i++ { if num%i == 0 { return false } } return true } l := interval1[0] if interval2[0] > l { l = interval2[0] } r := interval1[1] if interval2[1] < r { r = interval2[1] } length := r - l if length > 0 && is_prime(length) { return "YES" } return "NO" }
go
THUDM/humaneval-x
import ( "math" ) // You are given an array arr of integers and you need to return // sum of magnitudes of integers multiplied by product of all signs // of each number in the array, represented by 1, -1 or 0. // Note: return nil for empty arr. // // Example: // >>> ProdSigns([1, 2, 2, -4]) == -9 // >>> ProdSigns([0, 1]) == 0 // >>> ProdSigns([]) == nil func ProdSigns(arr []int) interface{} {
if len(arr) == 0 { return nil } cnt := 0 sum := 0 for _, i := range arr { if i == 0 { return 0 } if i < 0 { cnt++ } sum += int(math.Abs(float64(i))) } prod := int(math.Pow(-1, float64(cnt))) return prod * sum }
go
THUDM/humaneval-x
// Given a grid with N rows and N columns (N >= 2) and a positive integer k, // each cell of the grid contains a value. Every integer in the range [1, N * N] // inclusive appears exactly once on the cells of the grid. // // You have to find the minimum path of length k in the grid. You can start // from any cell, and in each step you can move to any of the neighbor cells, // in other words, you can go to cells which share an edge with you current // cell. // Please note that a path of length k means visiting exactly k cells (not // necessarily distinct). // You CANNOT go off the grid. // A path A (of length k) is considered less than a path B (of length k) if // after making the ordered lists of the values on the cells that A and B go // through (let's call them lst_A and lst_B), lst_A is lexicographically less // than lst_B, in other words, there exist an integer index i (1 <= i <= k) // such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have // lst_A[j] = lst_B[j]. // It is guaranteed that the answer is unique. // Return an ordered list of the values on the cells that the minimum path go through. // // Examples: // // Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 // Output: [1, 2, 1] // // Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 // Output: [1] func Minpath(grid [][]int, k int) []int {
n := len(grid) val := n * n + 1 for i:= 0;i < n; i++ { for j := 0;j < n;j++ { if grid[i][j] == 1 { temp := make([]int, 0) if i != 0 { temp = append(temp, grid[i - 1][j]) } if j != 0 { temp = append(temp, grid[i][j - 1]) } if i != n - 1 { temp = append(temp, grid[i + 1][j]) } if j != n - 1 { temp = append(temp, grid[i][j + 1]) } for _, x := range temp { if x < val { val = x } } } } } ans := make([]int, 0, k) for i := 0;i < k;i++ { if i & 1 == 0 { ans = append(ans, 1) } else { ans = append(ans, val) } } return ans }
go
THUDM/humaneval-x
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in // the last couple centuries. However, what people don't know is Tribonacci sequence. // Tribonacci sequence is defined by the recurrence: // Tri(1) = 3 // Tri(n) = 1 + n / 2, if n is even. // Tri(n) = Tri(n - 1) + Tri(n - 2) + Tri(n + 1), if n is odd. // For example: // Tri(2) = 1 + (2 / 2) = 2 // Tri(4) = 3 // Tri(3) = Tri(2) + Tri(1) + Tri(4) // = 2 + 3 + 3 = 8 // You are given a non-negative integer number n, you have to a return a list of the // first n + 1 numbers of the Tribonacci sequence. // Examples: // Tri(3) = [1, 3, 2, 8] func Tri(n int) []float64 {
if n == 0 { return []float64{1} } my_tri := []float64{1, 3} for i := 2; i < n + 1; i++ { if i &1 == 0 { my_tri = append(my_tri, float64(i) / 2 + 1) } else { my_tri = append(my_tri, my_tri[i - 1] + my_tri[i - 2] + (float64(i) + 3) / 2) } } return my_tri }
go
THUDM/humaneval-x
import ( "strconv" ) // Given a positive integer n, return the product of the odd Digits. // Return 0 if all Digits are even. // For example: // Digits(1) == 1 // Digits(4) == 0 // Digits(235) == 15 func Digits(n int) int {
product := 1 odd_count := 0 for _, digit := range strconv.Itoa(n) { int_digit := int(digit-'0') if int_digit&1 == 1 { product= product*int_digit odd_count++ } } if odd_count==0 { return 0 } return product }
go
THUDM/humaneval-x
// Create a function that takes a string as input which contains only square brackets. // The function should return true if and only if there is a valid subsequence of brackets // where at least one bracket in the subsequence is nested. // // IsNested('[[]]') ➞ true // IsNested('[]]]]]]][[[[[]') ➞ false // IsNested('[][]') ➞ false // IsNested('[]') ➞ false // IsNested('[[][]]') ➞ true // IsNested('[[]][[') ➞ true func IsNested(s string) bool {
opening_bracket_index := make([]int, 0) closing_bracket_index := make([]int, 0) for i:=0;i < len(s);i++ { if s[i] == '[' { opening_bracket_index = append(opening_bracket_index, i) } else { closing_bracket_index = append(closing_bracket_index, i) } } for i := 0;i < len(closing_bracket_index)>>1;i++ { closing_bracket_index[i], closing_bracket_index[len(closing_bracket_index)-i-1] = closing_bracket_index[len(closing_bracket_index)-i-1], closing_bracket_index[i] } cnt := 0 i := 0 l := len(closing_bracket_index) for _, idx := range opening_bracket_index { if i < l && idx < closing_bracket_index[i] { cnt++ i++ } } return cnt >= 2 }
go
THUDM/humaneval-x
import ( "math" ) // You are given a list of numbers. // You need to return the sum of squared numbers in the given list, // round each element in the list to the upper int(Ceiling) first. // Examples: // For lst = [1,2,3] the output should be 14 // For lst = [1,4,9] the output should be 98 // For lst = [1,3,5,7] the output should be 84 // For lst = [1.4,4.2,0] the output should be 29 // For lst = [-2.4,1,1] the output should be 6 func SumSquares(lst []float64) int {
squared := 0 for _, i := range lst { squared += int(math.Pow(math.Ceil(i), 2)) } return squared }
go
THUDM/humaneval-x
import ( "strings" ) // Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // // Examples: // CheckIfLastCharIsALetter("apple pie") ➞ false // CheckIfLastCharIsALetter("apple pi e") ➞ true // CheckIfLastCharIsALetter("apple pi e ") ➞ false // CheckIfLastCharIsALetter("") ➞ false func CheckIfLastCharIsALetter(txt string) bool {
split := strings.Split(txt, " ") check := strings.ToLower(split[len(split)-1]) if len(check) == 1 && 'a' <= check[0] && check[0] <= 'z' { return true } return false }
go
THUDM/humaneval-x
// Create a function which returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array will not contain // duplicate values. // // Examples: // CanArrange([1,2,4,3,5]) = 3 // CanArrange([1,2,3]) = -1 func CanArrange(arr []int) int {
ind:=-1 i:=1 for i<len(arr) { if arr[i]<arr[i-1] { ind=i } i++ } return ind }
go
THUDM/humaneval-x
// Create a function that returns a tuple (a, b), where 'a' is // the largest of negative integers, and 'b' is the smallest // of positive integers in a list. // If there is no negative or positive integers, return them as nil. // // Examples: // LargestSmallestIntegers([2, 4, 1, 3, 5, 7]) == (nil, 1) // LargestSmallestIntegers([]) == (nil, nil) // LargestSmallestIntegers([0]) == (nil, nil) func LargestSmallestIntegers(lst []int) [2]interface{}{
smallest := make([]int, 0) largest := make([]int, 0) for _, x := range lst { if x < 0 { smallest = append(smallest, x) } else if x > 0 { largest = append(largest, x) } } var result [2]interface{} if len(smallest) == 0 { result[0] = nil } else { max := smallest[0] for i := 1;i < len(smallest);i++ { if smallest[i] > max { max = smallest[i] } } result[0] = max } if len(largest) == 0 { result[1] = nil } else { min := largest[0] for i := 1;i < len(largest);i++ { if largest[i] < min { min = largest[i] } } result[1] = min } return result }
go
THUDM/humaneval-x
import ( "fmt" "strconv" "strings" ) // Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return nil if the values are equal. // Note: If a real number is represented as a string, the floating point might be . or , // // CompareOne(1, 2.5) ➞ 2.5 // CompareOne(1, "2,3") ➞ "2,3" // CompareOne("5,1", "6") ➞ "6" // CompareOne("1", 1) ➞ nil func CompareOne(a, b interface{}) interface{} {
temp_a := fmt.Sprintf("%v", a) temp_b := fmt.Sprintf("%v", b) temp_a = strings.ReplaceAll(temp_a, ",", ".") temp_b = strings.ReplaceAll(temp_b, ",", ".") fa, _ := strconv.ParseFloat(temp_a, 64) fb, _ := strconv.ParseFloat(temp_b, 64) if fa == fb { return nil } if fa > fb { return a } else { return b } }
go
THUDM/humaneval-x
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // IsEqualToSumEven(4) == false // IsEqualToSumEven(6) == false // IsEqualToSumEven(8) == true func IsEqualToSumEven(n int) bool {
return n&1 == 0 && n >= 8 }
go
THUDM/humaneval-x
// The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // // For example: // >>> SpecialFactorial(4) // 288 // // The function will receive an integer as input and should return the special // factorial of this integer. func SpecialFactorial(n int) int {
fact_i := 1 special_fact := 1 for i := 1; i <= n; i++ { fact_i *= i special_fact *= fact_i } return special_fact }
go
THUDM/humaneval-x
// Given a string text, replace all spaces in it with underscores, // and if a string has more than 2 consecutive spaces, // then replace all consecutive spaces with - // // FixSpaces("Example") == "Example" // FixSpaces("Example 1") == "Example_1" // FixSpaces(" Example 2") == "_Example_2" // FixSpaces(" Example 3") == "_Example-3" func FixSpaces(text string) string {
new_text := make([]byte, 0) i := 0 start, end := 0, 0 for i < len(text) { if text[i] == ' ' { end++ } else { switch { case end - start > 2: new_text = append(new_text, '-') case end - start > 0: for n := 0;n < end-start;n++ { new_text = append(new_text, '_') } } new_text = append(new_text, text[i]) start, end = i+1, i+1 } i+=1 } if end - start > 2 { new_text = append(new_text, '-') } else if end - start > 0 { new_text = append(new_text, '_') } return string(new_text) }
go
THUDM/humaneval-x
import ( "strings" ) // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // FileNameCheck("example.txt") # => 'Yes' // FileNameCheck("1example.dll") # => 'No' (the name should start with a latin alphapet letter) func FileNameCheck(file_name string) string {
suf := []string{"txt", "exe", "dll"} lst := strings.Split(file_name, ".") isInArray := func (arr []string, x string) bool { for _, y := range arr { if x == y { return true } } return false } switch { case len(lst) != 2: return "No" case !isInArray(suf, lst[1]): return "No" case len(lst[0]) == 0: return "No" case 'a' > strings.ToLower(lst[0])[0] || strings.ToLower(lst[0])[0] > 'z': return "No" } t := 0 for _, c := range lst[0] { if '0' <= c && c <= '9' { t++ } } if t > 3 { return "No" } return "Yes" }
go
THUDM/humaneval-x
import ( "math" ) // This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // // Examples: // For lst = [1,2,3] the output should be 6 // For lst = [] the output should be 0 // For lst = [-1,-5,2,-1,-5] the output should be -126 func SumSquares(lst []int) int {
result := make([]int, 0) for i := 0;i < len(lst);i++ { switch { case i %3 == 0: result = append(result, int(math.Pow(float64(lst[i]), 2))) case i % 4 == 0 && i%3 != 0: result = append(result, int(math.Pow(float64(lst[i]), 3))) default: result = append(result, lst[i]) } } sum := 0 for _, x := range result { sum += x } return sum }
go
THUDM/humaneval-x
import ( "strings" ) // You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // // Example 1: // Input: sentence = "This is a test" // Output: "is" // // Example 2: // Input: sentence = "lets go for swimming" // Output: "go for" // // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters func WordsInSentence(sentence string) string {
new_lst := make([]string, 0) for _, word := range strings.Fields(sentence) { flg := 0 if len(word) == 1 { flg = 1 } for i := 2;i < len(word);i++ { if len(word)%i == 0 { flg = 1 } } if flg == 0 || len(word) == 2 { new_lst = append(new_lst, word) } } return strings.Join(new_lst, " ") }
go
THUDM/humaneval-x
import ( "strconv" "strings" ) // Your task is to implement a function that will Simplify the expression // x * n. The function returns true if x * n evaluates to a whole number and false // otherwise. Both x and n, are string representation of a fraction, and have the following format, // <numerator>/<denominator> where both numerator and denominator are positive whole numbers. // // You can assume that x, and n are valid fractions, and do not have zero as denominator. // // Simplify("1/5", "5/1") = true // Simplify("1/6", "2/1") = false // Simplify("7/10", "10/2") = false func Simplify(x, n string) bool {
xx := strings.Split(x, "/") nn := strings.Split(n, "/") a, _ := strconv.Atoi(xx[0]) b, _ := strconv.Atoi(xx[1]) c, _ := strconv.Atoi(nn[0]) d, _ := strconv.Atoi(nn[1]) numerator := float64(a*c) denom := float64(b*d) return numerator/denom == float64(int(numerator/denom)) }
go
THUDM/humaneval-x
import ( "sort" "strconv" ) // Write a function which sorts the given list of integers // in ascending order according to the sum of their digits. // Note: if there are several items with similar sum of their digits, // order them based on their index in original list. // // For example: // >>> OrderByPoints([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11] // >>> OrderByPoints([]) == [] func OrderByPoints(nums []int) []int {
digits_sum := func (n int) int { neg := 1 if n < 0 { n, neg = -1 * n, -1 } sum := 0 for i, c := range strconv.Itoa(n) { if i == 0 { sum += int(c-'0')*neg } else { sum += int(c-'0') } } return sum } sort.SliceStable(nums, func(i, j int) bool { return digits_sum(nums[i]) < digits_sum(nums[j]) }) return nums }
go
THUDM/humaneval-x
import ( "strconv" ) // Write a function that takes an array of numbers as input and returns // the number of elements in the array that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // Specialfilter([15, -73, 14, -15]) => 1 // Specialfilter([33, -2, -3, 45, 21, 109]) => 2 func Specialfilter(nums []int) int {
count := 0 for _, num := range nums { if num > 10 { number_as_string := strconv.Itoa(num) if number_as_string[0]&1==1 && number_as_string[len(number_as_string)-1]&1==1 { count++ } } } return count }
go
THUDM/humaneval-x
// You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≀ i ≀ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // // Example : // Input: n = 5 // Output: 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). func GetMaxTriples(n int) int {
A := make([]int, 0) for i := 1;i <= n;i++ { A = append(A, i*i-i+1) } ans := 0 for i := 0;i < n;i++ { for j := i + 1;j < n;j++ { for k := j + 1;k < n;k++ { if (A[i]+A[j]+A[k])%3 == 0 { ans++ } } } } return ans }
go
THUDM/humaneval-x
// There are eight planets in our solar system: the closerst to the Sun // is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, // Uranus, Neptune. // Write a function that takes two planet names as strings planet1 and planet2. // The function should return a tuple containing all planets whose orbits are // located between the orbit of planet1 and the orbit of planet2, sorted by // the proximity to the sun. // The function should return an empty tuple if planet1 or planet2 // are not correct planet names. // Examples // Bf("Jupiter", "Neptune") ==> ("Saturn", "Uranus") // Bf("Earth", "Mercury") ==> ("Venus") // Bf("Mercury", "Uranus") ==> ("Venus", "Earth", "Mars", "Jupiter", "Saturn") func Bf(planet1, planet2 string) []string {
planet_names := []string{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"} pos1 := -1 pos2 := -1 for i, x := range planet_names { if planet1 == x { pos1 = i } if planet2 == x { pos2 = i } } if pos1 == -1 || pos2 == -1 || pos1 == pos2 { return []string{} } if pos1 < pos2 { return planet_names[pos1 + 1: pos2] } return planet_names[pos2 + 1 : pos1] }
go
THUDM/humaneval-x
import ( "sort" ) // Write a function that accepts a list of strings as a parameter, // deletes the strings that have odd lengths from it, // and returns the resulted list with a sorted order, // The list is always a list of strings and never an array of numbers, // and it may contain duplicates. // The order of the list should be ascending by length of each word, and you // should return the list sorted by that rule. // If two words have the same length, sort the list alphabetically. // The function should return a list of strings in sorted order. // You may assume that all words will have the same length. // For example: // assert list_sort(["aa", "a", "aaa"]) => ["aa"] // assert list_sort(["ab", "a", "aaa", "cd"]) => ["ab", "cd"] func SortedListSum(lst []string) []string {
sort.SliceStable(lst, func(i, j int) bool { return lst[i] < lst[j] }) new_lst := make([]string, 0) for _, i := range lst { if len(i)&1==0 { new_lst = append(new_lst, i) } } sort.SliceStable(new_lst, func(i, j int) bool { return len(new_lst[i]) < len(new_lst[j]) }) return new_lst }
go
THUDM/humaneval-x
// A simple program which should return the value of x if n is // a prime number and should return the value of y otherwise. // // Examples: // for XOrY(7, 34, 12) == 34 // for XOrY(15, 8, 5) == 5 func XOrY(n, x, y int) int {
if n == 1 { return y } for i := 2;i < n;i++ { if n % i == 0 { return y } } return x }
go
THUDM/humaneval-x
import ( "math" ) // Given a list of numbers, return the sum of squares of the numbers // in the list that are odd. Ignore numbers that are negative or not integers. // // DoubleTheDifference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10 // DoubleTheDifference([-1, -2, 0]) == 0 // DoubleTheDifference([9, -2]) == 81 // DoubleTheDifference([0]) == 0 // // If the input list is empty, return 0. func DoubleTheDifference(lst []float64) int {
sum := 0 for _, i := range lst { if i > 0 && math.Mod(i, 2) != 0 && i == float64(int(i)) { sum += int(math.Pow(i, 2)) } } return sum }
go
THUDM/humaneval-x
import ( "math" ) // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two arrays of scores and guesses of equal length, where each index shows a match. // Return an array of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // // // example: // // Compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3] // Compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6] func Compare(game,guess []int) []int {
ans := make([]int, 0, len(game)) for i := range game { ans = append(ans, int(math.Abs(float64(game[i]-guess[i])))) } return ans }
go
THUDM/humaneval-x
import ( "math" ) // You will be given the name of a class (a string) and a list of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the list. // For example, if you are given "Slices" as the class and a list of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // for StrongestExtension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA' func StrongestExtension(class_name string, extensions []string) string {
strong := extensions[0] my_val := math.MinInt for _, s := range extensions { cnt0, cnt1 := 0, 0 for _, c := range s { switch { case 'A' <= c && c <= 'Z': cnt0++ case 'a' <= c && c <= 'z': cnt1++ } } val := cnt0-cnt1 if val > my_val { strong = s my_val = val } } return class_name + "." + strong }
go
THUDM/humaneval-x
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word // CycpatternCheck("abcd","abd") => false // CycpatternCheck("hello","ell") => true // CycpatternCheck("whassup","psus") => false // CycpatternCheck("abab","baa") => true // CycpatternCheck("efef","eeff") => false // CycpatternCheck("himenss","simen") => true func CycpatternCheck(a , b string) bool {
l := len(b) pat := b + b for i := 0;i < len(a) - l + 1; i++ { for j := 0;j<l + 1;j++ { if a[i:i+l] == pat[j:j+l] { return true } } } return false }
go
THUDM/humaneval-x
import ( "strconv" ) // Given an integer. return a tuple that has the number of even and odd digits respectively. // // Example: // EvenOddCount(-12) ==> (1, 1) // EvenOddCount(123) ==> (1, 2) func EvenOddCount(num int) [2]int {
even_count := 0 odd_count := 0 if num < 0 { num = -num } for _, r := range strconv.Itoa(num) { if r&1==0 { even_count++ } else { odd_count++ } } return [2]int{even_count, odd_count} }
go
THUDM/humaneval-x
import ( "strings" ) // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // // Examples: // >>> IntToMiniRoman(19) == 'xix' // >>> IntToMiniRoman(152) == 'clii' // >>> IntToMiniRoman(426) == 'cdxxvi' func IntToMiniRoman(number int) string {
num := []int{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000} sym := []string{"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"} i := 12 res := "" for number != 0 { div := number / num[i] number %= num[i] for div != 0 { res += sym[i] div-- } i-- } return strings.ToLower(res) }
go
THUDM/humaneval-x
// Given the lengths of the three sides of a triangle. Return true if the three // sides form a right-angled triangle, false otherwise. // A right-angled triangle is a triangle in which one angle is right angle or // 90 degree. // Example: // RightAngleTriangle(3, 4, 5) == true // RightAngleTriangle(1, 2, 3) == false func RightAngleTriangle(a, b, c int) bool {
return a*a == b*b + c*c || b*b == a*a + c*c || c*c == a*a + b*b }
go
THUDM/humaneval-x
import ( "sort" ) // Write a function that accepts a list of strings. // The list contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // // FindMax(["name", "of", "string"]) == "string" // FindMax(["name", "enam", "game"]) == "enam" // FindMax(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa" func FindMax(words []string) string {
key := func (word string) (int, string) { set := make(map[rune]struct{}) for _, r := range word { set[r] = struct{}{} } return -len(set), word } sort.SliceStable(words, func(i, j int) bool { ia, ib := key(words[i]) ja, jb := key(words[j]) if ia == ja { return ib < jb } return ia < ja }) return words[0] }
go
THUDM/humaneval-x
// You're a hungry rabbit, and you already have Eaten a certain number of carrots, // but now you need to Eat more carrots to complete the day's meals. // you should return an array of [ total number of Eaten carrots after your meals, // the number of carrots left after your meals ] // if there are not enough remaining carrots, you will Eat all remaining carrots, but will still be hungry. // // Example: // * Eat(5, 6, 10) -> [11, 4] // * Eat(4, 8, 9) -> [12, 1] // * Eat(1, 10, 10) -> [11, 0] // * Eat(2, 11, 5) -> [7, 0] // // Variables: // @number : integer // the number of carrots that you have Eaten. // @need : integer // the number of carrots that you need to Eat. // @remaining : integer // the number of remaining carrots thet exist in stock // // Constrain: // * 0 <= number <= 1000 // * 0 <= need <= 1000 // * 0 <= remaining <= 1000 // // Have fun :) func Eat(number, need, remaining int) []int {
if(need <= remaining) { return []int{ number + need , remaining-need } } return []int{ number + remaining , 0} }
go
THUDM/humaneval-x
import ( "math" ) // Given two lists operator, and operand. The first list has basic algebra operations, and // the second list is a list of integers. Use the two given lists to build the algebric // expression and return the evaluation of this expression. // // The basic algebra operations: // Addition ( + ) // Subtraction ( - ) // Multiplication ( * ) // Floor division ( // ) // Exponentiation ( ** ) // // Example: // operator['+', '*', '-'] // array = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // // Note: // The length of operator list is equal to the length of operand list minus one. // Operand is a list of of non-negative integers. // Operator list has at least one operator, and operand list has at least two operands. func DoAlgebra(operator []string, operand []int) int {
higher := func(a, b string) bool { if b == "*" || b == "//" || b == "**" { return false } if a == "*" || a == "//" || a == "**" { return true } return false } for len(operand) > 1 { pos := 0 sign := operator[0] for i, str := range operator { if higher(str, sign) { sign = str pos = i } } switch sign { case "+": operand[pos] += operand[pos+1] case "-": operand[pos] -= operand[pos+1] case "*": operand[pos] *= operand[pos+1] case "//": operand[pos] /= operand[pos+1] case "**": operand[pos] = int(math.Pow(float64(operand[pos]), float64(operand[pos+1]))) } operator = append(operator[:pos], operator[pos+1:]...) operand = append(operand[:pos+1], operand[pos+2:]...) } return operand [0] }
go
THUDM/humaneval-x
// You are given a string s. // if s[i] is a letter, reverse its case from lower to upper or vise versa, // otherwise keep it as it is. // If the string contains no letters, reverse the string. // The function should return the resulted string. // Examples // Solve("1234") = "4321" // Solve("ab") = "AB" // Solve("#a@C") = "#A@c" func Solve(s string) string {
flg := 0 new_str := []rune(s) for i, r := range new_str { if ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') { if 'a' <= r && r <= 'z' { new_str[i] = r - 'a' + 'A' } else { new_str[i] = r - 'A' + 'a' } flg = 1 } } if flg == 0 { for i := 0;i < len(new_str)>>1;i++ { new_str[i], new_str[len(new_str)-i-1] = new_str[len(new_str)-i-1], new_str[i] } } return string(new_str) }
go
THUDM/humaneval-x
import ( "crypto/md5" "fmt" ) // Given a string 'text', return its md5 hash equivalent string. // If 'text' is an empty string, return nil. // // >>> StringToMd5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62' func StringToMd5(text string) interface{} {
if text == "" { return nil } return fmt.Sprintf("%x", md5.Sum([]byte(text))) }
go
THUDM/humaneval-x
// Given two positive integers a and b, return the even digits between a // and b, in ascending order. // // For example: // GenerateIntegers(2, 8) => [2, 4, 6, 8] // GenerateIntegers(8, 2) => [2, 4, 6, 8] // GenerateIntegers(10, 14) => [] func GenerateIntegers(a, b int) []int {
min := func (a, b int) int { if a > b { return b } return a } max := func (a, b int) int { if a > b { return a } return b } lower := max(2, min(a, b)) upper := min(8, max(a, b)) ans := make([]int, 0) for i := lower;i <= upper;i++ { if i&1==0 { ans = append(ans, i) } } return ans }
go
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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); } }
java
THUDM/humaneval-x
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); } } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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()); } }
java
THUDM/humaneval-x
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(); } }
java
THUDM/humaneval-x
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); } }
java
THUDM/humaneval-x
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()); } }
java
THUDM/humaneval-x
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()); } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
import java.util.*; import java.lang.*; class Solution { /** This function takes a list l and returns a list l' such that l' is identical to l in the 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; } }
java
THUDM/humaneval-x
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; } }
java
THUDM/humaneval-x
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); } }
java
THUDM/humaneval-x