├── .gitignore ├── 2D └── main.go ├── 2D_Make └── main.go ├── 4_by_4_skyscrappers ├── 4_by_4_skyscrappers.go ├── Screenshot 2020-09-12 at 22.57.13.png └── Screenshot 2020-09-12 at 22.57.32.png ├── IP_Validation ├── ip_validation.go └── ip_validation_test.go ├── Isograms ├── isograms.go └── isograms_test.go ├── abs_value_sort └── main.go ├── all_unique ├── all_unique.go └── all_unique_test.go ├── alphabet_symmetry ├── alphabet_assymetry_test.go └── alphabet_symmetry.go ├── ans └── ans.go ├── arrays ├── remove_duplicate.go ├── remove_duplicate_test.go ├── reverse_array.go ├── reverse_array_test.go ├── smallest_largest_number.go └── smallest_largest_number_test.go ├── baseE91 ├── baseE91.go └── baseE91_test.go ├── best_travel └── main.go ├── binary_search ├── binary_search.go └── binary_search_test.go ├── bit_counting ├── bit_counting.go └── bit_counting_test.go ├── bookseller └── main.go ├── breaking_chocolate ├── breaking_chocolate.go └── breaking_chocolate_test.go ├── bubble_sort └── main.go ├── buddy_pairs └── main.go ├── caeser_cipher ├── caeser_cipher.go └── caeser_cipher_test.go ├── caeser_cipher_2 └── caeser_cipher_2.go ├── ceaser_cipher_variation └── main.go ├── cipher └── main.go ├── clockwise_spiral └── main.go ├── closest_and_smallest ├── closest_and_smallest.go └── closest_and_smallest_test.go ├── codility-go ├── arrays │ ├── cyclicRotation │ │ ├── cyclicRotation.go │ │ └── cyclicRotation_test.go │ └── oddOccurrence │ │ ├── oddOccurrenceInArray_test.go │ │ └── oddOccurrencesInArray.go ├── binary-search │ └── NailingPlanks.go └── complexity │ ├── fromjmp │ ├── fromjmp.go │ └── fromjmp_test.go │ ├── permMissingElem │ ├── permMissingElem.go │ └── permMissingElem_test.go │ └── tapeEquilibrium │ └── tapeEquilibrium.go ├── collection └── main.go ├── common_den └── main.go ├── complex_struct └── main.go ├── compress_characters └── run-length-encoding │ ├── example_1 │ ├── example_1.go │ └── example_1_test.go │ ├── example_2 │ ├── example_2.go │ └── example_2_test.go │ └── example_3 │ ├── example_3.go │ └── example_3_test.go ├── consecutive_prime └── main.go ├── consecutive_string ├── consecutive_string.go └── consecutive_string_test.go ├── consecutive_strings └── main.go ├── consonant_value ├── consonant_value.go └── consonant_value_test.go ├── context └── main.go ├── copy └── main.go ├── count_divisors ├── count_divisors.go └── count_divisors_test.go ├── count_string └── main.go ├── datastructures ├── linkedlists │ └── singlylinkedlists │ │ ├── singly_linked_lists.go │ │ └── singly_linked_lists_test.go ├── sets │ └── hashsets │ │ └── hash_set.go └── trees │ └── trees.go ├── deadfish_swim ├── deadfish_swim.go └── deadfish_swim_test.go ├── decimal_to_factorial ├── decimal_to_factorial.go └── decimal_to_factorial_test.go ├── deodorant_evaporator ├── deodorant_evaporator.go └── deodorant_evaporator_test.go ├── digit_symmetry ├── digit_symmetry.go └── digit_symmetry_test.go ├── digits ├── six_digit │ └── six_digit.go └── weird_digit │ └── weird_digit.go ├── diophantine └── main.go ├── duplicate └── main.go ├── encrypt_this ├── encrypt_this.go └── encrypt_this_test.go ├── euler_method └── main.go ├── euler_method_first_ode └── main.go ├── exp └── main.go ├── factorial └── main.go ├── factorial_decomposition ├── factorial_decomposition.go └── factorial_decomposition_test.go ├── fib_optimized └── fib_optimized.go ├── fibonacci └── main.go ├── first_non_repeating └── main.go ├── first_variation_caeser_cipher └── main.go ├── fix_string_case ├── fix_string_case.go └── fix_string_case_test.go ├── fizzbuzz └── main.go ├── flag └── main.go ├── friend_cheating ├── friend_cheating.go └── friend_cheating_test.go ├── fusc └── main.go ├── gap_in_primes ├── gap_in_primes.go └── gap_in_primes_test.go ├── generate_string └── generate_string.go ├── go.mod ├── go.sum ├── go_max_procs └── main.go ├── going_to_the_cinema ├── going_to_the_cinema.go └── going_to_the_cinema_test.go ├── growing_plant ├── growing_plant.go └── growing_plant_test.go ├── hackerrank └── main.go ├── heap_example └── main.go ├── help_your_granny ├── Screenshot 2020-09-12 at 19.44.37.png ├── help_your_granny.go └── help_your_granny_test.go ├── howmuch └── main.go ├── http_server └── main.go ├── init └── main.go ├── interface_checking └── main.go ├── internals └── main.go ├── interview_questions └── main.go ├── iq_test └── main.go ├── isPrime └── main.go ├── isbn_10_validation ├── isbn_10_validation.go └── isbn_10_validation_test.go ├── josephus └── main.go ├── json_unmarshaling └── main.go ├── leetcode_problems ├── add_two_numbers │ └── add_two_numbers.go ├── longest_common_prefix │ ├── longest_common_prefix.go │ └── longest_common_prefix_test.go ├── longest_substring │ ├── longest_substring.go │ └── longest_substring_test.go ├── longest_substring_without_repeatition │ ├── longest_substring_without_repeatition.go │ └── longest_substring_without_repeatition_test.go ├── palindrome_number │ ├── palindrome_number.go │ └── palindrome_number_test.go ├── reverse_integer │ ├── reverse_integer.go │ └── reverse_integer_test.go ├── two_sum │ ├── two_sum.go │ └── two_sum_test.go └── valid_parentheses │ ├── valid_parentheses.go │ └── valid_parentheses_test.go ├── lowercase └── main.go ├── machine_learning └── machine_learning.go ├── matching └── main.go ├── max_length_diff └── main.go ├── max_number └── main.go ├── max_subarray └── main.go ├── mean └── main.go ├── mexican_wave ├── mexican_wave.go └── mexican_wave_test.go ├── min_max_words └── main.go ├── minimum_radius └── minimum_radius.go ├── morse └── main.go ├── morse_code └── morse_code.go ├── moves_in_square_strings └── moves_in_square_strings.go ├── mutexes └── main.go ├── next_big_number └── main.go ├── normal_http_call ├── main.go └── main_test.go ├── not_very_secure └── main.go ├── number_of_integer_partition ├── number_of_integer_partition.go └── number_of_integer_partition_test.go ├── numbers_in_order ├── numbers_in_order.go └── numbers_in_order_test.go ├── odd_int ├── odd_int.go └── odd_int_test.go ├── ordered_count_characters ├── ordered_count_characters.go └── ordered_count_characters_test.go ├── outlier └── main.go ├── palindrome ├── example_1 │ └── example_1.go ├── palindromesentences │ ├── palindrome_sentences.go │ └── palindrome_sentences_test.go └── palindromestrings │ ├── palindromestrings.go │ └── palindromestrings_test.go ├── paperfold_sequence ├── paperfold_sequence.go └── paperfold_sequence_test.go ├── parts_of_a_list ├── part_a_list_test.go └── parts_of_a_list.go ├── pascals_triangle └── main.go ├── passphrases ├── passphrases.go └── passphrases_test.go ├── passwords └── main.go ├── permutable_palindrome ├── permutable_palindrome.go └── permutable_palindrome_test.go ├── phone_directory └── main.go ├── phone_number ├── phone_number.go └── phone_number_test.go ├── pick_peaks └── main.go ├── pile_of_cube ├── pile_of_cube.go └── pile_of_cube_test.go ├── polymorphism └── main.go ├── power_of_3 ├── power_of_3.go └── power_of_3_test.go ├── prime_number_generator └── main.go ├── primes_in_numbers ├── primes_in_numbers.go └── primes_in_numbers_test.go ├── printer_error └── main.go ├── product_of_fib ├── product_of_fib.go └── product_of_fib_test.go ├── qualified ├── main.go └── main_2.go ├── quick_practice └── main.go ├── rand └── rand.go ├── random_questions └── main.go ├── range_extraction └── main.go ├── rectangle_into_rectangles ├── figure_1.png ├── figure_2.png ├── rectangle_into_rectangles.go └── rectangle_into_rectangles_test.go ├── rectangle_rotation └── main.go ├── regexp └── main.go ├── retate_cipher └── main.go ├── reverses ├── reversesentences │ ├── reverse_sentence_test.go │ └── reverse_sentences.go └── reversestring │ ├── reversestring.go │ └── reversestring_test.go ├── roman_decoder └── main.go ├── rotate_for_max ├── rotate_for_max.go └── rotate_for_max_test.go ├── same_array_squared ├── same_array_squared.go └── same_array_squared_test.go ├── shortest_word └── main.go ├── simple_string_indices ├── simple_string_indices.go └── simple_string_indices_test.go ├── smallest_number └── main.go ├── smallest_positive_integer ├── smallest_integer.go └── smallest_integer_test.go ├── smallest_possible_sum ├── smallest_possible_sum.go └── smallest_possible_sum_test.go ├── snail_sort └── main.go ├── snakes_and_ladders ├── Screenshot 2020-10-13 at 17.56.50.png ├── snakes_and_ladders.go └── snakes_and_ladders_test.go ├── sort └── main.go ├── sort_slice └── main.go ├── split_string_distinct ├── split_string_distinct.go └── split_string_distinct_test.go ├── string_builder └── main.go ├── string_ending └── main.go ├── string_mix └── main.go ├── string_revert └── main.go ├── string_to_int ├── string_to_int.go └── string_to_int_test.go ├── strings ├── reverse_string.go ├── reverse_string_test.go ├── vowel_count.go └── vowel_count_test.go ├── struct_to_json └── main.go ├── subsequence └── main.go ├── subsequence_product_sum ├── subsequence_product_sum.go └── subsequence_product_sum_test.go ├── sudoku └── main.go ├── sum_by_factor └── main.go ├── temp ├── fibonacci.go ├── fibonacci_test.go ├── fizzbuzz.go ├── fizzbuzz_test.go ├── palindrome.go ├── palindrome_test.go ├── prime_factor.go └── prime_factor_test.go ├── tortoise_racing └── tortoise_racing.go ├── trees └── inverttrees │ └── invertbinarytrees │ ├── invert_binary_trees.go │ └── invert_binary_trees_test.go ├── tribonacci └── main.go ├── turing └── main.go ├── turing2 └── main.go ├── twice_linear ├── twice_linear.go └── twice_linear_test.go ├── two_oldest_ages └── main.go ├── two_sum ├── two_sum.go └── two_sum_test.go ├── two_to_one ├── two_to_one.go └── two_to_one_test.go ├── ulam_sequence └── ulam_sequence.go ├── upside_down ├── upside_down.go └── upside_down_test.go ├── upside_down_2 ├── upside_down_2.go └── upside_down_2_test.go ├── utf8_length └── main.go ├── valid_braces ├── valid_braces.go └── valid_braces_test.go ├── valid_parentheses ├── valid_parentheses.go └── valid_parentheses_test.go ├── variadic_sum ├── variadic_sum.go └── variadic_sum_test.go ├── vasya_clerk ├── vasya_clerk.go └── vasya_clerk_test.go ├── vowel_count ├── vowel_count.go └── vowel_count_test.go ├── vowels └── main.go ├── wait_group └── main.go ├── weird_prime_generator └── main.go ├── word_values ├── word_values.go └── word_values_test.go ├── wordbreakers └── work_breaker.go └── words_to_marks ├── words_to_marks.go └── words_to_marks_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /2D_Make/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(grider(10)) 7 | } 8 | 9 | func grider(rows int) [][]int { 10 | grid := make([][]int, rows) 11 | for i := 0; i < rows; i++ { 12 | grid[i] = make([]int, 4) //each row have 4 columns 13 | } 14 | return grid 15 | } 16 | -------------------------------------------------------------------------------- /4_by_4_skyscrappers/Screenshot 2020-09-12 at 22.57.13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/4_by_4_skyscrappers/Screenshot 2020-09-12 at 22.57.13.png -------------------------------------------------------------------------------- /4_by_4_skyscrappers/Screenshot 2020-09-12 at 22.57.32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/4_by_4_skyscrappers/Screenshot 2020-09-12 at 22.57.32.png -------------------------------------------------------------------------------- /IP_Validation/ip_validation.go: -------------------------------------------------------------------------------- 1 | package IP_Validation 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive. 11 | // 12 | //Input to the function is guaranteed to be a single string. 13 | // 14 | //Examples 15 | //Valid inputs: 16 | // 17 | //1.2.3.4 18 | //123.45.67.89 19 | //Invalid inputs: 20 | // 21 | //1.2.3 22 | //1.2.3.4.5 23 | //123.456.78.90 24 | //123.045.067.089 25 | //Note that leading zeros (e.g. 01.02.03.04) are considered invalid. 26 | 27 | func split(value string, separator string) []string { 28 | 29 | var parts []string 30 | last := 0 31 | 32 | for i, v := range value { 33 | if string(v) == separator { 34 | parts = append(parts, value[last:i]) 35 | last = i + 1 36 | } 37 | } 38 | parts = append(parts, value[last:]) 39 | 40 | fmt.Println("the parts returned: ", parts) 41 | 42 | return parts 43 | } 44 | 45 | func Is_valid_ip(ip string) bool { 46 | 47 | //parts := split(ip, ".") 48 | //if len(parts) != 4 { 49 | // return false 50 | //} 51 | 52 | //could simply use split string: 53 | parts := strings.Split(ip, ".") 54 | if len(parts) != 4 { 55 | return false 56 | } 57 | 58 | for _, value := range parts { 59 | if value[0] == '0' && len(value) > 1 { 60 | return false 61 | } 62 | 63 | num, err := strconv.Atoi(value) 64 | if err != nil { 65 | return false 66 | } 67 | 68 | if num > 255 || num < 0 { 69 | return false 70 | } 71 | } 72 | 73 | return true 74 | } 75 | 76 | func Is_valid_ip2(ip string) bool { 77 | var ip_struct [4]uint8 78 | if _, err := fmt.Sscanf(ip, "%d.%d.%d.%d", &ip_struct[0], &ip_struct[1], &ip_struct[2], &ip_struct[3]); err != nil { 79 | return false 80 | } 81 | 82 | return fmt.Sprintf("%d.%d.%d.%d", ip_struct[0], ip_struct[1], ip_struct[2], ip_struct[3]) == ip 83 | } 84 | -------------------------------------------------------------------------------- /IP_Validation/ip_validation_test.go: -------------------------------------------------------------------------------- 1 | package IP_Validation 2 | 3 | import ( 4 | "fmt" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestValidIP(t *testing.T) { 10 | 11 | fixtures := []struct { 12 | IP string 13 | IsValid bool 14 | }{ 15 | { 16 | "1.2.3.4", 17 | true, 18 | }, 19 | { 20 | "123.45.67.89", 21 | true, 22 | }, 23 | { 24 | "1.2.3", 25 | false, 26 | }, 27 | { 28 | "1.2.3.4.5", 29 | false, 30 | }, 31 | { 32 | "123.456.78.90", 33 | false, 34 | }, 35 | { 36 | "123.045.067.089", 37 | false, 38 | }, 39 | } 40 | 41 | for _, v := range fixtures { 42 | 43 | t.Run(fmt.Sprintf("%s test", v.IP), func(t *testing.T) { 44 | isValid := Is_valid_ip2(v.IP) 45 | assert.Equal(t, v.IsValid, isValid) 46 | }) 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Isograms/isograms.go: -------------------------------------------------------------------------------- 1 | package Isograms 2 | 3 | import "strings" 4 | 5 | //An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. 6 | // 7 | //isIsogram "Dermatoglyphics" == true 8 | //isIsogram "aba" == false 9 | //isIsogram "moOse" == false -- ignore letter case 10 | 11 | func Isogram(str string) bool { 12 | 13 | if len(str) == 0 { 14 | return true 15 | } 16 | 17 | hashMap := make(map[rune]bool) 18 | 19 | for _, v := range strings.ToLower(str) { 20 | if ok := hashMap[v]; ok { 21 | return false 22 | } 23 | //insert 24 | hashMap[v] = true 25 | } 26 | 27 | return true 28 | } 29 | -------------------------------------------------------------------------------- /Isograms/isograms_test.go: -------------------------------------------------------------------------------- 1 | package Isograms 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestIsogram(t *testing.T) { 9 | 10 | assert.Equal(t, Isogram("Dermatoglyphics"), true) 11 | assert.Equal(t, Isogram("aba"), false) 12 | assert.Equal(t, Isogram("moOse"), false) 13 | assert.Equal(t, Isogram("isogram"), true) 14 | assert.Equal(t, Isogram("moose"), false) 15 | assert.Equal(t, Isogram("isIsogram"), false) 16 | assert.Equal(t, Isogram("thumbscrewjapingly"), true) 17 | assert.Equal(t, Isogram(""), true) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /abs_value_sort/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | A := []int{2, -7, -2, -2, 0} 10 | fmt.Println(absSort(A)) 11 | } 12 | 13 | func absSort(arr []int) []int { 14 | for i := len(arr) - 1; i >= 0; i-- { 15 | for j := 1; j <= i; j++ { 16 | if math.Abs(float64(arr[j-1])) > math.Abs(float64(arr[j])) { 17 | temp := arr[j-1] 18 | arr[j-1] = arr[j] 19 | arr[j] = temp 20 | } 21 | if math.Abs(float64(arr[j-1])) == math.Abs(float64(arr[j])) && arr[j-1] > 0 { 22 | temp := arr[j-1] 23 | arr[j-1] = arr[j] 24 | arr[j] = temp 25 | } 26 | } 27 | } 28 | return arr 29 | } 30 | -------------------------------------------------------------------------------- /all_unique/all_unique.go: -------------------------------------------------------------------------------- 1 | package all_unique 2 | 3 | import "strings" 4 | 5 | // Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise. 6 | // 7 | //The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. 'a' and 'A' are considered different characters. 8 | 9 | func HasUniqueChar(s string) bool { 10 | 11 | hash := make(map[string]int) 12 | for _, v := range s { 13 | hash[string(v)]++ 14 | } 15 | 16 | for _, v := range hash { 17 | if v > 1 { 18 | return false 19 | } 20 | } 21 | return true 22 | } 23 | 24 | func HashUniqueChar2(str string) bool { 25 | seen := make(map[rune]bool) 26 | for _, c := range str { 27 | if seen[c] { 28 | return false 29 | } 30 | seen[c] = true 31 | } 32 | return true 33 | } 34 | 35 | func HashUniqueChar3(str string) bool { 36 | for _, letter := range str { 37 | if strings.Count(str, string(letter)) > 1 { 38 | return false 39 | } 40 | } 41 | return true 42 | } 43 | -------------------------------------------------------------------------------- /all_unique/all_unique_test.go: -------------------------------------------------------------------------------- 1 | package all_unique 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestHasUniqueChar(t *testing.T) { 9 | 10 | assert.Equal(t, false, HasUniqueChar("abasddwq")) 11 | 12 | assert.Equal(t, true, HashUniqueChar2("abcdef")) 13 | 14 | assert.Equal(t, false, HashUniqueChar3("wweede")) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /alphabet_symmetry/alphabet_assymetry_test.go: -------------------------------------------------------------------------------- 1 | package alphabet_symmetry_test 2 | 3 | import ( 4 | "efficient-algorithms/alphabet_symmetry" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolve(t *testing.T) { 10 | 11 | assert.Equal(t, alphabet_symmetry.Solve2([]string{"abcde", "gBa"}), []int{5, 1}) 12 | } 13 | -------------------------------------------------------------------------------- /alphabet_symmetry/alphabet_symmetry.go: -------------------------------------------------------------------------------- 1 | package alphabet_symmetry 2 | 3 | import ( 4 | "strings" 5 | "unicode" 6 | ) 7 | 8 | //Consider the word "abode". We can see that the letter a is in position 1 and b is in position 2. In the alphabet, a and b are also in positions 1 and 2. Notice also that d and e in abode occupy the positions they would occupy in the alphabet, which are positions 4 and 5. 9 | // 10 | //Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example, 11 | // 12 | //solve(["abode","ABc","xyzD"]) = [4, 3, 1] 13 | //See test cases for more examples. 14 | // 15 | //Input will consist of alphabet characters, both uppercase and lowercase. No spaces. 16 | // 17 | //Good luck! 18 | // 19 | //If you like this Kata, please try: 20 | 21 | func Solve(slice []string) (result []int) { 22 | 23 | for _, str := range slice { 24 | count := 0 25 | for i, ch := range strings.ToLower(str) { 26 | if int(ch-'a') == i { 27 | count++ 28 | } 29 | } 30 | result = append(result, count) 31 | } 32 | return 33 | } 34 | 35 | func Solve2(slice []string) []int { 36 | 37 | alphabet := "abcdefghijklmnopqrstuvwxyz" 38 | 39 | results := make([]int, len(slice)) 40 | //loop string 41 | for index, str := range slice { 42 | //loop character 43 | for charIndex, char := range str { 44 | if unicode.ToLower(char) == rune(alphabet[charIndex]) { 45 | results[index]++ 46 | } 47 | } 48 | } 49 | return results 50 | } 51 | -------------------------------------------------------------------------------- /ans/ans.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "… 9 | 10 | func main() { 11 | 12 | result := solution("#####ab", "ab") 13 | 14 | fmt.Println(result) 15 | } 16 | 17 | func filterString(s string) string { 18 | 19 | str := []string{} 20 | 21 | for i, v := range s { 22 | if v == '#' { 23 | if len(str) > 0 { 24 | str = str[:i] 25 | } 26 | } else { 27 | str = append(str, string(v)) 28 | } 29 | } 30 | 31 | return strings.Join(str, "") 32 | } 33 | 34 | func solution(S, T string) bool { 35 | if filterString(S) != filterString(T) { 36 | return false 37 | } 38 | return true 39 | } 40 | -------------------------------------------------------------------------------- /arrays/remove_duplicate.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | func remove_duplicate(n []int) []int { 4 | var hashMap = make(map[int]bool) 5 | var newArray = make([]int, 0) 6 | for _, v := range n { 7 | if _, ok := hashMap[v]; !ok { 8 | hashMap[v] = true 9 | newArray = append(newArray, v) 10 | } 11 | } 12 | return newArray 13 | } 14 | -------------------------------------------------------------------------------- /arrays/remove_duplicate_test.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestRemoveDuplicate(t *testing.T) { 9 | arr := []int{1,2,2,4,5,5,2,6,6,5} 10 | expected := []int{1,2,4,5,6} 11 | result := remove_duplicate(arr) 12 | 13 | assert.Equal(t, expected, result) 14 | } 15 | -------------------------------------------------------------------------------- /arrays/reverse_array.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | func reverse_array(arr []int) []int { 4 | n := len(arr) 5 | for i := 0; i < n/2; i++ { 6 | arr[i], arr[n-1-i] = arr[n-1-i], arr[i] 7 | } 8 | return arr 9 | } -------------------------------------------------------------------------------- /arrays/reverse_array_test.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestReverseArray(t *testing.T) { 9 | arr := []int{1,2,3,4,5,6} 10 | result := reverse_array(arr) 11 | assert.Equal(t, result, []int{6,5,4,3,2,1}) 12 | } -------------------------------------------------------------------------------- /arrays/smallest_largest_number.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | func smallest_number(n []int) int { 4 | smallest := n[0] 5 | for _, v := range n { 6 | if v < smallest { 7 | smallest = v 8 | } 9 | } 10 | return smallest 11 | } 12 | 13 | func largest_number(n []int) int { 14 | largest := n[0] 15 | for _, v := range n { 16 | if v > largest { 17 | largest = v 18 | } 19 | } 20 | return largest 21 | } 22 | -------------------------------------------------------------------------------- /arrays/smallest_largest_number_test.go: -------------------------------------------------------------------------------- 1 | package arrays 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSmallestNumber(t *testing.T) { 9 | assert.Equal(t, 5, smallest_number([]int{6,7,5,8,9,10,13,100})) 10 | } 11 | 12 | func TestLargestNumber(t *testing.T) { 13 | assert.Equal(t, 100, largest_number([]int{6,7,5,8,9,10,13,100})) 14 | } 15 | -------------------------------------------------------------------------------- /baseE91/baseE91_test.go: -------------------------------------------------------------------------------- 1 | package baseE91 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestDecode(t *testing.T) { 9 | 10 | } 11 | 12 | func TestEncode(t *testing.T) { 13 | 14 | assert.Equal(t, Encode([]byte("test")), []byte("fPNKd")) 15 | } 16 | -------------------------------------------------------------------------------- /best_travel/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | var ls = []int{50, 55, 57, 58, 60} 10 | var k = 3 11 | var t = 174 12 | 13 | fmt.Println(ChooseBestSum(t, k, ls)) 14 | } 15 | 16 | //func ChooseBestSum(t, k int, ls []int) int { 17 | // if len(ls) < k { 18 | // return -1 19 | // } 20 | // tripCounter := 0 21 | //// sorting the array: 22 | // totalDistance := 0 23 | // sort.Ints(ls) 24 | // 25 | // sort.Slice(ls, func(i, j int) bool { 26 | // return ls[i] > ls[j] 27 | // }) 28 | // for _, v := range ls { 29 | // if v < t && (v + totalDistance) < t && tripCounter <= k { 30 | // tripCounter++ 31 | // totalDistance += v 32 | // } 33 | // } 34 | // return totalDistance 35 | //} 36 | 37 | func ChooseBestSum(t, k int, ls []int) int { 38 | outerbest := -1 39 | for i, d := range ls { 40 | //not enough remaining values for this d to work 41 | if len(ls) < k { 42 | continue 43 | } 44 | //recursively choose best from t-d, until final level k = 1 45 | if k > 1 { 46 | innerbest := ChooseBestSum(t-d, k-1, ls[i+1:]) 47 | //if no best available at lower level, this d cant work 48 | if innerbest < 0 { 49 | continue 50 | } 51 | d += innerbest 52 | } 53 | if d <= t && d > outerbest { 54 | outerbest = d 55 | } 56 | } 57 | return outerbest 58 | } 59 | 60 | var buffer [][]int 61 | 62 | func ChosseBestSum2(t, k int, ls []int) int { 63 | buffer = buffer[0:0] 64 | data := make([]int, k) 65 | n := len(ls) 66 | sort.Ints(ls) 67 | combinations(ls, data, 0, n-1, 0, k) 68 | max := -1 69 | sum := 0 70 | for _, value := range buffer { 71 | for _, v := range value { 72 | sum += v 73 | } 74 | if sum <= t && max < sum { 75 | max = sum 76 | } 77 | sum = 0 78 | } 79 | return max 80 | } 81 | 82 | func combinations(arr, data []int, start, end, index, r int) { 83 | if index == r { 84 | var i = make([]int, 0) 85 | i = append(i, data...) 86 | buffer = append(buffer, i) 87 | return 88 | } 89 | for i := start; i <= end && end-i+1 >= r-index; i++ { 90 | data[index] = arr[i] 91 | combinations(arr, data, i+1, end, index+1, r) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /binary_search/binary_search.go: -------------------------------------------------------------------------------- 1 | package binary_search 2 | -------------------------------------------------------------------------------- /binary_search/binary_search_test.go: -------------------------------------------------------------------------------- 1 | package binary_search 2 | -------------------------------------------------------------------------------- /bit_counting/bit_counting.go: -------------------------------------------------------------------------------- 1 | package bit_counting 2 | 3 | import "math/bits" 4 | 5 | //Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. 6 | // 7 | //Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case 8 | 9 | func CountBits(n uint) int { 10 | return bits.OnesCount(n) 11 | } 12 | 13 | //func CountBits(n uint) int { 14 | // var res int = 0 15 | // for (n>0) { 16 | // if (n & 1 == 1) { 17 | // res = res + 1 18 | // } 19 | // n = n >> 1 20 | // } 21 | // return res 22 | //} 23 | -------------------------------------------------------------------------------- /bit_counting/bit_counting_test.go: -------------------------------------------------------------------------------- 1 | package bit_counting_test 2 | 3 | import ( 4 | "efficient-algorithms/bit_counting" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestCountBits(t *testing.T) { 10 | 11 | assert.Equal(t, bit_counting.CountBits(1234), 5) 12 | } 13 | -------------------------------------------------------------------------------- /bookseller/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | ) 8 | 9 | func main() { 10 | var b = []string{"BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600"} 11 | var c = []string{"A", "B", "C", "D"} 12 | fmt.Println(StockList(b, c)) 13 | } 14 | 15 | func StockList(listArt []string, listCat []string) string { 16 | if len(listArt) == 0 || len(listCat) == 0 { 17 | return "" 18 | } 19 | result := "" 20 | for _, v := range listCat { 21 | tot := 0 22 | for _, w := range listArt { 23 | //check the first character for the listCat and the listArt slices, 24 | //w[0] fetches the first character ASCII value, same with v[0], 25 | //so if listCat = []string{"A", "B", "C", "D"}, then, v[0] = 65, which corresponds to A 26 | //if we have listArt = []string{"BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600"}, then w[0]= 66, which corresponds to B 27 | //so the comparison goes like this: if 65 == 66 (depending on the iteration) 28 | if w[0] == v[0] { 29 | ans, _ := strconv.Atoi(strings.Split(w, " ")[1]) 30 | tot += ans 31 | } 32 | } 33 | if result != "" { 34 | result += " - " 35 | } 36 | result += "(" + v + " : " + strconv.Itoa(tot) + ")" 37 | } 38 | return result 39 | } 40 | -------------------------------------------------------------------------------- /breaking_chocolate/breaking_chocolate.go: -------------------------------------------------------------------------------- 1 | package breaking_chocolate 2 | 3 | //Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return minimum number of breaks needed. 4 | // 5 | //For example if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks. 6 | // 7 | //If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer. 8 | 9 | func BreakChocolate(n, m int) int { 10 | if n < 1 || m < 1 { 11 | return 0 12 | } 13 | 14 | return (n * m) - 1 15 | } 16 | -------------------------------------------------------------------------------- /breaking_chocolate/breaking_chocolate_test.go: -------------------------------------------------------------------------------- 1 | package breaking_chocolate_test 2 | 3 | import ( 4 | "efficient-algorithms/breaking_chocolate" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestBreakChocolate(t *testing.T) { 10 | 11 | assert.Equal(t, breaking_chocolate.BreakChocolate(2, 1), 1) 12 | assert.Equal(t, breaking_chocolate.BreakChocolate(3, 1), 2) 13 | } 14 | -------------------------------------------------------------------------------- /bubble_sort/main.go: -------------------------------------------------------------------------------- 1 | package bubble_sort 2 | -------------------------------------------------------------------------------- /caeser_cipher/caeser_cipher_test.go: -------------------------------------------------------------------------------- 1 | package caeser_cipher_test 2 | 3 | import ( 4 | "efficient-algorithms/caeser_cipher" 5 | "testing" 6 | ) 7 | 8 | func assert(expected, actual string) bool { 9 | 10 | if expected == actual { 11 | return true 12 | } 13 | return false 14 | } 15 | 16 | //caesar("Abcd", 2) should return "Cdef" 17 | //caesar("message", -1) should return "ldrrzfd" 18 | //caesar("ZZ Top", 3) should return "CC Wrs" 19 | 20 | func TestCipher(t *testing.T) { 21 | 22 | result1 := caeser_cipher.Cipher("Abcd", 2) 23 | result2 := caeser_cipher.Cipher("message", -1) 24 | result3 := caeser_cipher.Cipher("ZZ Top", 3) 25 | 26 | if ok := assert("Cdef", result1); !ok { 27 | t.Errorf("got %s, want %s", result1, "Cdef") 28 | } 29 | 30 | if ok := assert("ldrrzfd", result2); !ok { 31 | t.Errorf("got %s, want %s", result2, "ldrrzfd") 32 | } 33 | 34 | if ok := assert("CC Wrs", result3); !ok { 35 | t.Errorf("got %s, want %s", result3, "CC Wrs") 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /caeser_cipher_2/caeser_cipher_2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | type ckey struct { 9 | enc, dec func(rune) rune 10 | } 11 | 12 | func newCaeser(k int) (*ckey, bool) { 13 | if k < 1 || k > 25 { 14 | return nil, false 15 | } 16 | 17 | rk := rune(k) 18 | 19 | return &ckey{ 20 | enc: func(c rune) rune { 21 | if c >= 'a' && c < 'z'-rk || c >= 'A' && c <= 'Z'-rk { 22 | return c + rk 23 | } else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' { 24 | return c + rk - 26 25 | } 26 | return c 27 | }, 28 | dec: func(c rune) rune { 29 | if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' { 30 | return c - rk 31 | } else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk { 32 | return c - rk + 26 33 | } 34 | return c 35 | }, 36 | }, true 37 | } 38 | 39 | func (ck ckey) encipher(pt string) string { 40 | return strings.Map(ck.enc, pt) 41 | } 42 | 43 | func (ck ckey) decipher(ct string) string { 44 | return strings.Map(ck.dec, ct) 45 | } 46 | 47 | func main() { 48 | 49 | pt := "The five boxing wizards jump quickly" 50 | 51 | for _, key := range []int{0, 1, 7, 25, 26} { 52 | ck, ok := newCaeser(key) 53 | if !ok { 54 | fmt.Println("key", key, "invalid") 55 | continue 56 | } 57 | ct := ck.encipher(pt) 58 | fmt.Println("key ", key) 59 | fmt.Println(" Enciphered: ", ct) 60 | fmt.Println(" Deciphered: ", ck.decipher(ct)) 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /cipher/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func cipher(str string, direction int) string { 9 | 10 | shift, offset := rune(math.Abs(float64(direction))), rune(26) 11 | 12 | runes := []rune(str) 13 | 14 | for i, c := range runes { 15 | 16 | switch { 17 | case direction > 0: 18 | if c >= 'a' && c <= 'z'-shift || c >= 'A' && c <= 'Z'-shift { 19 | c = c + shift 20 | } else if c > 'z'-shift && c <= 'z' || c > 'Z'-shift && c <= 'Z' { 21 | c = c + shift - offset 22 | } 23 | case direction < 0: 24 | if c >= 'a'+shift && c <= 'z' || c >= 'A'+shift && c <= 'Z' { 25 | c = c - shift 26 | } else if c >= 'a' && c < 'a'+shift || c >= 'A'+shift && c < 'A'+shift { 27 | fmt.Println("the one: ", string(c)) 28 | c = c - shift + offset 29 | } 30 | } 31 | 32 | runes[i] = c 33 | } 34 | 35 | return string(runes) 36 | } 37 | 38 | //caesar("Abcd", 2) should return "Cdef" 39 | //caesar("message", -1) should return "ldrrzfd" 40 | //caesar("ZZ Top", 3) should return "CC Wrs" 41 | 42 | func main() { 43 | 44 | result1 := cipher("Abcd", 2) 45 | fmt.Println(result1) 46 | 47 | result2 := cipher("message", -1) 48 | fmt.Println(result2) 49 | // 50 | result3 := cipher("ZZ Top", 3) 51 | fmt.Println(result3) 52 | } 53 | -------------------------------------------------------------------------------- /clockwise_spiral/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("this is the ans: ", CreateSpiral(5)) 7 | } 8 | 9 | //func CreateSpiral(n int) [][]int { 10 | // if n < 1 { 11 | // return [][]int{} 12 | // } 13 | // var matirx [][]int 14 | // 15 | // top, left, bottom, right := 0,0, n-1, n-1 16 | // sz := n * n 17 | // a := make([]int, sz) 18 | // i := 0 19 | // for left < right { 20 | // // work right, along top 21 | // for c := left; c <= right; c++ { 22 | // a[top*n+c] = i 23 | // i++ 24 | // } 25 | // top++ 26 | // //work down right side 27 | // for r := top; r <= bottom; r++ { 28 | // a[r*n+right] = i 29 | // i++ 30 | // } 31 | // right-- 32 | // if top == bottom { 33 | // break 34 | // } 35 | // //Work left, along bottom 36 | // for c := right; c >= left; c-- { 37 | // a[bottom*n+c] = i 38 | // i++ 39 | // } 40 | // bottom-- 41 | // 42 | // //work up left side 43 | // for r := bottom; r >= top; r-- { 44 | // a[r*n+left] = i 45 | // i++ 46 | // } 47 | // left++ 48 | // } 49 | // a[top*n+left] = i 50 | // 51 | // for m := 0; m <= n - 1; m++ { 52 | // l := m*n 53 | // h := m*n+n 54 | // matirx = append(matirx, a[l:h]) 55 | // } 56 | // return matirx 57 | //} 58 | 59 | func CreateSpiral(n int) [][]int { 60 | // your code here 61 | var matrice [][]int 62 | if n > 0 { 63 | l := 0 64 | t := 0 65 | r := n - 1 66 | b := n - 1 67 | 68 | line := make([]int, n*n) 69 | i := 1 70 | for l < r { 71 | for c := l; c <= r; c++ { 72 | line[t*n+c] = i 73 | i++ 74 | } 75 | t++ 76 | for z := t; z <= b; z++ { 77 | line[z*n+r] = i 78 | i++ 79 | } 80 | r-- 81 | if t == b { 82 | break 83 | } 84 | for c := r; c >= l; c-- { 85 | line[b*n+c] = i 86 | i++ 87 | } 88 | b-- 89 | for z := b; z >= t; z-- { 90 | line[z*n+l] = i 91 | i++ 92 | } 93 | l++ 94 | } 95 | line[t*n+l] = i 96 | // return matrice 97 | for m := 0; m <= n-1; m++ { 98 | low := m * n 99 | high := m*n + n 100 | matrice = append(matrice, line[low:high]) 101 | } 102 | return matrice 103 | } 104 | return [][]int{} 105 | 106 | } 107 | -------------------------------------------------------------------------------- /closest_and_smallest/closest_and_smallest_test.go: -------------------------------------------------------------------------------- 1 | package closest_and_smallest 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestClosest(t *testing.T) { 9 | 10 | assert.Equal(t, Closest("456899 50 11992 176 272293 163 389128 96 290193 85 52"), "[(13, 9, 85), (14, 3, 176)]") 11 | 12 | assert.Equal(t, Closest("239382 162 254765 182 485944 134 468751 62 49780 108 54"), "[(8, 5, 134), (8, 7, 62)]") 13 | 14 | } 15 | -------------------------------------------------------------------------------- /codility-go/arrays/cyclicRotation/cyclicRotation.go: -------------------------------------------------------------------------------- 1 | package cyclicRotation 2 | 3 | import "fmt" 4 | 5 | /* 6 | A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is 7 | shifted right by one index, and the last element of the array is also moved to the first place. 8 | 9 | For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. 10 | The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes. 11 | 12 | Write a function: 13 | 14 | func Solution(A []int, K int) []int 15 | 16 | that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times. 17 | 18 | For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8]. 19 | 20 | Assume that: 21 | 22 | N and K are integers within the range [0..100]; 23 | each element of array A is an integer within the range [−1,000..1,000]. 24 | In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment. 25 | */ 26 | 27 | func CyclicRotation(A []int, k int) []int { 28 | 29 | if k == 0 || len(A) == 0 || len(A) == 1 { 30 | return A 31 | } 32 | 33 | if len(A) < k { 34 | k = k % len(A) 35 | } 36 | 37 | lhs := A[len(A)-k:] 38 | 39 | fmt.Println("the lhs: ", lhs) 40 | 41 | return append(lhs, A[:len(A)-k]...) 42 | } 43 | 44 | func main() { 45 | 46 | A := []int{3, 8, 9, 7, 6} 47 | 48 | fmt.Println(CyclicRotation(A, 2)) 49 | } 50 | -------------------------------------------------------------------------------- /codility-go/arrays/cyclicRotation/cyclicRotation_test.go: -------------------------------------------------------------------------------- 1 | package cyclicRotation_test 2 | 3 | import ( 4 | "efficient-algorithms/codility-go/arrays/cyclicRotation" 5 | "fmt" 6 | "github.com/stretchr/testify/assert" 7 | "testing" 8 | ) 9 | 10 | func TestCyclicRotation(t *testing.T) { 11 | 12 | A := []int{3, 8, 9, 7, 6} 13 | k := 3 14 | 15 | ans := cyclicRotation.CyclicRotation(A, k) 16 | 17 | fmt.Println(ans) 18 | 19 | assert.EqualValues(t, len(A), 5) 20 | 21 | } 22 | -------------------------------------------------------------------------------- /codility-go/arrays/oddOccurrence/oddOccurrenceInArray_test.go: -------------------------------------------------------------------------------- 1 | package oddOccurrence_test 2 | 3 | import ( 4 | "efficient-algorithms/codility-go/arrays/oddOccurrence" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestOddOccurrence(t *testing.T) { 10 | 11 | A := []int{9, 1, 9, 3, 9, 7, 9} 12 | 13 | num := oddOccurrence.OddOccurrence(A) 14 | 15 | assert.EqualValues(t, num, 7) 16 | } 17 | -------------------------------------------------------------------------------- /codility-go/arrays/oddOccurrence/oddOccurrencesInArray.go: -------------------------------------------------------------------------------- 1 | package oddOccurrence 2 | 3 | /* 4 | A non-empty zero-indexed array A consisting of N integers is given. 5 | The array contains an odd number of elements, and each element of the array 6 | can be paired with another element that has the same value, except for one element that is left unpaired. 7 | 8 | For example, in array A such that: 9 | 10 | A[0] = 9 A[1] = 3 A[2] = 9 11 | A[3] = 3 A[4] = 9 A[5] = 7 12 | A[6] = 9 13 | 14 | the elements at indexes 0 and 2 have value 9, 15 | the elements at indexes 1 and 3 have value 3, 16 | the elements at indexes 4 and 6 have value 9, 17 | the element at index 5 has value 7 and is unpaired. 18 | Write a function: 19 | 20 | func Solution(A []int) int 21 | that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. 22 | 23 | For example, given array A such that: 24 | 25 | A[0] = 9 A[1] = 3 A[2] = 9 26 | A[3] = 3 A[4] = 9 A[5] = 7 27 | A[6] = 9 28 | the function should return 7, as explained in the example above. 29 | 30 | Assume that: 31 | 32 | N is an odd integer within the range [1..1,000,000]; 33 | each element of array A is an integer within the range [1..1,000,000,000]; 34 | all but one of the values in A occur an even number of times. 35 | 36 | */ 37 | 38 | func OddOccurrence(A []int) (oddOne int) { 39 | 40 | var histogram = make(map[int]int) 41 | 42 | for _, value := range A { 43 | histogram[value]++ 44 | } 45 | 46 | for k, value := range histogram { 47 | if isOdd(value) { 48 | oddOne = k 49 | return 50 | } 51 | } 52 | return -1 53 | } 54 | 55 | func isOdd(n int) bool { 56 | return n%2 == 1 57 | } 58 | -------------------------------------------------------------------------------- /codility-go/complexity/fromjmp/fromjmp.go: -------------------------------------------------------------------------------- 1 | package fromjmp 2 | 3 | import "math" 4 | 5 | /* 6 | A small frog wants to get to the other side of the road. 7 | The frog is currently located at position X and wants to get to a position greater than or equal to Y. 8 | The small frog always jumps a fixed distance, D. 9 | 10 | Count the minimal number of jumps that the small frog must perform to reach its target. 11 | 12 | Write a function: 13 | 14 | func Solution(X int, Y int, D int) int 15 | 16 | that, given three integers X, Y and D, returns the minimal number of 17 | jumps from position X to a position equal to or greater than Y. 18 | 19 | For example, given: 20 | 21 | X = 10 22 | Y = 85 23 | D = 30 24 | the function should return 3, because the frog will be positioned as follows: 25 | 26 | after the first jump, at position 10 + 30 = 40 27 | after the second jump, at position 10 + 30 + 30 = 70 28 | after the third jump, at position 10 + 30 + 30 + 30 = 100 29 | Assume that: 30 | 31 | X, Y and D are integers within the range [1..1,000,000,000]; 32 | X ≤ Y. 33 | 34 | Complexity: 35 | 36 | expected worst-case time complexity is O(1); 37 | expected worst-case space complexity is O(1). 38 | */ 39 | 40 | func FromJmp(x int, y int, d int) int { 41 | return int(math.Ceil(float64(float64(y-x) / float64(d)))) 42 | } 43 | -------------------------------------------------------------------------------- /codility-go/complexity/fromjmp/fromjmp_test.go: -------------------------------------------------------------------------------- 1 | package fromjmp_test 2 | 3 | import ( 4 | "efficient-algorithms/codility-go/complexity/fromjmp" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestFromJmp(t *testing.T) { 10 | 11 | ans1 := fromjmp.FromJmp(10, 85, 30) 12 | ans2 := fromjmp.FromJmp(1, 5, 2) 13 | 14 | assert.EqualValues(t, ans1, 3) 15 | assert.EqualValues(t, ans2, 2) 16 | } 17 | -------------------------------------------------------------------------------- /codility-go/complexity/permMissingElem/permMissingElem.go: -------------------------------------------------------------------------------- 1 | package permMissingElem 2 | 3 | import ( 4 | "math" 5 | "sort" 6 | ) 7 | 8 | /* 9 | A zero-indexed array A consisting of N different integers is given. 10 | The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. 11 | 12 | Your goal is to find that missing element. 13 | 14 | Write a function: 15 | 16 | func Solution(A []int) int 17 | 18 | that, given a zero-indexed array A, returns the value of the missing element. 19 | 20 | For example, given array A such that: 21 | 22 | A[0] = 2 23 | A[1] = 3 24 | A[2] = 1 25 | A[3] = 5 26 | the function should return 4, as it is the missing element. 27 | 28 | Assume that: 29 | 30 | N is an integer within the range [0..100,000]; 31 | the elements of A are all distinct; 32 | each element of array A is an integer within the range [1..(N + 1)]. 33 | 34 | Complexity: 35 | 36 | expected worst-case time complexity is O(N); 37 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 38 | 39 | */ 40 | 41 | // Use Sum formula to calculate Sum(len(A)+1) - Sum(A). This will pick up the difference of the 2 sums 42 | func PerMissingElem(A []int) int { 43 | if len(A) == 0 { 44 | return 1 45 | } 46 | 47 | n := len(A) + 1 48 | arraySum := 0 49 | totalSum := (n + 1) * n / 2 50 | 51 | for _, value := range A { 52 | arraySum += value 53 | } 54 | 55 | return totalSum - arraySum 56 | 57 | } 58 | 59 | func mine(A []int) int { 60 | 61 | //sort the array: 62 | sort.Ints(A) 63 | 64 | x := 1 65 | 66 | for i := 0; i < len(A); i++ { 67 | if x < A[i] { 68 | return x 69 | } 70 | //x = A[i] + 1 71 | x = int(math.Abs(float64(A[i])) + 1) 72 | } 73 | 74 | return x 75 | 76 | } 77 | 78 | //function solution(A) { 79 | //// only positive values, sorted 80 | //A = A.filter(x => x >= 1).sort((a, b) => a - b) 81 | // 82 | //let x = 1 83 | // 84 | //for(let i = 0; i < A.length; i++) { 85 | //// if we find a smaller number no need to continue, cause the array is sorted 86 | //if(x < A[i]) { 87 | //return x 88 | //} 89 | //x = A[i] + 1 90 | //} 91 | // 92 | //return x 93 | //} 94 | -------------------------------------------------------------------------------- /codility-go/complexity/permMissingElem/permMissingElem_test.go: -------------------------------------------------------------------------------- 1 | package permMissingElem_test 2 | 3 | import ( 4 | "efficient-algorithms/codility-go/complexity/permMissingElem" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestPerMissingElem(t *testing.T) { 10 | 11 | A := []int{2, 3, 1, 5} 12 | ans := permMissingElem.PerMissingElem(A) 13 | assert.EqualValues(t, ans, 4) 14 | 15 | A2 := []int{1, 2, 3, 4, 5, 7} 16 | ans2 := permMissingElem.PerMissingElem(A2) 17 | assert.EqualValues(t, ans2, 6) 18 | } 19 | -------------------------------------------------------------------------------- /codility-go/complexity/tapeEquilibrium/tapeEquilibrium.go: -------------------------------------------------------------------------------- 1 | package tapeEquilibrium 2 | 3 | import "math" 4 | 5 | /* 6 | A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. 7 | 8 | Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: 9 | A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. 10 | 11 | The difference between the two parts is the value of: 12 | |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| 13 | 14 | In other words, it is the absolute difference between the sum of the first part and the sum of the second part. 15 | 16 | For example, consider array A such that: 17 | 18 | A[0] = 3 19 | A[1] = 1 20 | A[2] = 2 21 | A[3] = 4 22 | A[4] = 3 23 | We can split this tape in four places: 24 | 25 | P = 1, difference = |3 − 10| = 7 26 | P = 2, difference = |4 − 9| = 5 27 | P = 3, difference = |6 − 7| = 1 28 | P = 4, difference = |10 − 3| = 7 29 | Write a function: 30 | 31 | func Solution(A []int) int 32 | that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved. 33 | 34 | For example, given: 35 | 36 | A[0] = 3 37 | A[1] = 1 38 | A[2] = 2 39 | A[3] = 4 40 | A[4] = 3 41 | the function should return 1, as explained above. 42 | 43 | Assume that: 44 | 45 | N is an integer within the range [2..100,000]; 46 | each element of array A is an integer within the range [−1,000..1,000]. 47 | 48 | Complexity: 49 | 50 | expected worst-case time complexity is O(N); 51 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 52 | */ 53 | 54 | func TapeEquilibrium(A []int) int { 55 | arraySum := 0 56 | currentMin := 1<<32 - 1 57 | 58 | for _, value := range A { 59 | arraySum += value 60 | } 61 | lhs := A[0] 62 | rhs := arraySum - lhs 63 | 64 | for i := 1; i < len(A); i++ { 65 | diff := int(math.Abs(float64(lhs) - float64(rhs))) 66 | 67 | if diff < currentMin { 68 | currentMin = diff 69 | } 70 | 71 | lhs += A[i] 72 | rhs -= A[i] 73 | } 74 | 75 | return currentMin 76 | } 77 | -------------------------------------------------------------------------------- /common_den/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | var lst = [][]int{{1, 2}, {1, 3}, {1, 4}} 9 | 10 | func main() { 11 | fmt.Println("this is the statement") 12 | fmt.Println(ConvertFracts(lst)) 13 | } 14 | 15 | func ConvertFracts(a [][]int) string { 16 | var lcm = 1 17 | for _, v := range a { 18 | var denom = v[1] / GCF(v[0], v[1]) 19 | var gcf = GCF(lcm, denom) 20 | lcm = lcm * (denom / gcf) 21 | } 22 | var answer string 23 | for _, item := range a { 24 | answer = answer + "(" + strconv.Itoa(item[0]*lcm/item[1]) + "," + strconv.Itoa(lcm) + ")" 25 | } 26 | return answer 27 | } 28 | 29 | func GCF(a int, b int) int { 30 | var x, y int 31 | if a > b { 32 | x, y = a, b 33 | } else { 34 | x, y = b, a 35 | } 36 | for y != 0 { 37 | x, y = y, x%y 38 | } 39 | return x 40 | } 41 | -------------------------------------------------------------------------------- /complex_struct/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | 11 | const tpl = ` 12 | {{.Name}}{{ range $child := .Children }} {{ $child.Name }} {{ range $grandchild := $child.Children }} {{ $grandchild.Name }} {{ end }} {{ end }} 13 | ` 14 | 15 | root := mine{ 16 | "Steven", []mine{ 17 | { 18 | "Stanley", []mine{ 19 | { 20 | "Gozie", 21 | nil, 22 | }, 23 | { 24 | "Mark", 25 | nil, 26 | }, 27 | }, 28 | }, 29 | }, 30 | } 31 | t := template.Must(template.New("tree").Parse(tpl)) 32 | err := t.Execute(os.Stdout, root) 33 | if err != nil { 34 | log.Fatalf("executing template: ", err) 35 | } 36 | 37 | //fmt.Println(ans) 38 | 39 | } 40 | 41 | type mine struct { 42 | Name string 43 | Children []mine 44 | } 45 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_1/example_1.go: -------------------------------------------------------------------------------- 1 | package example_1 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it. 9 | 10 | //Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW 11 | 12 | //Output: 12W1B12W3B24W1B14W 13 | 14 | //This deifference between this and example 2 is that for single values, add the 1 in from of the character 15 | 16 | func Solution1(str string) string { 17 | 18 | count := 0 19 | result := "" 20 | 21 | for i := 0; i < len(str); i++ { 22 | 23 | //get the first character: 24 | a := string(str[i]) 25 | //make the count to be one: 26 | count = 1 27 | 28 | //now check how many times each character occur: 29 | for i+1 < len(str) && string(str[i]) == string(str[i+1]) { 30 | count++ 31 | i++ 32 | } 33 | 34 | //the output: 35 | result += fmt.Sprintf("%d%s", count, a) 36 | 37 | } 38 | 39 | return result 40 | } 41 | 42 | func Solution2(str string) string { 43 | 44 | prev := str[0:1] 45 | count := 1 46 | 47 | result := "" 48 | 49 | for _, v := range strings.Split(str[1:], "") { 50 | if prev == v { 51 | count++ 52 | } else { 53 | result += fmt.Sprintf("%d%s", count, prev) 54 | prev = v 55 | count = 1 //this is very important so the previous count of another element is not added to another 56 | } 57 | } 58 | result += fmt.Sprintf("%d%s", count, prev) 59 | 60 | return result 61 | 62 | } 63 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_1/example_1_test.go: -------------------------------------------------------------------------------- 1 | package example_1_test 2 | 3 | import ( 4 | "efficient-algorithms/compress_characters/run-length-encoding/example_1" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolution1(t *testing.T) { 10 | 11 | sample := []struct { 12 | str string 13 | result string 14 | }{ 15 | { 16 | "AAAADDFFFAAFFDDSSWW", 17 | "4A2D3F2A2F2D2S2W", 18 | }, 19 | { 20 | "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 21 | "12W1B12W3B24W1B14W", 22 | }, 23 | { 24 | "ABC", 25 | "1A1B1C", 26 | }, 27 | } 28 | 29 | for _, v := range sample { 30 | 31 | result := example_1.Solution1(v.str) 32 | 33 | assert.EqualValues(t, v.result, result) 34 | } 35 | } 36 | 37 | func TestSolution2(t *testing.T) { 38 | 39 | sample := []struct { 40 | str string 41 | result string 42 | }{ 43 | { 44 | "AAAADDFFFAAFFDDSSWW", 45 | "4A2D3F2A2F2D2S2W", 46 | }, 47 | { 48 | "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 49 | "12W1B12W3B24W1B14W", 50 | }, 51 | { 52 | "ABC", 53 | "1A1B1C", 54 | }, 55 | } 56 | 57 | for _, v := range sample { 58 | 59 | result := example_1.Solution2(v.str) 60 | 61 | assert.EqualValues(t, v.result, result) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_2/example_2.go: -------------------------------------------------------------------------------- 1 | package example_2 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //Run-length encoding (RLE) is a simple "compression algorithm" (an algorithm which takes a block of data and reduces its size, producing a block that contains the same information in less space). It works by replacing repetitive sequences of identical data items with short "tokens" that represent entire sequences. Applying RLE to a string involves finding sequences in the string where the same character repeats. Each such sequence should be replaced by a "token" consisting of: 9 | // 10 | //the number of characters in the sequence the repeating character If a character does not repeat, it should be left alone. 11 | // 12 | //For example, consider the following string: 13 | 14 | //qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT 15 | 16 | //After applying the RLE algorithm, this string is converted into: 17 | // 18 | //q9w5e2rt5y4qw2Er3T 19 | 20 | func Solution1(str string) string { 21 | 22 | count := 0 23 | result := "" 24 | 25 | for i := 0; i < len(str); i++ { 26 | var a = string(str[i]) 27 | count = 1 28 | 29 | for i+1 < len(str) && string(str[i]) == string(str[i+1]) { 30 | count++ 31 | i++ 32 | } 33 | 34 | if count == 1 { 35 | result += fmt.Sprintf("%s", a) 36 | } else { 37 | result += fmt.Sprintf("%d%s", count, a) 38 | } 39 | } 40 | 41 | return result 42 | } 43 | 44 | func Solution2(str string) string { 45 | 46 | prev := str[0:1] 47 | count := 1 48 | 49 | result := "" 50 | 51 | for _, v := range strings.Split(str[1:], "") { 52 | if prev == v { 53 | count++ 54 | } else { 55 | if count == 1 { 56 | result += fmt.Sprintf("%s", prev) 57 | } else { 58 | result += fmt.Sprintf("%d%s", count, prev) 59 | } 60 | prev = v 61 | count = 1 62 | } 63 | } 64 | 65 | if count == 1 { 66 | result += fmt.Sprintf("%s", prev) 67 | } else { 68 | result += fmt.Sprintf("%d%s", count, prev) 69 | } 70 | 71 | return result 72 | 73 | } 74 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_2/example_2_test.go: -------------------------------------------------------------------------------- 1 | package example_2_test 2 | 3 | import ( 4 | "efficient-algorithms/compress_characters/run-length-encoding/example_2" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolution1(t *testing.T) { 10 | 11 | sample := []struct { 12 | str string 13 | result string 14 | }{ 15 | { 16 | "AAAADDFFFAAFFDDSSWW", 17 | "4A2D3F2A2F2D2S2W", 18 | }, 19 | { 20 | "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 21 | "12WB12W3B24WB14W", 22 | }, 23 | { 24 | "ABC", 25 | "ABC", 26 | }, 27 | } 28 | 29 | for _, v := range sample { 30 | 31 | result := example_2.Solution1(v.str) 32 | 33 | assert.EqualValues(t, v.result, result) 34 | } 35 | } 36 | 37 | func TestSolution2(t *testing.T) { 38 | 39 | sample := []struct { 40 | str string 41 | result string 42 | }{ 43 | { 44 | "AAAADDFFFAAFFDDSSWW", 45 | "4A2D3F2A2F2D2S2W", 46 | }, 47 | { 48 | "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 49 | "12WB12W3B24WB14W", 50 | }, 51 | { 52 | "ABC", 53 | "ABC", 54 | }, 55 | } 56 | 57 | for _, v := range sample { 58 | 59 | result := example_2.Solution2(v.str) 60 | 61 | assert.EqualValues(t, v.result, result) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_3/example_3.go: -------------------------------------------------------------------------------- 1 | package example_3 2 | 3 | import "fmt" 4 | 5 | //In this example, we will group all alphabets and count all same alphabets 6 | 7 | func Solution1(str string) string { 8 | 9 | mapStr := make(map[string]uint) 10 | 11 | result := "" 12 | 13 | for _, v := range str { 14 | mapStr[string(v)]++ 15 | } 16 | 17 | for key, val := range mapStr { 18 | if val == 1 { 19 | result += fmt.Sprintf("%s", key) 20 | } else { 21 | result += fmt.Sprintf("%d%s", val, key) 22 | } 23 | } 24 | 25 | return result 26 | } 27 | -------------------------------------------------------------------------------- /compress_characters/run-length-encoding/example_3/example_3_test.go: -------------------------------------------------------------------------------- 1 | package example_3_test 2 | 3 | import ( 4 | "efficient-algorithms/compress_characters/run-length-encoding/example_3" 5 | "fmt" 6 | "testing" 7 | ) 8 | 9 | func TestSolution1(t *testing.T) { 10 | 11 | //sample := []struct{ 12 | // str string 13 | // result string 14 | //}{ 15 | //6A4D5F2S2W is just one arrangement, so we cant assert for it alone. 16 | //{ 17 | // "AAAADDFFFAAFFDDSSWW", 18 | // "6A4D5F2S2W", 19 | //}, 20 | 21 | //the ans can either be 62W5B or 5B62W, 22 | //{ 23 | // "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 24 | // "62W5B", 25 | //}, 26 | 27 | //ABC is just one arrangement, but we cant assert for it alone 28 | //{ 29 | // "ABC", 30 | // "ABC", 31 | //}, 32 | //} 33 | 34 | //for _, v := range sample { 35 | // 36 | // result := example_3.Solution1(v.str) 37 | // 38 | // assert.EqualValues(t, v.result, result) 39 | // 40 | //} 41 | 42 | fmt.Println(example_3.Solution1("AAAADDFFFAAFFDDSSWW")) 43 | } 44 | -------------------------------------------------------------------------------- /consecutive_string/consecutive_string.go: -------------------------------------------------------------------------------- 1 | package consecutive_string 2 | 3 | import "strings" 4 | 5 | //ou are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array. 6 | // 7 | //Example: 8 | //longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta" 9 | // 10 | //n being the length of the string array, if n = 0 or k > n or k <= 0 return "". 11 | // 12 | //Note 13 | //consecutive strings : follow one after another without an interruption 14 | 15 | func LongestConsec(strarr []string, k int) string { 16 | 17 | n := len(strarr) 18 | if n == 0 || k > n || k <= 0 { 19 | return "" 20 | } 21 | 22 | var buffer string 23 | var largest string 24 | 25 | for i := 0; i <= len(strarr)-k; i++ { 26 | buffer = strings.Join(strarr[i : i+k][:], "") 27 | if len(buffer) > len(largest) { 28 | largest = buffer 29 | } 30 | } 31 | 32 | return largest 33 | 34 | } 35 | 36 | func LongestConsec2(strarr []string, k int) string { 37 | longest := "" 38 | for i := 0; i < len(strarr)-k+1; i++ { 39 | joined := strings.Join(strarr[i:i+k], "") 40 | if len(joined) > len(longest) { 41 | longest = joined 42 | } 43 | } 44 | return longest 45 | } 46 | -------------------------------------------------------------------------------- /consecutive_string/consecutive_string_test.go: -------------------------------------------------------------------------------- 1 | package consecutive_string 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestLongestConsec(t *testing.T) { 9 | 10 | assert.Equal(t, LongestConsec([]string{"zone", "abigail", "theta", "form", "libe", "zas"}, 2), "abigailtheta") 11 | assert.Equal(t, LongestConsec([]string{"ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"}, 1), "oocccffuucccjjjkkkjyyyeehh") 12 | assert.Equal(t, LongestConsec([]string{"itvayloxrp", "wkppqsztdkmvcuwvereiupccauycnjutlv", "vweqilsfytihvrzlaodfixoyxvyuyvgpck"}, 2), "wkppqsztdkmvcuwvereiupccauycnjutlvvweqilsfytihvrzlaodfixoyxvyuyvgpck") 13 | assert.Equal(t, LongestConsec([]string{}, 3), "") 14 | 15 | } 16 | -------------------------------------------------------------------------------- /consecutive_strings/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | func LongestConsec(strarr []string, k int) string { 8 | n := len(strarr) 9 | str := "" 10 | if n == 0 || k > n || k <= 0 { 11 | return str 12 | } 13 | var max = 0 14 | var longest_word = "" 15 | for i := 0; i < n; i++ { 16 | if len(strarr[i]) > max { 17 | max = len(strarr[i]) 18 | longest_word = strarr[i] 19 | if i == len(strarr)-1 { 20 | return longest_word 21 | } 22 | } 23 | for j := i + 1; j <= k; j++ { 24 | str = longest_word + strarr[j] 25 | } 26 | } 27 | return str 28 | } 29 | -------------------------------------------------------------------------------- /consonant_value/consonant_value.go: -------------------------------------------------------------------------------- 1 | package consonant_value 2 | 3 | import ( 4 | "regexp" 5 | ) 6 | 7 | //Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except "aeiou". 8 | // 9 | //We shall assign the following values: a = 1, b = 2, c = 3, .... z = 26. 10 | // 11 | //For example, for the word "zodiacs", let's cross out the vowels. We get: "z o d ia cs" 12 | // 13 | //-- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The highest is 26. 14 | //solve("zodiacs") = 26 15 | // 16 | //For the word "strength", solve("strength") = 57 17 | //-- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The highest is 57. 18 | //For C: do not mutate input. 19 | // 20 | //More examples in test cases. Good luck! 21 | 22 | //func Solve(str string) int { 23 | // 24 | // reg := regexp.MustCompile(`[aeiou]`) 25 | // 26 | // consonantStr := reg.ReplaceAllString(str, "-") 27 | // 28 | // consoArr := strings.Split(consonantStr, "-") 29 | // 30 | // numArr := []int{} 31 | // 32 | // for _, s := range consoArr { 33 | // num := 0 34 | // for _, ch := range s { 35 | // num += int(ch) - 'a' + 1 36 | // } 37 | // numArr = append(numArr, num) 38 | // } 39 | // 40 | // max := 0 41 | // 42 | // for _, v := range numArr { 43 | // if max < v { 44 | // max = v 45 | // } 46 | // } 47 | // 48 | // return max 49 | // 50 | //} 51 | 52 | func Solve(str string) int { 53 | 54 | reg := regexp.MustCompile(`[aeiou]`) 55 | 56 | consoArr := reg.Split(str, -1) 57 | 58 | numArr := []int{} 59 | 60 | for _, s := range consoArr { 61 | num := 0 62 | for _, ch := range s { 63 | num += int(ch) - 'a' + 1 64 | } 65 | numArr = append(numArr, num) 66 | } 67 | 68 | max := 0 69 | 70 | for _, v := range numArr { 71 | if max < v { 72 | max = v 73 | } 74 | } 75 | 76 | return max 77 | 78 | } 79 | 80 | func Solve2(str string) (maximum int) { 81 | 82 | var sum int 83 | 84 | for _, r := range str { 85 | switch r { 86 | case 'a', 'e', 'i', 'o', 'u': 87 | sum = 0 88 | continue 89 | } 90 | sum += int(r) - 'a' + 1 91 | 92 | if sum > maximum { 93 | maximum = sum 94 | } 95 | } 96 | return maximum 97 | } 98 | -------------------------------------------------------------------------------- /consonant_value/consonant_value_test.go: -------------------------------------------------------------------------------- 1 | package consonant_value 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSolve(t *testing.T) { 9 | 10 | assert.Equal(t, Solve("zodiacs"), 26) 11 | assert.Equal(t, Solve("uaoczei"), 29) 12 | assert.Equal(t, Solve2("abababababfapeifapefijaefaepfjavnefjnfbhwyfnjsifjapnes"), 143) 13 | assert.Equal(t, Solve2("codewars"), 37) 14 | 15 | assert.Equal(t, Solve("this is the man at the balcony"), 39) 16 | 17 | } 18 | -------------------------------------------------------------------------------- /context/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | 11 | timeout := 3 * time.Second 12 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 13 | defer cancel() 14 | 15 | select { 16 | case <-time.After(1 * time.Second): 17 | fmt.Println("waited for 1 sec") 18 | case <-time.After(2 * time.Second): 19 | fmt.Println("waited for 2 sec") 20 | case <-time.After(3 * time.Second): 21 | fmt.Println("waited for 3 seconds") 22 | case <-ctx.Done(): 23 | fmt.Println(ctx.Err()) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /copy/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var s = make([]int, 3) 7 | n := copy(s, []int{0, 1, 2, 3}) 8 | 9 | fmt.Println(n) 10 | fmt.Println("the slice: ", s) 11 | 12 | b := make([]byte, 5) 13 | m := copy(b, "Hello world") 14 | fmt.Println(m) 15 | fmt.Println("the byte slice: ", string(b)) 16 | 17 | var s1 []int 18 | s2 := []int{1, 2, 3} 19 | n1 := copy(s1, s2) 20 | fmt.Printf("n1=%d, s1=%v, s2=%v\n", n1, s1, s2) 21 | fmt.Println("s1 == nil", s1 == nil) 22 | } 23 | -------------------------------------------------------------------------------- /count_divisors/count_divisors.go: -------------------------------------------------------------------------------- 1 | package count_divisors 2 | 3 | //Count the number of divisors of a positive integer n. 4 | // 5 | //Random tests go up to n = 500000. 6 | 7 | //Examples 8 | //divisors(4) == 3 // 1, 2, 4 9 | //divisors(5) == 2 // 1, 5 10 | //divisors(12) == 6 // 1, 2, 3, 4, 6, 12 11 | //divisors(30) == 8 // 1, 2, 3, 5, 6, 10, 15, 30 12 | 13 | func Divisors(n int) int { 14 | 15 | count := 0 16 | 17 | for i := 1; i <= 50000; i++ { 18 | 19 | if n%i == 0 { 20 | count++ 21 | } 22 | } 23 | 24 | return count 25 | } 26 | -------------------------------------------------------------------------------- /count_divisors/count_divisors_test.go: -------------------------------------------------------------------------------- 1 | package count_divisors 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestDivisors(t *testing.T) { 9 | 10 | assert.Equal(t, 3, Divisors(4)) 11 | assert.Equal(t, 2, Divisors(5)) 12 | assert.Equal(t, 6, Divisors(12)) 13 | assert.Equal(t, 8, Divisors(30)) 14 | } 15 | -------------------------------------------------------------------------------- /count_string/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(countString("aaabbbvraqq")) 10 | } 11 | 12 | func countString(s string) []string { 13 | number_values := []string{} 14 | for _, v := range s { 15 | ans := strings.Count(strings.ToLower(s), string(v)) 16 | ansMod := fmt.Sprintf("%v-%v", string(v), ans) 17 | number_values = append(number_values, ansMod) 18 | } 19 | newArray := []string{} 20 | keys := make(map[string]bool) 21 | for _, v := range number_values { 22 | if value := keys[v]; !value { 23 | keys[v] = true 24 | newArray = append(newArray, v) 25 | } 26 | } 27 | return newArray 28 | } 29 | -------------------------------------------------------------------------------- /datastructures/trees/trees.go: -------------------------------------------------------------------------------- 1 | package trees 2 | 3 | //MultiNode multi node 4 | type MultiNode struct { 5 | Parent *MultiNode 6 | Data interface{} 7 | Children []*MultiNode 8 | } 9 | 10 | //BinaryNode binary node 11 | type BinaryNode struct { 12 | Parent *BinaryNode 13 | Data interface{} 14 | Left *BinaryNode 15 | Right *BinaryNode 16 | } 17 | -------------------------------------------------------------------------------- /deadfish_swim/deadfish_swim.go: -------------------------------------------------------------------------------- 1 | package deadfish_swim 2 | 3 | // Write a simple parser that will parse and run Deadfish. 4 | // 5 | //Deadfish has 4 commands, each 1 character long: 6 | // 7 | //i increments the value (initially 0) 8 | //d decrements the value 9 | //s squares the value 10 | //o outputs the value into the return array 11 | //Invalid characters should be ignored. 12 | // 13 | //Parse("iiisdoso") == []int{8, 64} 14 | 15 | func Parse(data string) []int { 16 | output := []int{} 17 | 18 | var val int 19 | for _, s := range data { 20 | switch string(s) { 21 | case "i": 22 | val++ 23 | case "d": 24 | val-- 25 | case "s": 26 | val = val * val 27 | case "o": 28 | output = append(output, val) 29 | } 30 | } 31 | return output 32 | } 33 | -------------------------------------------------------------------------------- /deadfish_swim/deadfish_swim_test.go: -------------------------------------------------------------------------------- 1 | package deadfish_swim 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestParse(t *testing.T) { 9 | assert.Equal(t, []int{8, 64}, Parse("iiisdoso")) 10 | assert.Equal(t, []int{0, 1}, Parse("idoiido")) 11 | assert.Equal(t, []int{1, 4, 25}, Parse("isoisoiso")) 12 | } 13 | -------------------------------------------------------------------------------- /decimal_to_factorial/decimal_to_factorial_test.go: -------------------------------------------------------------------------------- 1 | package decimal_to_factorial 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestDec2FactString(t *testing.T) { 9 | 10 | assert.Equal(t, Dec2FactString(36288000), "A0000000000") 11 | assert.Equal(t, Dec2FactString(2982), "4041000") 12 | 13 | assert.Equal(t, FacsString2Dec("341010"), 463) 14 | assert.Equal(t, FacsString2Dec("4042100"), 2990) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /deodorant_evaporator/deodorant_evaporator.go: -------------------------------------------------------------------------------- 1 | package deodorant_evaporator 2 | -------------------------------------------------------------------------------- /deodorant_evaporator/deodorant_evaporator_test.go: -------------------------------------------------------------------------------- 1 | package deodorant_evaporator 2 | 3 | import "fmt" 4 | 5 | func Evaporator(content float64, evapPerDay int, threshold int) int { 6 | // your code 7 | 8 | fmt.Println("this is the tiny example") 9 | 10 | return -1 11 | } 12 | -------------------------------------------------------------------------------- /digit_symmetry/digit_symmetry.go: -------------------------------------------------------------------------------- 1 | package digit_symmetry 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | //Consider the number 1176 and its square (1176 * 1176) = 1382976. Notice that: 8 | // 9 | //the first two digits of 1176 form a prime. 10 | //the first two digits of the square 1382976 also form a prime. 11 | //the last two digits of 1176 and 1382976 are the same. 12 | //Given two numbers representing a range (a, b), how many numbers satisfy this property within that range? (a <= n < b) 13 | 14 | //Example 15 | //solve(2, 1200) = 1, because only 1176 satisfies this property within the range 2 <= n < 1200. See test cases for more examples. The upper bound for the range will not exceed 1,000,000. 16 | // 17 | //Good luck! 18 | // 19 | //If you like this Kata, please try: 20 | 21 | func DigitSymmetry(a, b int) int { 22 | n := 0 23 | for i := a; i < b; i++ { 24 | x := strconv.Itoa(i) 25 | y := strconv.Itoa(i * i) 26 | 27 | if len(x) > 2 && len(y) > 2 { 28 | if x[len(x)-2:] != y[len(y)-2:] { 29 | continue 30 | } 31 | if !isPrime(x[:2]) { 32 | continue 33 | } 34 | if !isPrime(y[:2]) { 35 | continue 36 | } 37 | n++ 38 | } 39 | } 40 | return n 41 | } 42 | 43 | func isPrime(x string) bool { 44 | 45 | n, _ := strconv.Atoi(x) 46 | 47 | for i := 2; i < n; i++ { 48 | if n%i == 0 { 49 | return false 50 | } 51 | } 52 | 53 | return true 54 | 55 | } 56 | -------------------------------------------------------------------------------- /digit_symmetry/digit_symmetry_test.go: -------------------------------------------------------------------------------- 1 | package digit_symmetry_test 2 | 3 | import ( 4 | "efficient-algorithms/digit_symmetry" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestDigitSymmetry(t *testing.T) { 10 | 11 | assert.Equal(t, digit_symmetry.DigitSymmetry(2, 1200), 1) 12 | 13 | assert.Equal(t, digit_symmetry.DigitSymmetry(2, 100000), 247) 14 | 15 | assert.Equal(t, digit_symmetry.DigitSymmetry(2, 1000000), 2549) 16 | 17 | assert.Equal(t, digit_symmetry.DigitSymmetry(100000, 1000000), 2302) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /digits/six_digit/six_digit.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //Given any six digit number, how could one output a slice where each character of that number is assigned an individual location within the slice? 4 | // 5 | //For instance, a slice (let's call it s) containing all of these characters, would have s[0]=first digit, s[1]=second digit, s[2]=third digit and so on. 6 | // 7 | //Any help would be greatly appreciated! 8 | 9 | ///////////////// 10 | //func IntToSlice(n int64, sequence []int64) []int64 { 11 | // if n != 0 { 12 | // i := n % 10 13 | // sequence = append([]int64{i}, sequence...) 14 | // 15 | // return IntToSlice(n/10, sequence) 16 | // } 17 | // return sequence 18 | //} 19 | // 20 | //func main() { 21 | // 22 | // ans := IntToSlice(3, []int64{1,2,3,4,5,6}) 23 | // 24 | // fmt.Println(ans) 25 | // 26 | //} 27 | -------------------------------------------------------------------------------- /diophantine/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("this is the output: ", Solequa(90005)) 10 | } 11 | 12 | func Solequa(n int) [][]int { 13 | r := make([][]int, 0) 14 | for i := 1; i < int(math.Sqrt(float64(n)))+1; i++ { 15 | if n%i == 0 { 16 | d := n / i 17 | if (d-i)%4 == 0 { 18 | y := (d - i) / 4 19 | x := i + 2*y 20 | r = append(r, []int{x, y}) 21 | } 22 | } 23 | } 24 | return r 25 | } 26 | 27 | func Solequa2(n int) (ret [][]int) { 28 | ret = [][]int{} 29 | sqrt := int(math.Sqrt(float64(n))) 30 | for i := 1; i <= sqrt; i++ { 31 | if n%i != 0 { 32 | continue 33 | } 34 | t := n / i 35 | t1 := t - i 36 | if t1%4 != 0 { 37 | continue 38 | } 39 | ret = append(ret, []int{(t + i) / 2, t1 / 4}) 40 | } 41 | return 42 | } 43 | -------------------------------------------------------------------------------- /duplicate/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(unique([]int{1, 2, 3, 5, 5, 3, 2, 5})) 7 | fmt.Println(removeDup([]int{1, 2, 3, 5, 5, 3, 2, 5})) 8 | 9 | } 10 | 11 | func unique(intSlice []int) []int { 12 | keys := make(map[int]bool) 13 | var list []int 14 | for _, entry := range intSlice { 15 | if _, value := keys[entry]; !value { 16 | keys[entry] = true 17 | list = append(list, entry) 18 | } 19 | } 20 | return list 21 | } 22 | 23 | func removeDup(intSlice []int) []int { 24 | var list []int 25 | keys := make(map[int]bool) 26 | for _, v := range intSlice { 27 | if _, value := keys[v]; !value { //it is not a duplicate 28 | keys[v] = true 29 | list = append(list, v) 30 | } 31 | } 32 | return list 33 | } 34 | -------------------------------------------------------------------------------- /encrypt_this/encrypt_this.go: -------------------------------------------------------------------------------- 1 | package encrypt_this 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //Encrypt this! 9 | // 10 | //You want to create secret messages which can be deciphered by the Decipher this! kata. Here are the conditions: 11 | // 12 | //Your message is a string containing space separated words. 13 | //You need to encrypt each word in the message using the following rules: 14 | //The first letter needs to be converted to its ASCII code. 15 | //The second letter needs to be switched with the last letter 16 | //Keepin' it simple: There are no special characters in input. 17 | //Examples: 18 | //EncryptThis("Hello") == "72olle" 19 | //EncryptThis("good") == "103doo" 20 | //EncryptThis("normal_http_call world") == "104olle 119drlo" 21 | 22 | func EncryptThis(text string) string { 23 | 24 | if len(text) == 0 { 25 | return text 26 | } 27 | 28 | str := strings.Split(text, " ") 29 | 30 | strEncrypt := "" 31 | 32 | for _, v := range str { 33 | 34 | strEncrypt += fmt.Sprintf("%s ", encryptThis(v)) 35 | 36 | } 37 | 38 | return strings.TrimSpace(strEncrypt) 39 | } 40 | 41 | func encryptThis(text string) string { 42 | 43 | r := []rune(text) 44 | 45 | if len(text)-1 > 0 { 46 | r[1], r[len(text)-1] = r[len(text)-1], r[1] 47 | } 48 | 49 | rString := string(r) 50 | 51 | output := fmt.Sprintf("%d%s", r[0], rString[1:len(rString)]) 52 | 53 | return output 54 | } 55 | 56 | //func EncryptThis(text string) string { 57 | // 58 | // res := "" 59 | // 60 | // for _, word := range strings.Split(text, " ") { 61 | // for i, letter := range word { 62 | // switch i { 63 | // case 0: res += strconv.Itoa(int(letter)) 64 | // case 1: res += string(word[len(word)-1]) 65 | // case len(word)-1: res += string(word[1]) 66 | // default: 67 | // res += string(letter) 68 | // } 69 | // } 70 | // res += " " 71 | // } 72 | // return strings.TrimSpace(res) 73 | //} 74 | 75 | //func EncryptThis(text string) string { 76 | // if len(text) == 0 {return text} 77 | // words := strings.Split(text, " ") 78 | // for i, s := range words { 79 | // r := []rune(s) 80 | // n := len(r)-1 81 | // if n > 1 { r[1], r[n] = r[n], r[1] } 82 | // r = append([]rune(strconv.FormatInt(int64(r[0]), 10)), r[1:]...) 83 | // words[i] = string(r) 84 | // } 85 | // return strings.Join(words, " ") 86 | //} 87 | -------------------------------------------------------------------------------- /encrypt_this/encrypt_this_test.go: -------------------------------------------------------------------------------- 1 | package encrypt_this 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestEncryptThis(t *testing.T) { 9 | 10 | assert.Equal(t, EncryptThis("Hello"), "72olle") 11 | 12 | assert.Equal(t, EncryptThis("The more he saw the less he spoke"), "84eh 109ero 104e 115wa 116eh 108sse 104e 115eokp") 13 | 14 | assert.Equal(t, EncryptThis("Why can we not all be like that wise old bird"), "87yh 99na 119e 110to 97ll 98e 108eki 116tah 119esi 111dl 98dri") 15 | 16 | assert.Equal(t, EncryptThis("The more he saw the less he spoke"), "84eh 109ero 104e 115wa 116eh 108sse 104e 115eokp") 17 | 18 | assert.Equal(t, EncryptThis("Thank you Piotr for all your help"), "84kanh 121uo 80roti 102ro 97ll 121ruo 104ple") 19 | 20 | assert.Equal(t, EncryptThis("The less he spoke the more he heard"), "84eh 108sse 104e 115eokp 116eh 109ero 104e 104dare") 21 | 22 | } 23 | -------------------------------------------------------------------------------- /euler_method/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | k := 0.07 10 | tempRoom := 20. 11 | tempObject := 100. 12 | fcr := newCoolingRateDy(k, tempRoom) 13 | analytic := newTempFunc(k, tempRoom, tempObject) 14 | for _, deltaTime := range []float64{2, 5, 10} { 15 | fmt.Printf("Step size = %.1f\n", deltaTime) 16 | fmt.Println(" Time Euler's Analytic") 17 | temp := tempObject 18 | for time := 0.; time <= 100; time += deltaTime { 19 | fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time)) 20 | temp = eulerStep(fcr, time, temp, deltaTime) 21 | } 22 | fmt.Println() 23 | } 24 | 25 | } 26 | 27 | //fdy is a type for function f used in Euler's method 28 | type fdy func(float64, float64) float64 29 | 30 | //eulerStep computes a single new value using Euler's method 31 | func eulerStep(f fdy, x, y, h float64) float64 { 32 | return y + h*f(x, y) 33 | } 34 | 35 | //newTempFunc returns a funtion that computes the analytical cooling rate 36 | //for a given cooling rate constant k 37 | func newCoolingRate(k float64) func(float64) float64 { 38 | return func(deltaTemp float64) float64 { 39 | return -k * deltaTemp 40 | } 41 | } 42 | 43 | //newTempFunc returns a function that computes the analytical solution of cooling rate integrated over time 44 | func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 { 45 | return func(time float64) float64 { 46 | return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time) 47 | } 48 | } 49 | 50 | //newCoolingRateDy returns a function of the kind needed for Euler's method 51 | //That is a function representing dy(x, y(x)) 52 | 53 | func newCoolingRateDy(k, ambientTemp float64) fdy { 54 | crf := newCoolingRate(k) 55 | return func(_, objectTemp float64) float64 { 56 | return crf(objectTemp - ambientTemp) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /exp/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | 9 | //normal_http_call := "38494583" 10 | 11 | //mine := []string{"NBC", "BDE", "CXAOE", "OJO"} 12 | //for i := range mine { 13 | // fmt.Println(i) 14 | //} 15 | //arr := strings.Split(normal_http_call, "") 16 | //for i := 0; i < len(arr); i++ { 17 | // for j := 0; j < len(arr); j++ { 18 | // fmt.Println(arr[i]) 19 | // } 20 | //} 21 | //fmt.Println("this is a test: ", mine) 22 | 23 | testArray := []int{1, 2, 3, 5, 6, 7, 8} 24 | fmt.Println(testArray[:4]) 25 | fmt.Println(testArray[4:]) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /factorial/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("the fac: ", fac(5)) 7 | fmt.Println("the fib number: ", fib(7)) 8 | 9 | c := make(chan int) 10 | go fibSeries(c) 11 | for i := 0; i < 10; i++ { 12 | fmt.Println(<-c) 13 | } 14 | } 15 | 16 | //Write a function to return the factorial of a number. 17 | //Solutions can be iterative or recursive. 18 | //Recursion solution 19 | func fac(n int) int { 20 | if n < 2 { 21 | return 1 22 | } 23 | return n * fac(n-1) 24 | } 25 | 26 | func fib(a int) int { 27 | if a < 2 { 28 | return a 29 | } 30 | return fib(a-1) + fib(a-2) 31 | } 32 | 33 | func fibSeries(c chan int) { 34 | a, b := 0, 1 35 | for { 36 | c <- a 37 | a, b = b, a+b 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /factorial_decomposition/factorial_decomposition_test.go: -------------------------------------------------------------------------------- 1 | package factorial_decomposition_test 2 | 3 | import ( 4 | "efficient-algorithms/factorial_decomposition" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestDecomp(t *testing.T) { 10 | 11 | //assert.Equal(t, "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", factorial_decomposition.Decomp(17)) 12 | //assert.Equal(t, "2^3 * 3 * 5", factorial_decomposition.Decomp(5)) 13 | 14 | //assert.Equal(t, "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19", factorial_decomposition.Decomp(22)) 15 | 16 | assert.Equal(t, "2^11 * 3^5 * 5^2 * 7^2 * 11 * 13", factorial_decomposition.Decomp(14)) 17 | 18 | //assert.Equal(t, "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23", factorial_decomposition.Decomp(22)) 19 | //assert.Equal(t, "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23", factorial_decomposition.Decomp1(25)) 20 | 21 | //assert.Equal(t, "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", factorial_decomposition.Decomp1(17)) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /fib_optimized/fib_optimized.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | ) 8 | 9 | //This is from the work of @adeshinaHH 10 | 11 | func main() { 12 | 13 | fmt.Println("the main started") 14 | 15 | input := int64(10) 16 | 17 | //recursion 18 | start1 := time.Now() 19 | result1 := expensiveFib(input) 20 | defer trackTime(start1, result1, "Recursive for first function") 21 | fmt.Println() 22 | 23 | //forloop 24 | start2 := time.Now() 25 | result2 := FibByLoop(input) 26 | defer trackTime(start2, result2, "Forloop Implementation") 27 | fmt.Println() 28 | 29 | //memoization 30 | start3 := time.Now() 31 | val := memoize(expensiveFib) 32 | result3 := val(input) 33 | defer trackTime(start3, result3, "Memoization") 34 | 35 | } 36 | 37 | func expensiveFib(n int64) int64 { 38 | 39 | if n < 2 { 40 | return n 41 | } 42 | 43 | result := expensiveFib(n-1) + expensiveFib(n-2) 44 | 45 | return result 46 | } 47 | 48 | func FibByLoop(n int64) int64 { 49 | 50 | fibBox := []int64{0, 1} 51 | 52 | for i := int64(0); i < n; i++ { 53 | 54 | value := fibBox[i] + fibBox[i+1] 55 | 56 | fibBox = append(fibBox, value) 57 | } 58 | 59 | result := fibBox[n] 60 | 61 | return result 62 | } 63 | 64 | func trackTime(start time.Time, result int64, name string) { 65 | 66 | elapsed := time.Since(start) 67 | 68 | log.Printf("----> %s solution | result: %v | took: %s", name, result, elapsed) 69 | } 70 | 71 | type funcFib func(int64) int64 72 | 73 | func memoize(fn funcFib) func(int64) int64 { 74 | cache := make(map[int64]int64, 0) 75 | 76 | return func(n int64) int64 { 77 | if _, ok := cache[n]; ok { 78 | return cache[n] 79 | } 80 | result := fn(n) 81 | cache[n] = result 82 | 83 | return result 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /first_non_repeating/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string. 9 | //For example, if given the input 'stress', the function should return 't', since the letter t only occurs once in the string, and occurs first in the string. 10 | //As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'. 11 | //If a string contains all repeating characters, it should return an empty string ("") or None -- see sample tests. 12 | 13 | func main() { 14 | fmt.Println(FirstNoneRepeatinf("sTreSS")) 15 | } 16 | 17 | func FirstNoneRepeatinf(str string) string { 18 | for _, c := range str { 19 | if strings.Count(strings.ToLower(str), strings.ToLower(string(c))) < 2 { 20 | return string(c) 21 | } 22 | } 23 | return "" 24 | } 25 | -------------------------------------------------------------------------------- /fix_string_case/fix_string_case.go: -------------------------------------------------------------------------------- 1 | package fix_string_case 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | "unicode" 7 | ) 8 | 9 | //In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: 10 | // 11 | //make as few changes as possible. 12 | //if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase. 13 | //For example: 14 | // 15 | //solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase. 16 | //solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase. 17 | //solve("coDE") = "code". Upper == lowercase. Change all to lowercase. 18 | //More examples in test cases. Good luck! 19 | 20 | func Solve(str string) string { 21 | 22 | upperReg := regexp.MustCompile(`[A-Z][^A-Z]*`) 23 | 24 | up := upperReg.FindAllString(str, -1) 25 | 26 | lowerReg := regexp.MustCompile(`[a-z][^a-z]*`) 27 | 28 | low := lowerReg.FindAllString(str, -1) 29 | 30 | if len(up) > len(low) { 31 | return strings.ToUpper(str) 32 | } else { 33 | return strings.ToLower(str) 34 | } 35 | } 36 | 37 | func Solve2(str string) string { 38 | 39 | uppers := 0 40 | 41 | for _, rune := range str { 42 | if unicode.IsUpper(rune) { 43 | uppers++ 44 | } 45 | } 46 | if uppers > len(str)/2 { 47 | return strings.ToUpper(str) 48 | } 49 | 50 | return strings.ToLower(str) 51 | } 52 | -------------------------------------------------------------------------------- /fix_string_case/fix_string_case_test.go: -------------------------------------------------------------------------------- 1 | package fix_string_case_test 2 | 3 | import ( 4 | "efficient-algorithms/fix_string_case" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolve(t *testing.T) { 10 | 11 | assert.Equal(t, fix_string_case.Solve("Hello"), "normal_http_call") 12 | 13 | } 14 | -------------------------------------------------------------------------------- /fizzbuzz/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | //Write a program that prints the integers from 1 to 100 (inclusive). 9 | // 10 | //But: 11 | // 12 | //for multiples of three, print Fizz (instead of the number) 13 | //for multiples of five, print Buzz (instead of the number) 14 | //for multiples of both three and five, print FizzBuzz (instead of the number) 15 | // 16 | //The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy. 17 | 18 | func main() { 19 | fmt.Println(fizzBuzz(15)) 20 | } 21 | 22 | func fizzBuzz(n int) []string { 23 | 24 | result := []string{} 25 | for i := 1; i <= n; i++ { 26 | switch { 27 | case i%3 == 0 && i%5 == 0: 28 | result = append(result, "FizzBuzz") 29 | case i%3 == 0: 30 | result = append(result, "Fizz") 31 | case i%5 == 0: 32 | result = append(result, "Buzz") 33 | default: 34 | result = append(result, strconv.Itoa(i)) 35 | } 36 | } 37 | return result 38 | } 39 | -------------------------------------------------------------------------------- /flag/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | ) 7 | 8 | var ip string 9 | var port int 10 | 11 | func init() { 12 | flag.StringVar(&ip, "ip", "0.0.0.0", "ip address") 13 | flag.IntVar(&port, "port", 8000, "port number") 14 | } 15 | 16 | func main() { 17 | flag.Parse() 18 | fmt.Printf("%s:%d", ip, port) 19 | } 20 | -------------------------------------------------------------------------------- /friend_cheating/friend_cheating.go: -------------------------------------------------------------------------------- 1 | package friend_cheating 2 | 3 | //A friend of mine takes a sequence of numbers from 1 to n (where n > 0). 4 | //Within that sequence, he chooses two numbers, a and b. 5 | //He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b. 6 | //Given a number n, could you tell me the numbers he excluded from the sequence? 7 | //The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string (depending on the language) of the form: 8 | // 9 | //[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or or [{a, b}, ...] 10 | //with all (a, b) which are the possible removed numbers in the sequence 1 to n. 11 | // 12 | //[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or ...will be sorted in increasing order of the "a". 13 | // 14 | //It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth! (Go: in this case return nil). 15 | // 16 | //(See examples of returns for each language in "RUN SAMPLE TESTS") 17 | // 18 | //Examples: 19 | //removNb(26) should return [(15, 21), (21, 15)] 20 | //or 21 | // 22 | //removNb(26) should return { {15, 21}, {21, 15} } 23 | //or 24 | // 25 | //removeNb(26) should return [[15, 21], [21, 15]] 26 | //or 27 | // 28 | //removNb(26) should return [ {15, 21}, {21, 15} ] 29 | //or 30 | // 31 | //removNb(26) should return "15 21, 21 15" 32 | //or 33 | // 34 | //in C: 35 | //removNb(26) should return **an array of pairs {{15, 21}{21, 15}}** 36 | //tested by way of strings. 37 | 38 | func RemovNb(m uint64) [][2]uint64 { 39 | n := m 40 | var sum uint64 = n * (n + 1) / 2 41 | var res [][2]uint64 42 | for a := uint64(1); a <= n; a++ { 43 | if (sum-a)%(a+1) == 0 { 44 | b := (sum - a) / (a + 1) 45 | if b < n { 46 | res = append(res, [2]uint64{a, b}) 47 | } 48 | } 49 | } 50 | return res 51 | } 52 | -------------------------------------------------------------------------------- /friend_cheating/friend_cheating_test.go: -------------------------------------------------------------------------------- 1 | package friend_cheating_test 2 | 3 | import ( 4 | "efficient-algorithms/friend_cheating" 5 | "fmt" 6 | "github.com/stretchr/testify/assert" 7 | "testing" 8 | ) 9 | 10 | func TestRemovNb(t *testing.T) { 11 | 12 | ans := friend_cheating.RemovNb(26) 13 | fmt.Println("Our ans: ", ans) 14 | 15 | assert.Equal(t, friend_cheating.RemovNb(101), [][2]uint64{{55, 91}, {91, 55}}) 16 | assert.Equal(t, friend_cheating.RemovNb(102), [][2]uint64{{70, 73}, {73, 70}}) 17 | assert.Equal(t, friend_cheating.RemovNb(110), [][2]uint64{{70, 85}, {85, 70}}) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /gap_in_primes/gap_in_primes_test.go: -------------------------------------------------------------------------------- 1 | package gap_in_primes 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestGap(t *testing.T) { 9 | 10 | //assert.Equal(t, AllPossiblePrimes(20), []int{2, 3, 5, 7, 11, 13, 17, 19}) 11 | 12 | //assert.Equal(t, Gap(2, 3, 50), []int{3, 5}) 13 | //assert.Equal(t, Gap(2,100,110), []int{101, 103}) 14 | //assert.Equal(t, Gap(4,100,110), []int{103, 107}) 15 | assert.Equal(t, Gap(6, 100, 110), nil) 16 | //assert.Equal(t, Gap(8,300,400), []int{359, 367}) 17 | //assert.Equal(t, Gap(10,300,400), []int{337, 347}) 18 | 19 | //dotest(2,100,110, []int{101, 103}) 20 | //dotest(4,100,110, []int{103, 107}) 21 | //dotest(6,100,110, nil) 22 | //dotest(8,300,400, []int{359, 367}) 23 | //dotest(10,300,400, []int{337, 347}) 24 | 25 | } 26 | -------------------------------------------------------------------------------- /generate_string/generate_string.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //Generate a string consisting of characters ‘a’ and ‘b’ that satisfy the given conditions 6 | 7 | //Given two integers A and B, the task is to generate and print a string str such that: 8 | // 9 | //str must only contain the characters ‘a’ and ‘b’. 10 | //str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to B 11 | //The sub-strings “aaa” or “bbb” must not occur in str. 12 | //Note that for the given values of A and B, a valid string can always be generated. 13 | 14 | //Examples: 15 | // 16 | //Input: A = 1, B = 2 17 | //Output: abb 18 | //“abb”, “bab” and “bba” are all valid strings. 19 | // 20 | //Input: A = 4, B = 1 21 | //Output: aabaa 22 | 23 | func generateString(A int, B int) string { 24 | 25 | rt := "" 26 | 27 | for A > 0 || B > 0 { 28 | //more 'b' , append "bba" 29 | if A < B { 30 | B-- 31 | if 0 < B { 32 | rt += "b" 33 | } 34 | A-- 35 | if 0 < A { 36 | rt += "a" 37 | } 38 | //More 'a', append "aab" 39 | } else if B < A { 40 | A-- 41 | if 0 < A { 42 | rt += "a" 43 | } 44 | B-- 45 | if 0 < B { 46 | rt += "b" 47 | } 48 | //equal number of 'a' and 'b', append "ab" 49 | } else { 50 | A-- 51 | if 0 < A { 52 | rt += "a" 53 | } 54 | B-- 55 | if 0 < B { 56 | rt += "b" 57 | } 58 | } 59 | } 60 | return rt 61 | } 62 | 63 | func main() { 64 | ans := generateString(2, 6) 65 | fmt.Println(ans) 66 | } 67 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module efficient-algorithms 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/stretchr/testify v1.6.1 7 | golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 7 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 8 | golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf h1:B2n+Zi5QeYRDAEodEu72OS36gmTWjgpXr2+cWcBW90o= 9 | golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= 10 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 11 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 12 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 13 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 14 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 15 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 16 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 17 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 18 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 19 | -------------------------------------------------------------------------------- /go_max_procs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | ) 8 | 9 | func main() { 10 | const GOMAXPROCS = 1 //A 11 | runtime.GOMAXPROCS(GOMAXPROCS) 12 | 13 | var wg sync.WaitGroup 14 | wg.Add(2) 15 | 16 | go func() { 17 | defer wg.Done() 18 | for char := 0; char < 26; char++ { 19 | fmt.Printf("%c ", 'A'+char) 20 | } 21 | }() 22 | go func() { 23 | defer wg.Done() 24 | for char := 0; char < 26; char++ { 25 | fmt.Printf("%c ", 'a'+char) 26 | } 27 | }() 28 | 29 | fmt.Println("main executed") 30 | 31 | wg.Wait() 32 | } 33 | -------------------------------------------------------------------------------- /going_to_the_cinema/going_to_the_cinema.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | //My friend John likes to go to the cinema. He can choose between system A and system B. 8 | // 9 | //System A : he buys a ticket (15 dollars) every time 10 | //System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price, 11 | //then for each additional ticket he pays 0.90 times the price paid for the previous ticket. 12 | //#Example: If John goes to the cinema 3 times: 13 | // 14 | //System A : 15 * 3 = 45 15 | //System B : 500 + 15 * 0.90 + (15 * 0.90) * 0.90 + (15 * 0.90 * 0.90) * 0.90 ( = 536.5849999999999, no rounding for each ticket) 16 | //John wants to know how many times he must go to the cinema so that the final result of System B, when rounded up to the next dollar, will be cheaper than System A. 17 | // 18 | //The function movie has 3 parameters: card (price of the card), ticket (normal price of a ticket), perc (fraction of what he paid for the previous ticket) and returns the first n such that 19 | // 20 | //ceil(price of System B) < price of System A. 21 | //More examples: 22 | // 23 | //movie(500, 15, 0.9) should return 43 24 | // (with card the total price is 634, with tickets 645) 25 | //movie(100, 10, 0.95) should return 24 26 | // (with card the total price is 235, with tickets 240) 27 | 28 | func Movie(card, ticket int, perc float64) (count int) { 29 | 30 | var systemA float64 31 | 32 | systemB := float64(card) 33 | 34 | for systemA <= math.Ceil(systemB) { 35 | count++ 36 | systemA = float64(ticket * count) 37 | systemB += float64(ticket) * math.Pow(perc, float64(count)) 38 | } 39 | 40 | return count 41 | } 42 | -------------------------------------------------------------------------------- /going_to_the_cinema/going_to_the_cinema_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestMovie(t *testing.T) { 9 | 10 | assert.Equal(t, Movie(500, 15, 0.9), 43) 11 | 12 | assert.Equal(t, Movie(100, 10, 0.95), 24) 13 | 14 | } 15 | -------------------------------------------------------------------------------- /growing_plant/growing_plant_test.go: -------------------------------------------------------------------------------- 1 | package growing_plant 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestGrowingPlant(t *testing.T) { 9 | 10 | assert.Equal(t, GrowingPlant(100, 10, 910), 10) 11 | assert.Equal(t, GrowingPlant(10, 9, 4), 1) 12 | assert.Equal(t, GrowingPlant2(5, 2, 6), 2) 13 | assert.Equal(t, GrowingPlant3(72, 2, 369), 6) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /heap_example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | //str := "normal_http_call, Sam, how are you today. Alice, good to me you" 10 | //fmt.Println(vowel(str)) 11 | h := &intHeap{6, 2, 1, 5} 12 | heap.Init(h) 13 | for h.Len() > 0 { 14 | fmt.Printf("%d", heap.Pop(h)) 15 | } 16 | } 17 | 18 | type intHeap []int 19 | 20 | func (h intHeap) Len() int { 21 | return len(h) 22 | } 23 | func (h intHeap) Less(i, j int) bool { 24 | return h[i] < h[j] 25 | } 26 | 27 | func (h intHeap) Swap(i, j int) { 28 | h[i], h[j] = h[j], h[i] 29 | } 30 | 31 | func (h *intHeap) Push(x interface{}) { 32 | *h = append(*h, x.(int)) 33 | } 34 | 35 | func (h *intHeap) Pop() interface{} { 36 | old := *h 37 | n := len(old) 38 | x := old[n-1] 39 | *h = old[0 : n-1] 40 | return x 41 | } 42 | -------------------------------------------------------------------------------- /help_your_granny/Screenshot 2020-09-12 at 19.44.37.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/help_your_granny/Screenshot 2020-09-12 at 19.44.37.png -------------------------------------------------------------------------------- /help_your_granny/help_your_granny_test.go: -------------------------------------------------------------------------------- 1 | package help_your_granny_test 2 | 3 | import ( 4 | "efficient-algorithms/help_your_granny" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestTour(t *testing.T) { 10 | assert.Equal(t, help_your_granny.Tour(), "") 11 | } 12 | -------------------------------------------------------------------------------- /howmuch/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("this is the result: ", HowMuch(1, 100)) 10 | } 11 | 12 | func HowMuch(m int, n int) [][3]string { 13 | var results [][3]string 14 | 15 | if m > n { 16 | m, n = n, m 17 | } 18 | 19 | for i := m; i <= n; i++ { 20 | if (i-1)%9 == 0 && (i-2)%7 == 0 { 21 | results = append(results, [3]string{ 22 | "M: " + strconv.Itoa(i), 23 | "B: " + strconv.Itoa((i-2)/7), 24 | "C: " + strconv.Itoa((i-1)/9), 25 | }) 26 | } 27 | } 28 | return results 29 | } 30 | -------------------------------------------------------------------------------- /http_server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func main() { 10 | mux := http.NewServeMux() 11 | mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 12 | fmt.Fprintf(w, "Hello\n") 13 | }) 14 | log.Fatal(http.ListenAndServe(":8080", mux)) 15 | 16 | http.HandleFunc("/me", func(w http.ResponseWriter, req *http.Request){ 17 | fmt.Fprintf(w, "Hello") 18 | }) 19 | } 20 | 21 | //something else 22 | //func ore() { 23 | // 24 | // age := 27 25 | // rows, err := db.Query("SELECT name FROM users WHERE age=?", age) 26 | // if err != nil { 27 | // log.Fatal(err) 28 | // } 29 | // defer rows.Close() // A 30 | // for rows.Next() { //B 31 | // var name string 32 | // if err := rows.Scan(&name); err != nil { //C 33 | // log.Fatal(err) 34 | // } 35 | // fmt.Printf("%s is %d\n", name, age) 36 | // } 37 | // if err := rows.Err(); err != nil { //D 38 | // log.Fatal(err) 39 | // } 40 | //} 41 | -------------------------------------------------------------------------------- /init/main.go: -------------------------------------------------------------------------------- 1 | // A/a1.go 2 | package A 3 | 4 | func init() { 5 | println("a1") 6 | } 7 | 8 | var A1 = "" 9 | 10 | // A/a2.go 11 | //package A 12 | //func init() { 13 | // println("a2") 14 | //} 15 | //var A2 = "" 16 | // 17 | // 18 | //// B/b1.go 19 | //package B 20 | //func init() { 21 | // println("b1") 22 | //} 23 | //var B1 = "" 24 | // 25 | // 26 | //// B/b2.go 27 | //package B 28 | //import "github.com/test/A" 29 | //func init() { 30 | // println("b2") 31 | //} 32 | //func f() { 33 | // _ = A.A2 34 | //} 35 | //var B2 = "" 36 | // 37 | // 38 | //// C/main.go 39 | //package main 40 | //import ( 41 | //"github.com/test/B" 42 | //) 43 | //func main() { 44 | // _ = B.B2 45 | //} 46 | -------------------------------------------------------------------------------- /interface_checking/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(intCast(23)) 7 | fmt.Println(stringCast(23)) 8 | } 9 | 10 | //checking if the interface input type is an int 11 | func intCast(x interface{}) int { 12 | if v, ok := x.(int); ok { 13 | return v 14 | } else { 15 | return -1 //if not, return -1 16 | } 17 | } 18 | 19 | //checking if the interface input type is a string 20 | func stringCast(x interface{}) string { 21 | if str, ok := x.(string); ok { 22 | return str 23 | } else { 24 | return "cant be converted" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /internals/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unsafe" 6 | ) 7 | 8 | func main() { 9 | //var b = []byte("123") 10 | //string_internals(b) 11 | x := 1 12 | 13 | y := &x 14 | 15 | fmt.Println(*y) 16 | 17 | *y = 2 18 | 19 | fmt.Println(x) 20 | 21 | const ( 22 | i = 7 23 | 24 | j 25 | 26 | k 27 | ) 28 | fmt.Println(i, j, k) 29 | 30 | a := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9} 31 | 32 | // creates new slice 33 | 34 | s := a[2:4] 35 | 36 | fmt.Println(s) 37 | 38 | //var v []int 39 | 40 | v := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9} 41 | 42 | s = v[2:4] 43 | 44 | fmt.Println(cap(s)) 45 | fmt.Println(len(s)) 46 | 47 | fmt.Println(&v[2] == &s[0]) 48 | 49 | s[0] = 33 50 | 51 | fmt.Println(a[2]) 52 | 53 | newS := append(s, 55, 66) 54 | 55 | fmt.Printf("len=%d, cap=%d\n", len(newS), cap(newS)) 56 | 57 | h := []int{1, 2, 3, 4, 5, 6} 58 | 59 | h = append(h, 7, 8) 60 | 61 | fmt.Println(len(h)) 62 | 63 | //fmt.Printf("len=%d, len(h)) 64 | 65 | s2 := []int{1, 2, 3} 66 | 67 | s3 := []int{4, 5, 6, 7} 68 | 69 | n2 := copy(s2, s3) 70 | 71 | fmt.Printf("n2=%d, s2=%v, s3=%v\n", n2, s2, s3) 72 | 73 | } 74 | 75 | //to convert b from []byte to string without causing memory copy 76 | func string_internals(b []byte) { 77 | s := *(*string)(unsafe.Pointer(&b)) 78 | 79 | b[1] = '4' 80 | fmt.Printf("%+v. And the type is: %T\n ", s, s) 81 | } 82 | -------------------------------------------------------------------------------- /isPrime/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(isPrime(6)) 7 | fmt.Println(isPrime(7)) 8 | fmt.Println(isPrime(9)) 9 | fmt.Println(isPrime(2)) 10 | } 11 | 12 | func isPrime(n int) bool { 13 | if n < 2 { 14 | return false 15 | } 16 | for i := 2; i <= n/2; i++ { 17 | if n%i == 0 { 18 | return false 19 | } 20 | } 21 | return true 22 | } 23 | -------------------------------------------------------------------------------- /isbn_10_validation/isbn_10_validation.go: -------------------------------------------------------------------------------- 1 | package isbn_10_validation 2 | 3 | //ISBN-10 identifiers are ten digits long. The first nine characters are digits 0-9. The last digit can be 0-9 or X, to indicate a value of 10. 4 | // 5 | //An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero. 6 | // 7 | //For example: 8 | // 9 | //ISBN : 1 1 1 2 2 2 3 3 3 9 10 | //position : 1 2 3 4 5 6 7 8 9 10 11 | //This is a valid ISBN, because: 12 | // 13 | //(1*1 + 1*2 + 1*3 + 2*4 + 2*5 + 2*6 + 3*7 + 3*8 + 3*9 + 9*10) % 11 = 0 14 | //Examples 15 | //1112223339 --> true 16 | //111222333 --> false 17 | //1112223339X --> false 18 | //1234554321 --> true 19 | //1234512345 --> false 20 | //048665088X --> true 21 | //X123456788 --> false 22 | 23 | 24 | 25 | func ValidISBN10(isbn string) bool { 26 | if len(isbn) < 10 { 27 | return false 28 | } 29 | 30 | var sum int 31 | for i, v := range isbn { 32 | if i == 9 && (v == 'X' || v == 'x') { 33 | sum += 100 34 | } else if v < '0' || v > '9' { 35 | return false 36 | } else { 37 | sum += int(v - '0') * (i + 1) 38 | } 39 | } 40 | 41 | return sum % 11 == 0 42 | } 43 | -------------------------------------------------------------------------------- /isbn_10_validation/isbn_10_validation_test.go: -------------------------------------------------------------------------------- 1 | package isbn_10_validation 2 | 3 | import "testing" 4 | 5 | func TestValidISBN10(t *testing.T) { 6 | 7 | ValidISBN10("1112223339") 8 | } 9 | -------------------------------------------------------------------------------- /josephus/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | ans := jose(7, 3) 7 | fmt.Println(ans) 8 | } 9 | 10 | func josephus_survivor(people, elim int) int { 11 | if people == 1 { 12 | return 1 13 | } else { 14 | return (josephus_survivor(people-1, elim)+elim-1)%people + 1 15 | } 16 | } 17 | 18 | //Solution 2: 19 | func jose(n, k int) int { 20 | survivor := 0 21 | for i := 1; i < n; i++ { 22 | survivor = (survivor + k) % (i + 1) 23 | } 24 | return survivor + 1 25 | } 26 | -------------------------------------------------------------------------------- /json_unmarshaling/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type Result struct { 9 | Status int `json:"status"` 10 | } 11 | 12 | func main() { 13 | var data = []byte(`{"status": 200}`) 14 | var result = Result{} 15 | 16 | if err := json.Unmarshal(data, &result); err != nil { 17 | fmt.Println("error: ", err) 18 | return 19 | } 20 | fmt.Printf("result=%+v\n", result) 21 | } 22 | -------------------------------------------------------------------------------- /leetcode_problems/add_two_numbers/add_two_numbers.go: -------------------------------------------------------------------------------- 1 | package add_two_numbers 2 | 3 | // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 4 | // 5 | //You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | // Input: l1 = [2,4,3], l2 = [5,6,4] 8 | //Output: [7,0,8] 9 | //Explanation: 342 + 465 = 807. 10 | //Example 2: 11 | // 12 | //Input: l1 = [0], l2 = [0] 13 | //Output: [0] 14 | //Example 3: 15 | // 16 | //Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 17 | //Output: [8,9,9,9,0,0,0,1] 18 | 19 | // Constraints: 20 | // 21 | //The number of nodes in each linked list is in the range [1, 100]. 22 | //0 <= Node.val <= 9 23 | //It is guaranteed that the list represents a number that does not have leading zeros. 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * type ListNode struct { 28 | * Val int 29 | * Next *ListNode 30 | * } 31 | */ 32 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 33 | 34 | } 35 | -------------------------------------------------------------------------------- /leetcode_problems/longest_common_prefix/longest_common_prefix.go: -------------------------------------------------------------------------------- 1 | package longest_common_prefix 2 | 3 | // Write a function to find the longest common prefix string amongst an array of strings. 4 | // 5 | //If there is no common prefix, return an empty string "". 6 | // 7 | // 8 | // 9 | //Example 1: 10 | // 11 | //Input: strs = ["flower","flow","flight"] 12 | //Output: "fl" 13 | //Example 2: 14 | // 15 | //Input: strs = ["dog","racecar","car"] 16 | //Output: "" 17 | //Explanation: There is no common prefix among the input strings. 18 | // 19 | // 20 | //Constraints: 21 | // 22 | //0 <= strs.length <= 200 23 | //0 <= strs[i].length <= 200 24 | //strs[i] consists of only lower-case English letters. 25 | 26 | func longestCommonPrefix(strs []string) string { 27 | 28 | if len(strs) == 0 { 29 | return "" 30 | } 31 | for i := 1; i < len(strs[0]); i++ { 32 | c := strs[0][i] 33 | for j := 1; j < len(strs); j++ { 34 | if i == len(strs[j]) || strs[j][i] != c { 35 | return strs[0][0:i] 36 | } 37 | } 38 | } 39 | return strs[0] 40 | } -------------------------------------------------------------------------------- /leetcode_problems/longest_common_prefix/longest_common_prefix_test.go: -------------------------------------------------------------------------------- 1 | package longest_common_prefix 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestLongestCommonPrefix(t *testing.T) { 9 | 10 | strs := []string{"flower","flow","flight"} 11 | 12 | fmt.Println(longestCommonPrefix(strs)) 13 | } 14 | -------------------------------------------------------------------------------- /leetcode_problems/longest_substring/longest_substring_test.go: -------------------------------------------------------------------------------- 1 | package longest_substring 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestLengthOfLongestSubstring(t *testing.T) { 9 | 10 | //assert.Equal(t, 3, LengthOfLongestSubstring("abcabcbb")) 11 | //assert.Equal(t, 1, LengthOfLongestSubstring("bbbbb")) 12 | 13 | //assert.Equal(t, 3, LengthOfLongestSubstring2("abcabcbb")) 14 | assert.Equal(t, 1, LengthOfLongestSubstring3("bbbbb")) 15 | assert.Equal(t, 3, LengthOfLongestSubstring3("abcabcbb")) 16 | } 17 | -------------------------------------------------------------------------------- /leetcode_problems/longest_substring_without_repeatition/longest_substring_without_repeatition_test.go: -------------------------------------------------------------------------------- 1 | package longest_substring_without_repeatition 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLongestSubstring(t *testing.T) { 8 | 9 | if lengthOfLongestSubstring("abcabcbb") != 3 { 10 | t.Errorf("Want %d, got %d", 3, lengthOfLongestSubstring4("abcabcbb")) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /leetcode_problems/palindrome_number/palindrome_number.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "strconv" 7 | ) 8 | 9 | // Given an integer x, return true if x is palindrome integer. 10 | // 11 | //An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not. 12 | // 13 | // 14 | // 15 | //Example 1: 16 | // 17 | //Input: x = 121 18 | //Output: true 19 | //Example 2: 20 | // 21 | //Input: x = -121 22 | //Output: false 23 | //Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 24 | //Example 3: 25 | // 26 | //Input: x = 10 27 | //Output: false 28 | //Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 29 | //Example 4: 30 | // 31 | //Input: x = -101 32 | //Output: false 33 | // 34 | // 35 | //Constraints: 36 | // 37 | //-231 <= x <= 231 - 1 38 | // 39 | // 40 | //Follow up: Could you solve it without converting the integer to a string? 41 | 42 | func isPalindrome(x int) bool { 43 | 44 | s := strconv.Itoa(x) 45 | runes := make([]rune, 0) 46 | 47 | if x < 0 { 48 | s = s[1:] 49 | runes = []rune(s) 50 | } else { 51 | runes = []rune(s) 52 | } 53 | for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 54 | runes[i], runes[j] = runes[j], runes[i] 55 | } 56 | 57 | result := string(runes) 58 | 59 | resultNum, _ := strconv.Atoi(result) 60 | if x < 0 { 61 | resultNum = resultNum * -1 62 | } 63 | if float64(resultNum) < math.Pow(-2, 31) || float64(resultNum) > math.Pow(2, 31) { 64 | return false 65 | } 66 | 67 | if x < 0 { 68 | result = fmt.Sprintf("%v%v", result, "-") 69 | } 70 | 71 | return result == s 72 | } 73 | -------------------------------------------------------------------------------- /leetcode_problems/palindrome_number/palindrome_number_test.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestPalindromeNumber(t *testing.T) { 8 | 9 | if isPalindrome(121) == false { 10 | t.Errorf("121 is not a palindrome") 11 | } 12 | } 13 | 14 | func TestPalindromeNumber2(t *testing.T) { 15 | 16 | if isPalindrome(-121) == true { 17 | t.Errorf("-121 is not a palindrome") 18 | } 19 | } 20 | 21 | func TestPalindromeNumber3(t *testing.T) { 22 | 23 | if isPalindrome(10) == true { 24 | t.Errorf("10 is not a palindrome") 25 | } 26 | } 27 | 28 | func TestPalindromeNumber4(t *testing.T) { 29 | 30 | if isPalindrome(-101) == true { 31 | t.Errorf("-101 is not a palindrome") 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode_problems/reverse_integer/reverse_integer.go: -------------------------------------------------------------------------------- 1 | package reverse_integer 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | // Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 9 | // 10 | //Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 11 | // 12 | // 13 | // 14 | //Example 1: 15 | // 16 | //Input: x = 123 17 | //Output: 321 18 | //Example 2: 19 | // 20 | //Input: x = -123 21 | //Output: -321 22 | //Example 3: 23 | // 24 | //Input: x = 120 25 | //Output: 21 26 | //Example 4: 27 | // 28 | //Input: x = 0 29 | //Output: 0 30 | // 31 | // 32 | //Constraints: 33 | // 34 | //-2^31 <= x <= 2^31 - 1 35 | 36 | func reverse(x int) int { 37 | 38 | runes := make([]rune, 0) 39 | str := strconv.Itoa(x) 40 | if x < 0 { 41 | str = str[1:] // remove the minus sign 42 | runes = []rune(str) 43 | } else { 44 | runes = []rune(str) 45 | } 46 | 47 | for i, j := 0, len(runes)-1; i < j; i, j = i + 1, j-1 { 48 | runes[i], runes[j] = runes[j], runes[i] 49 | } 50 | 51 | y, _ := strconv.Atoi(string(runes)) 52 | 53 | if float64(y) < math.Pow(-2, 31) || float64(y) > math.Pow(2, 31) { 54 | return 0 55 | } 56 | 57 | if x < 0 { 58 | return y * -1 59 | } 60 | return y 61 | } 62 | -------------------------------------------------------------------------------- /leetcode_problems/reverse_integer/reverse_integer_test.go: -------------------------------------------------------------------------------- 1 | package reverse_integer 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestReverseInteger(t *testing.T) { 9 | 10 | fmt.Println(reverse(1534236469)) 11 | 12 | //fmt.Println(reverse(-123)) 13 | 14 | //fmt.Println(reverse(120)) 15 | // 16 | //fmt.Println(reverse(0)) 17 | } 18 | -------------------------------------------------------------------------------- /leetcode_problems/two_sum/two_sum_test.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestTwoSum(t *testing.T) { 9 | 10 | assert.Equal(t, []int{0, 1}, TwoSum([]int{2, 7, 11, 15}, 9)) 11 | assert.Equal(t, []int{1, 2}, TwoSum([]int{3, 2, 4}, 6)) 12 | 13 | assert.Equal(t, []int{0, 1}, TwoSum2([]int{2, 7, 11, 15}, 9)) 14 | 15 | assert.Equal(t, []int{0, 1}, TwoSum2a([]int{2, 7, 11, 15}, 9)) 16 | 17 | assert.Equal(t, []int{1, 2}, TwoSum2([]int{3, 2, 4}, 6)) 18 | 19 | assert.Equal(t, []int{0, 1}, TwoSum3([]int{2, 7, 11, 15}, 9)) 20 | assert.Equal(t, []int{1, 2}, TwoSum3([]int{3, 2, 4}, 6)) 21 | 22 | assert.Equal(t, []int{1, 2}, TwoSum3a([]int{3, 2, 4}, 6)) 23 | assert.Equal(t, []int{1, 2}, TwoSum3b([]int{3, 2, 4}, 6)) 24 | 25 | } 26 | -------------------------------------------------------------------------------- /leetcode_problems/valid_parentheses/valid_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestValidParentheses(t *testing.T) { 9 | 10 | fmt.Println(isValid4("()[]{}")) 11 | } -------------------------------------------------------------------------------- /lowercase/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(alpha("THEgenaway mine own HELLObo")) 10 | } 11 | 12 | //get only the lowercase letters 13 | func alpha(str string) string { 14 | //re := regexp.MustCompile("[]") 15 | var allLowerCase = regexp.MustCompile(`[^[:lower:]]`) 16 | 17 | str = allLowerCase.ReplaceAllString(str, " ") 18 | 19 | return str 20 | } 21 | -------------------------------------------------------------------------------- /max_length_diff/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func main() { 6 | 7 | } 8 | 9 | //You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array. 10 | //Example: 11 | // 12 | //longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta" 13 | // 14 | //n being the length of the string array, if n = 0 or k > n or k <= 0 return "". 15 | 16 | func MxDifLg(a1 []string, a2 []string) int { 17 | 18 | if len(a1) == 0 || len(a2) == 0 { 19 | return -1 20 | } 21 | var max = 0 22 | for i := 0; i < len(a1); i++ { 23 | for j := 0; j < len(a2); j++ { 24 | var diff = int(math.Abs(float64(len(a1[i])) - float64(len(a2[j])))) 25 | if diff > max { 26 | max = diff 27 | } 28 | } 29 | } 30 | return max 31 | } 32 | -------------------------------------------------------------------------------- /max_number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | A := []int{20, 2, 16, 4, 6, 7, 34, 2, 9, 15, 5} 7 | fmt.Println(max_num(A)) 8 | } 9 | 10 | func max_num(arr []int) int { 11 | 12 | maxnumber := arr[0] 13 | for i := 0; i < len(arr); i++ { 14 | if arr[i] > maxnumber { 15 | maxnumber = arr[i] 16 | } 17 | } 18 | return maxnumber 19 | } 20 | -------------------------------------------------------------------------------- /max_subarray/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | A := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} 7 | fmt.Println("max sum: ", max_subarray(A)) 8 | fmt.Println("max sum: ", max_subarray_2(A)) 9 | 10 | //fmt.Println(max_subarray_plus(A)) 11 | //fmt.Println() 12 | } 13 | 14 | //The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: 15 | //maxSequence [-2, 1, -3, 4, -1, 2, 1, -5, 4] 16 | //-- should be 6: [4, -1, 2, 1] 17 | 18 | //Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead. 19 | 20 | //Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray. 21 | 22 | func max_subarray(numbers []int) int { 23 | var best, sum int 24 | for _, x := range numbers { 25 | sum += x 26 | //fmt.Printf("The current %d and the sum %d \n", x, sum) 27 | //fmt.Println(sum) 28 | switch { 29 | case sum > best: 30 | best = sum 31 | case sum < 0: 32 | sum = 0 33 | } 34 | } 35 | return best 36 | } 37 | 38 | //Another approach 39 | func max_subarray_2(numbers []int) int { 40 | max, curr := 0, 0 41 | for _, v := range numbers { 42 | if curr += v; curr < 0 { 43 | curr = 0 44 | } else if curr > max { 45 | max = curr 46 | } 47 | } 48 | return max 49 | } 50 | 51 | //Return both the filtered array 52 | func max_subarray_plus(numbers []int) ([]int, int) { 53 | 54 | var best, start, end, sum, sumStart int 55 | for i, x := range numbers { 56 | sum += x 57 | switch { 58 | case sum > best: 59 | best = sum 60 | start = sumStart 61 | end = i + 1 62 | case sum < 0: 63 | sum = 0 64 | sumStart = i + 1 65 | } 66 | } 67 | return numbers[start:end], best 68 | } 69 | -------------------------------------------------------------------------------- /mean/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(sum(10)) 10 | 11 | str := "This is the awesome birthday here. Okay" 12 | fmt.Println(vowel(str)) 13 | 14 | } 15 | 16 | func sum(n int) float64 { 17 | ans := 0 18 | for i := 1; i <= n; i++ { 19 | ans += i * i 20 | } 21 | //the mean: 22 | mean := math.Sqrt(float64(ans / n)) 23 | 24 | return mean 25 | } 26 | 27 | //count the vowels in a word 28 | 29 | func vowel(str string) int { 30 | count := 0 31 | for _, v := range str { 32 | switch v { 33 | case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U': 34 | count++ 35 | } 36 | } 37 | return count 38 | } 39 | -------------------------------------------------------------------------------- /mexican_wave/mexican_wave.go: -------------------------------------------------------------------------------- 1 | package mexican_wave 2 | 3 | import "strings" 4 | 5 | //Introduction 6 | //The wave (known as the Mexican wave in the English-speaking world outside North America) is an example of metachronal rhythm achieved in a packed stadium when successive groups of spectators briefly stand, yell, and raise their arms. Immediately upon stretching to full height, the spectator returns to the usual seated position. 7 | // 8 | //The result is a wave of standing spectators that travels through the crowd, even though individual spectators never move away from their seats. In many large arenas the crowd is seated in a contiguous circuit all the way around the sport field, and so the wave is able to travel continuously around the arena; in discontiguous seating arrangements, the wave can instead reflect back and forth through the crowd. When the gap in seating is narrow, the wave can sometimes pass through it. Usually only one wave crest will be present at any given time in an arena, although simultaneous, counter-rotating waves have been produced. (Source Wikipedia) 9 | //Task 10 | //In this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up. 11 | //Rules 12 | // 1. The input string will always be lower case but maybe empty. 13 | // 14 | // 2. If the character in the string is whitespace then pass over it as if it was an empty seat 15 | //Example 16 | //wave("normal_http_call") => []string{"Hello", "hEllo", "heLlo", "helLo", "hellO"} 17 | 18 | func Wave(words string) []string { 19 | 20 | result := []string{} 21 | //result := make([]string, 0) 22 | 23 | for i, letter := range words { 24 | if letter == ' ' { 25 | continue 26 | } 27 | //upperLetter := string(letter - 'a' + 'A') //or 28 | upperLetter := strings.ToUpper(string(letter)) 29 | 30 | result = append(result, words[:i]+upperLetter+words[i+1:]) 31 | } 32 | 33 | return result 34 | } 35 | -------------------------------------------------------------------------------- /mexican_wave/mexican_wave_test.go: -------------------------------------------------------------------------------- 1 | package mexican_wave 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestWave(t *testing.T) { 9 | 10 | assert.Equal(t, Wave("normal_http_call"), []string{"Hello", "hEllo", "heLlo", "helLo", "hellO"}) 11 | 12 | assert.Equal(t, Wave(" x yz"), []string{" X yz", " x Yz", " x yZ"}) 13 | 14 | assert.Equal(t, Wave(""), []string{}) 15 | 16 | assert.Equal(t, Wave("z"), []string{"Z"}) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /min_max_words/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("this is the ans low: ", FindLow("normal_http_call my name is a")) 10 | fmt.Println("this is the ans high: ", FindHigh("normal_http_call my name is a")) 11 | 12 | low, high := FindLowHigh("normal_http_call my name is a") 13 | fmt.Println("Lowest: ", low) 14 | fmt.Println("Highest: ", high) 15 | } 16 | 17 | func FindLow(s string) int { 18 | if len(s) <= 0 { 19 | return 0 20 | } 21 | words := strings.Split(s, " ") 22 | 23 | lowestWord := words[0] 24 | for _, v := range words { 25 | if len(v) < len(lowestWord) { 26 | lowestWord = v 27 | } 28 | } 29 | return len(lowestWord) 30 | } 31 | 32 | func FindHigh(s string) int { 33 | if len(s) <= 0 { 34 | return 0 35 | } 36 | words := strings.Split(s, " ") 37 | 38 | lowestWord := words[0] 39 | for _, v := range words { 40 | if len(v) > len(lowestWord) { 41 | lowestWord = v 42 | } 43 | } 44 | return len(lowestWord) 45 | } 46 | 47 | func FindLowHigh(s string) (int, int) { 48 | if len(s) <= 0 { 49 | return 0, 0 50 | } 51 | words := strings.Split(s, " ") 52 | 53 | lowestWord := words[0] 54 | highestWord := words[0] 55 | 56 | for _, v := range words { 57 | if len(v) < len(lowestWord) { 58 | lowestWord = v 59 | } 60 | } 61 | 62 | for _, v := range words { 63 | if len(v) > len(highestWord) { 64 | highestWord = v 65 | } 66 | } 67 | return len(lowestWord), len(highestWord) 68 | } 69 | -------------------------------------------------------------------------------- /minimum_radius/minimum_radius.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | //Given a positive integer K, a circle center at (0, 0) and coordinates of some points. The task is to find minimum radius of the circle so that at-least k points lie inside the circle. Output the square of the minimum radius. 9 | 10 | //Input : (1, 1), (-1, -1), (1, -1), 11 | // k = 3 12 | //Output : 2 13 | //We need a circle of radius at least 2 14 | //to include 3 points. 15 | // 16 | // 17 | //Input : (1, 1), (0, 1), (1, -1), 18 | // k = 2 19 | //Output : 1 20 | //We need a circle of radius at least 1 21 | //to include 2 points. The circle around 22 | //(0, 0) of radius 1 would include (1, 1) 23 | //and (0, 1). 24 | 25 | func minRadius(k int, x, y []int, n int) int { 26 | 27 | //this slice is not created with the length of 0, so we can add to it by "reslicing". 28 | //slices created with zero length can receive elements using the append() function, else, it will throw an error similar to this: "index out of range [0] with length 0" 29 | dis := make([]int, n) 30 | 31 | //Finding distance between of each point from origin 32 | for i := 0; i < n; i++ { 33 | 34 | dis[i] = x[i]*x[i] + y[i]*y[i] 35 | 36 | //sorting the distance 37 | sort.Ints(dis) 38 | 39 | } 40 | return dis[k-1] 41 | } 42 | 43 | func main() { 44 | 45 | k := 3 46 | x := []int{1, -1, 1} 47 | y := []int{1, -1, -1} 48 | 49 | n := len(x) 50 | 51 | fmt.Println(minRadius(k, x, y, n)) 52 | } 53 | -------------------------------------------------------------------------------- /morse/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | //fmt.Println(decodeMorse(".... . -.-- .--- ..- -.. .")) 10 | fmt.Println(decodeMorse(".... . -.-- .--- ..- -.. .")) 11 | } 12 | 13 | var MORSE_CODE = map[string]string{ 14 | ".-": "A", 15 | "-...": "B", 16 | "-.-.": "C", 17 | "-..": "D", 18 | ".": "E", 19 | "..-.": "F", 20 | "--.": "G", 21 | "....": "H", 22 | "..": "I", 23 | ".---": "J", 24 | "-.-": "K", 25 | ".-..": "L", 26 | "--": "M", 27 | "-.": "N", 28 | "---": "O", 29 | ".--.": "P", 30 | "--.-": "Q", 31 | ".-.": "R", 32 | "...": "S", 33 | "-": "T", 34 | "..-": "U", 35 | "...-": "V", 36 | ".--": "W", 37 | "-..-": "X", 38 | "-.--": "Y", 39 | "--..": "Z", 40 | "-----": "0", 41 | ".----": "1", 42 | "..---": "2", 43 | "...--": "3", 44 | "....-": "4", 45 | ".....": "5", 46 | "-....": "6", 47 | "--...": "7", 48 | "---..": "8", 49 | "----.": "9", 50 | } 51 | 52 | //func decodeMorse(morseCode string) string { 53 | // decoded := "" 54 | // morseWords := strings.Split(strings.TrimSpace(morseCode), " ") 55 | // for _, word := range morseWords { 56 | // morseWord := strings.Split(word, " ") 57 | // for _, char := range morseWord { 58 | // decoded += MORSE_CODE[char] 59 | // } 60 | // decoded += " " 61 | // } 62 | // return strings.TrimSpace(decoded) 63 | //} 64 | 65 | func decodeMorse(morseCode string) string { 66 | decoded := "" 67 | morseWords := strings.Split(morseCode, " ") 68 | for _, v := range morseWords { 69 | morseChars := strings.Split(v, " ") 70 | for _, char := range morseChars { 71 | decoded += MORSE_CODE[char] 72 | } 73 | decoded += " " 74 | } 75 | return strings.TrimSpace(decoded) 76 | } 77 | -------------------------------------------------------------------------------- /mutexes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | type AtomicInt struct { 9 | m sync.Mutex 10 | n int 11 | } 12 | 13 | func (a *AtomicInt) Add(n int) { 14 | a.m.Lock() 15 | a.n += n 16 | a.m.Unlock() 17 | } 18 | 19 | func (a *AtomicInt) Value() int { 20 | a.m.Lock() 21 | n := a.n 22 | a.m.Unlock() 23 | return n 24 | } 25 | 26 | func main() { 27 | 28 | wait := make(chan struct{}) 29 | 30 | var n AtomicInt 31 | 32 | go func() { 33 | n.Add(1) 34 | close(wait) 35 | }() 36 | 37 | n.Add(1) 38 | <-wait 39 | 40 | fmt.Println(n.Value()) 41 | } 42 | -------------------------------------------------------------------------------- /next_big_number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "sort" 7 | ) 8 | 9 | //Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example: 10 | //12 ==> 21 11 | //513 ==> 531 12 | //2017 ==> 2071 13 | 14 | func main() { 15 | 16 | fmt.Println(NextBigger(3452)) 17 | 18 | } 19 | 20 | func intToSlice(n int) []int { 21 | var numb []int 22 | for n > 0 { 23 | numb = append(numb, n%10) 24 | n /= 10 25 | } 26 | return numb 27 | } 28 | 29 | func sliceToInt(numb []int) int { 30 | n := 0 31 | for i, v := range numb { 32 | //fmt.Println("the ints: ", int(math.Pow10(i))) //1, 10, 100, 1000 33 | n += v * int(math.Pow10(i)) 34 | } 35 | return n 36 | } 37 | 38 | func NextBigger(n int) int { 39 | numb := intToSlice(n) 40 | i := 0 41 | for i := 0; i < len(numb); i++ { 42 | if numb[i] > numb[i+1] { 43 | break 44 | } 45 | } 46 | if i == len(numb)-1 { 47 | return -1 48 | } 49 | 50 | mn := i 51 | for j := 0; j < i; j++ { 52 | if numb[j] > numb[i+1] { 53 | mn = j 54 | } 55 | } 56 | numb[mn], numb[i+1] = numb[i+1], numb[mn] 57 | tmp := numb[:i+1] 58 | //fmt.Println("the temp: ", tmp) 59 | sort.Slice(tmp, func(i, j int) bool { 60 | return tmp[i] > tmp[j] 61 | }) 62 | return sliceToInt(numb) 63 | } 64 | 65 | //func NextBigger(n int) int { 66 | // numb := intToSlice(n) 67 | // i := 0 68 | // for i := 0; i < len(numb) - 1; i++ { 69 | // if numb[i] > numb[i + 1] { 70 | // break 71 | // } 72 | // } 73 | // if i == len(numb)-1 { 74 | // return -1 75 | // } 76 | // 77 | // mn := i 78 | // 79 | // for j := 0; j < i; j++ { 80 | // if numb[j] > numb[i + 1] { 81 | // mn = j 82 | // } 83 | // } 84 | // numb[mn], numb[i+1] = numb[i + 1], numb[mn] 85 | // tmp := numb[:i + 1] 86 | // sort.Slice(tmp, func(i, j int) bool { 87 | // return tmp[i] > tmp[j] 88 | // }) 89 | // return sliceToInt(numb) 90 | //} 91 | 92 | func countDigit(i int) (count int) { 93 | for i != 0 { 94 | i = i / 10 95 | fmt.Println(i) 96 | //i /= 10 97 | count++ 98 | } 99 | return count 100 | } 101 | -------------------------------------------------------------------------------- /not_very_secure/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | //In this example you have to validate if a user input string is alphanumeric. The given string is not nil/null/NULL/None, so you don't have to check that. 9 | // 10 | //The string has the following conditions to be alphanumeric: 11 | // 12 | //At least one character ("" is not valid) 13 | //Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9 14 | //No whitespaces / underscore 15 | 16 | func main() { 17 | fmt.Println(alphanumeric("THEgenaw@#$@*(ay mine own HELLObo!@#$#")) 18 | fmt.Println(alphanumeric("THEsuf dsufniudf jdsfniusdf")) 19 | fmt.Println(alphanumeric("THEsuf df")) 20 | 21 | } 22 | 23 | func alphanumeric(str string) bool { 24 | // ^ means negation 25 | r := regexp.MustCompile("^[a-zA-Z0-9]+$") 26 | return r.MatchString(str) 27 | } 28 | -------------------------------------------------------------------------------- /number_of_integer_partition/number_of_integer_partition.go: -------------------------------------------------------------------------------- 1 | package number_of_integer_partition 2 | 3 | import "fmt" 4 | 5 | //An integer partition of n is a weakly decreasing list of positive integers which sum to n. 6 | // 7 | //For example, there are 7 integer partitions of 5: 8 | // 9 | //[5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1]. 10 | // 11 | //Write a function named partitions which returns the number of integer partitions of n. The function should be able to find the number of integer partitions of n for n as least as large as 100. 12 | 13 | func p(n, m int) int { 14 | 15 | if n <= 1 { 16 | return 1 17 | } 18 | if m > n { 19 | return p(n, n) 20 | } 21 | 22 | sum := 0 23 | for k := 1; k <= m; k++ { 24 | fmt.Println("ans passed: ", n-k, k) 25 | sum += p(n-k, k) 26 | fmt.Println("sum: ", sum) 27 | } 28 | return sum 29 | } 30 | 31 | func Partitions(n int) int { 32 | return p(n, n) 33 | } 34 | -------------------------------------------------------------------------------- /number_of_integer_partition/number_of_integer_partition_test.go: -------------------------------------------------------------------------------- 1 | package number_of_integer_partition_test 2 | 3 | import ( 4 | "efficient-algorithms/number_of_integer_partition" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestPartitions(t *testing.T) { 10 | 11 | assert.Equal(t, number_of_integer_partition.Partitions(5), 7) 12 | 13 | } 14 | -------------------------------------------------------------------------------- /numbers_in_order/numbers_in_order.go: -------------------------------------------------------------------------------- 1 | package numbers_in_order 2 | 3 | import "sort" 4 | 5 | //Are the numbers in order? 6 | //In this Kata, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value. 7 | // 8 | //For the purposes of this Kata, you may assume that all inputs are valid, i.e. non-empty arrays containing only integers. 9 | // 10 | //Note that an array of 1 integer is automatically considered to be sorted in ascending order since all (zero) adjacent pairs of integers satisfy the condition that the left integer does not exceed the right integer in value. An empty list is considered a degenerate case and therefore will not be tested in this Kata - feel free to raise an Issue if you see such a list being tested. 11 | // 12 | //For example: 13 | // 14 | //InAscOrder([]int{1, 2, 4, 7, 19}) # returns True 15 | //InAscOrder([]int{1, 2, 3, 4, 5}) // returns True 16 | //InAscOrder([]int{1, 6, 10, 18, 2, 4, 20}) # returns False 17 | //InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) # returns False because the numbers are in DESCENDING order 18 | 19 | func InAscOrder(numbers []int) bool { 20 | for i := 0; i < len(numbers)-1; i++ { 21 | if numbers[i] > numbers[i+1] { 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | 28 | func InAscOrder1(numbers []int) bool { 29 | 30 | return sort.IntsAreSorted(numbers) 31 | } 32 | -------------------------------------------------------------------------------- /numbers_in_order/numbers_in_order_test.go: -------------------------------------------------------------------------------- 1 | package numbers_in_order_test 2 | 3 | import ( 4 | "efficient-algorithms/numbers_in_order" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestInAscOrder(t *testing.T) { 10 | 11 | assert.True(t, numbers_in_order.InAscOrder([]int{1, 2, 4, 7})) 12 | assert.True(t, numbers_in_order.InAscOrder([]int{1, 2, 3, 4, 5})) 13 | assert.False(t, numbers_in_order.InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /odd_int/odd_int.go: -------------------------------------------------------------------------------- 1 | package odd_int 2 | 3 | import "fmt" 4 | 5 | func FindOdd(seq []int) int { 6 | 7 | hashMap := make(map[int]int) 8 | 9 | for _, v := range seq { 10 | hashMap[v]++ 11 | } 12 | 13 | fmt.Println("this is the seq: ", seq) 14 | fmt.Println("this is the hashmap: ", hashMap) 15 | for i, v := range hashMap { 16 | if isOdd(v) { 17 | return i 18 | } 19 | } 20 | return 0 21 | } 22 | 23 | func isOdd(x int) bool { 24 | 25 | if x%2 != 0 { 26 | return true 27 | } 28 | return false 29 | } 30 | 31 | func FindOdd2(seq []int) (res int) { 32 | for _, n := range seq { 33 | res ^= n 34 | } 35 | return 36 | } 37 | -------------------------------------------------------------------------------- /odd_int/odd_int_test.go: -------------------------------------------------------------------------------- 1 | package odd_int 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestFindOdd(t *testing.T) { 9 | 10 | assert.Equal(t, FindOdd([]int{20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5}), 5) 11 | assert.Equal(t, FindOdd([]int{1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5}), -1) 12 | assert.Equal(t, FindOdd([]int{20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5}), 5) 13 | assert.Equal(t, FindOdd([]int{10}), 10) 14 | assert.Equal(t, FindOdd([]int{1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1}), 10) 15 | assert.Equal(t, FindOdd([]int{5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10}), 1) 16 | } 17 | -------------------------------------------------------------------------------- /ordered_count_characters/ordered_count_characters.go: -------------------------------------------------------------------------------- 1 | package ordered_count_characters 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | //Count the number of occurrences of each character and return it as a list of tuples in order of appearance. For empty output return an empty list. 8 | 9 | //Example: 10 | // 11 | //OrderedCount("abracadabra") == []Tuple{Tuple{'a', 5}, Tuple{'b', 2}, Tuple{'r', 2}, Tuple{'c', 1}, Tuple{'d', 1}} 12 | // 13 | //// Where 14 | //type Tuple struct { 15 | // Char rune 16 | // Count int 17 | //} 18 | 19 | type Tuple struct { 20 | Char rune 21 | Count int 22 | } 23 | 24 | func OrderedCount(text string) (tups []Tuple) { 25 | 26 | str := "" 27 | 28 | for _, v := range text { 29 | if strings.Count(str, string(v)) == 0 { 30 | tups = append(tups, Tuple{ 31 | Char: v, 32 | Count: strings.Count(text, string(v)), 33 | }) 34 | str += string(v) 35 | } 36 | } 37 | return tups 38 | } 39 | 40 | //A different approach 41 | func OrderedCount2(text string) (tups []Tuple) { 42 | 43 | var hashMap = make(map[rune]int) 44 | for _, v := range text { 45 | if _, ok := hashMap[v]; !ok { 46 | count := strings.Count(text, string(v)) 47 | hashMap[v] = count 48 | 49 | tups = append(tups, Tuple{ 50 | Char: v, 51 | Count: count, 52 | }) 53 | } 54 | } 55 | return tups 56 | } 57 | -------------------------------------------------------------------------------- /ordered_count_characters/ordered_count_characters_test.go: -------------------------------------------------------------------------------- 1 | package ordered_count_characters 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestOrderedCount(t *testing.T) { 9 | 10 | ans := OrderedCount("abracadabra") 11 | 12 | expected := []Tuple{Tuple{'a', 5}, Tuple{'b', 2}, Tuple{'r', 2}, Tuple{'c', 1}, Tuple{'d', 1}} 13 | 14 | assert.Equal(t, expected, ans) 15 | 16 | ans2 := OrderedCount2("abracadabra") 17 | 18 | expected2 := []Tuple{Tuple{'a', 5}, Tuple{'b', 2}, Tuple{'r', 2}, Tuple{'c', 1}, Tuple{'d', 1}} 19 | 20 | assert.Equal(t, expected2, ans2) 21 | 22 | } 23 | -------------------------------------------------------------------------------- /outlier/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | 7 | A := []int{2, 3, 4, 6, 8, 10} 8 | 9 | fmt.Println("this is the code: ", FindOutlier(A)) 10 | } 11 | 12 | func FindOutlier(integers []int) int { 13 | outlier := 0 14 | odd_array := []int{} 15 | even_array := []int{} 16 | for _, v := range integers { 17 | if v%2 == 0 { 18 | even_array = append(even_array, v) 19 | } else { 20 | odd_array = append(odd_array, v) 21 | } 22 | } 23 | if len(odd_array) > len(even_array) { 24 | outlier = even_array[0] 25 | } else { 26 | outlier = odd_array[0] 27 | } 28 | return outlier 29 | } 30 | -------------------------------------------------------------------------------- /palindrome/example_1/example_1.go: -------------------------------------------------------------------------------- 1 | package example_1 2 | 3 | //Find all numbers less than n, which are palindromic. Numbers can be printed in any order. 4 | 5 | //func createPalindrome(input, b int, isOdd bool) int { 6 | // 7 | // n := input 8 | // palin := input 9 | // 10 | // if isOdd { 11 | // n = n / b 12 | // } 13 | // 14 | // //creates palindrome by just appending reverse of number of itself 15 | // for n > 0 { 16 | // palin = palin * b + (n % b) 17 | // n = n / b 18 | // } 19 | // return palin 20 | //} 21 | // 22 | //func generatePalindrome(n int) int { 23 | // 24 | // num := 0 25 | // 26 | // for j := 0; j < 2; j++ { 27 | // 28 | // // Creates palindrome numbers 29 | // // with first half as i. Value 30 | // // of j decided whether we need 31 | // // an odd length of even length 32 | // // palindrome. 33 | // //i := 1 34 | // //for num = createPalindrome(i, 10, j % 2)) < n { 35 | // // fmt.Println(n, ""), 36 | // // i++ 37 | // //} 38 | // } 39 | //} 40 | -------------------------------------------------------------------------------- /palindrome/palindromesentences/palindrome_sentences.go: -------------------------------------------------------------------------------- 1 | package palindromesentences 2 | 3 | import "strings" 4 | 5 | //IsPalindrome determines if the input is a palindrome 6 | 7 | const ( 8 | capitalA = 'A' 9 | capitalZ = 'Z' 10 | smallA = 'a' 11 | smallZ = 'z' 12 | ) 13 | 14 | func IsPalindromeCaseInsensitive(s string) bool { 15 | 16 | //change to lower case 17 | sentence := strings.ToLower(s) 18 | 19 | runes := []rune(sentence) 20 | length := len(runes) 21 | 22 | i := 0 23 | j := length - 1 24 | 25 | for i < j { 26 | if !isCharacterCaseInsensitive(runes[i]) { 27 | i++ 28 | continue 29 | } 30 | if !isCharacterCaseInsensitive(runes[j]) { 31 | j-- 32 | continue 33 | } 34 | if runes[i] != runes[j] { 35 | return false 36 | } 37 | i++ 38 | j-- 39 | } 40 | 41 | return true 42 | } 43 | 44 | func IsPalindrome(sentence string) bool { 45 | 46 | runes := []rune(sentence) 47 | 48 | length := len(runes) 49 | 50 | i := 0 51 | j := length - 1 52 | 53 | for i < j { 54 | if !isCharacter(runes[i]) { 55 | i++ 56 | continue 57 | } 58 | 59 | if !isCharacter(runes[j]) { 60 | j-- 61 | continue 62 | } 63 | 64 | if runes[i] != runes[j] { 65 | return false 66 | } 67 | i++ 68 | j-- 69 | } 70 | return true 71 | } 72 | 73 | func isCharacter(character rune) bool { 74 | if character >= capitalA && character <= capitalZ { 75 | return true 76 | } 77 | if character >= smallA && character <= smallZ { 78 | return true 79 | } 80 | return false 81 | } 82 | 83 | func isCharacterCaseInsensitive(character rune) bool { 84 | 85 | if character >= smallA && character <= smallZ { 86 | return true 87 | } 88 | return false 89 | } 90 | -------------------------------------------------------------------------------- /palindrome/palindromesentences/palindrome_sentences_test.go: -------------------------------------------------------------------------------- 1 | package palindromesentences_test 2 | 3 | import ( 4 | "efficient-algorithms/palindrome/palindromesentences" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestIsPalindrome(t *testing.T) { 10 | 11 | assert.True(t, palindromesentences.IsPalindrome("hannah")) 12 | assert.True(t, palindromesentences.IsPalindrome("too hot to hoot.")) 13 | assert.False(t, palindromesentences.IsPalindrome("normal_http_call")) 14 | 15 | assert.True(t, palindromesentences.IsPalindromeCaseInsensitive("Do geese see God?")) 16 | assert.True(t, palindromesentences.IsPalindromeCaseInsensitive("Was it a car or a cat I saw?")) 17 | } 18 | -------------------------------------------------------------------------------- /palindrome/palindromestrings/palindromestrings.go: -------------------------------------------------------------------------------- 1 | package palindromestrings 2 | 3 | //IsPalindrome determines if the input is a palindrome 4 | //func IsPalindrome(text string) bool { 5 | // 6 | // runes := []rune(text) 7 | // length := len(runes) 8 | // for i, j := 0, length - 1; i < length/2; i, j = i + 1, j - 1 { 9 | // if runes[i] != runes[j] { 10 | // return false 11 | // } 12 | // } 13 | // return true 14 | //} 15 | 16 | func IsPalindrome(text string) bool { 17 | 18 | //runes := []rune(text) 19 | length := len(text) 20 | for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 { 21 | if string(text[i]) != string(text[j]) { 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | -------------------------------------------------------------------------------- /palindrome/palindromestrings/palindromestrings_test.go: -------------------------------------------------------------------------------- 1 | package palindromestrings_test 2 | 3 | import ( 4 | "efficient-algorithms/palindrome/palindromestrings" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestIsPalindrome(t *testing.T) { 10 | 11 | assert.True(t, palindromestrings.IsPalindrome("hannah")) 12 | assert.True(t, palindromestrings.IsPalindrome("hanah")) 13 | assert.False(t, palindromestrings.IsPalindrome("normal_http_call")) 14 | assert.True(t, palindromestrings.IsPalindrome("level")) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /paperfold_sequence/paperfold_sequence.go: -------------------------------------------------------------------------------- 1 | package paperfold_sequence 2 | 3 | //Wikipedia: The regular paperfolding sequence, also known as the dragon curve sequence, is an infinite automatic sequence of 0s and 1s defined as the limit of the following process: 4 | // 5 | //1 6 | //1 1 0 7 | //1 1 0 1 1 0 0 8 | //1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 9 | // 10 | //At each stage an alternating sequence of 1s and 0s is inserted between the terms of the previous sequence. 11 | // 12 | //Define a generator PaperFold that sequentially generates the values of this sequence. 13 | // 14 | //It will be tested for up to 1 000 000 values. 15 | 16 | func PaperFold(ch chan<- int) { 17 | v := 1 18 | i := 1 19 | for true { 20 | v = i 21 | for v%2 == 0 { 22 | v /= 2 23 | } 24 | if v%4 == 1 { 25 | ch <- 1 26 | } else { 27 | ch <- 0 28 | } 29 | i++ 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /paperfold_sequence/paperfold_sequence_test.go: -------------------------------------------------------------------------------- 1 | package paperfold_sequence 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPaperFold(t *testing.T) { 9 | 10 | arr := []int{} 11 | 12 | ch := make(chan int, 100) 13 | go PaperFold(ch) 14 | 15 | for i := 0; i < 20; i++ { 16 | arr = append(arr, <-ch) 17 | } 18 | assert.Equal(t, arr, []int{1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1}) 19 | } 20 | -------------------------------------------------------------------------------- /parts_of_a_list/part_a_list_test.go: -------------------------------------------------------------------------------- 1 | package parts_of_a_list 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPartList(t *testing.T) { 9 | 10 | assert.Equal(t, PartList([]string{"I", "wish", "I", "hadn't", "come"}), "(I, wish I hadn't come)(I wish, I hadn't come)(I wish I, hadn't come)(I wish I hadn't, come)") 11 | 12 | assert.Equal(t, PartList([]string{"cdIw", "tzIy", "xDu", "rThG"}), "(cdIw, tzIy xDu rThG)(cdIw tzIy, xDu rThG)(cdIw tzIy xDu, rThG)") 13 | 14 | } 15 | -------------------------------------------------------------------------------- /pascals_triangle/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func main() { 9 | //fmt.Println() 10 | pascal(10) 11 | } 12 | 13 | func binomialCoeff(n, k int) int { 14 | res := 1 15 | if k > n-k { 16 | k = n - k 17 | } 18 | for i := 0; i < k; i++ { 19 | res *= n - i 20 | res /= i + 1 21 | } 22 | return res 23 | } 24 | 25 | func pascal(n int) { 26 | for line := 0; line < n; line++ { 27 | for i := 0; i <= line; i++ { 28 | fmt.Print("" + strconv.Itoa(binomialCoeff(line, i)) + " ") 29 | } 30 | fmt.Println() 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /passphrases/passphrases_test.go: -------------------------------------------------------------------------------- 1 | package passphrases 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestPlayPass(t *testing.T) { 9 | 10 | ans := PlayPass("MY GRANMA CAME FROM NY ON THE 23RD OF APRIL 2015", 2) 11 | 12 | fmt.Println("the result: ", ans) 13 | } 14 | -------------------------------------------------------------------------------- /passwords/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "golang.org/x/crypto/bcrypt" 6 | ) 7 | 8 | func main() { 9 | 10 | fmt.Println("this is the password: ", Encrypt("123456")) 11 | } 12 | 13 | 14 | // Encrypt securely encrypts a Password object 15 | func Encrypt(password string) string { 16 | bytes, _ := bcrypt.GenerateFromPassword([]byte(password), 14) 17 | return string(bytes) 18 | } 19 | 20 | // Check compared password and returns if they match 21 | func Check(password string) bool { 22 | err := bcrypt.CompareHashAndPassword([]byte(password), []byte(password)) 23 | return err == nil 24 | } 25 | -------------------------------------------------------------------------------- /permutable_palindrome/permutable_palindrome.go: -------------------------------------------------------------------------------- 1 | package permutable_palindrome 2 | 3 | func PermutablePalindrome(s string) bool { 4 | 5 | hashMap := make(map[rune]int, 0) 6 | 7 | for _, v := range s { 8 | hashMap[v]++ 9 | } 10 | 11 | odd := 0 12 | for _, v := range hashMap { 13 | if v % 2 != 0 { 14 | odd++ 15 | } 16 | } 17 | if odd > 1 { 18 | return false 19 | } 20 | return true 21 | } 22 | 23 | func PermutablePalindrome2(s string) bool { 24 | 25 | hashMap := make(map[rune]int, 0) 26 | odd := 0 27 | for _, v := range s { 28 | if _, ok := hashMap[v]; ok { 29 | if hashMap[v] > 1 && hashMap[v] % 2 != 0 { 30 | odd++ 31 | } 32 | } 33 | hashMap[v]++ 34 | } 35 | if odd > 1 { 36 | return false 37 | } 38 | return true 39 | } 40 | -------------------------------------------------------------------------------- /permutable_palindrome/permutable_palindrome_test.go: -------------------------------------------------------------------------------- 1 | package permutable_palindrome 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPermutablePalindrome(t *testing.T) { 9 | if !PermutablePalindrome("aad") { 10 | t.Errorf("Want %v, got %v", true, false) 11 | } 12 | 13 | assert.True(t, PermutablePalindrome2("aad"), true) 14 | assert.True(t, PermutablePalindrome2("racecar"), true) 15 | assert.True(t, PermutablePalindrome2("rcaerca"), true) 16 | assert.True(t, PermutablePalindrome2("racecap"), false) 17 | assert.True(t, PermutablePalindrome2("rcaepca"), false) 18 | } 19 | -------------------------------------------------------------------------------- /phone_number/phone_number.go: -------------------------------------------------------------------------------- 1 | package phone_number 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | //Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. 8 | 9 | func CreatePhoneNumber(numbers [10]uint) string { 10 | 11 | for _, v := range numbers { 12 | if v > 9 || v < 0 { 13 | return "" 14 | } 15 | } 16 | 17 | return fmt.Sprintf("(%d%d%d) %d%d%d-%d%d%d%d", numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5], numbers[6], numbers[7], numbers[8], numbers[9]) 18 | } 19 | -------------------------------------------------------------------------------- /phone_number/phone_number_test.go: -------------------------------------------------------------------------------- 1 | package phone_number_test 2 | 3 | import ( 4 | "efficient-algorithms/phone_number" 5 | "fmt" 6 | "testing" 7 | ) 8 | 9 | func TestCreatePhoneNumber(t *testing.T) { 10 | 11 | nums := [10]uint{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} 12 | ans := phone_number.CreatePhoneNumber(nums) 13 | 14 | fmt.Println(ans) 15 | } 16 | -------------------------------------------------------------------------------- /pick_peaks/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type PosPeaks struct { 6 | Pos []int 7 | Peaks []int 8 | } 9 | 10 | func main() { 11 | fmt.Println(PickPeaks([]int{3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3})) 12 | fmt.Println(PickPeaks([]int{1, 2, 3, 5, 2, 1, 5})) 13 | fmt.Println(PickPeaks([]int{1, 1, 2, 2, 2, 2, 1, 1})) 14 | } 15 | 16 | func PickPeaks(array []int) PosPeaks { 17 | posPeaks := PosPeaks{Pos: []int{}, Peaks: []int{}} 18 | maxpos := 0 19 | for i := 1; i < len(array); i++ { 20 | if array[i] > array[i-1] { 21 | maxpos = i 22 | } else if array[i-1] > array[i] && maxpos > 0 { 23 | posPeaks.Pos = append(posPeaks.Pos, maxpos) 24 | posPeaks.Peaks = append(posPeaks.Peaks, array[maxpos]) 25 | maxpos = 0 26 | } 27 | } 28 | return posPeaks 29 | } 30 | -------------------------------------------------------------------------------- /pile_of_cube/pile_of_cube.go: -------------------------------------------------------------------------------- 1 | package pile_of_cube 2 | 3 | import "fmt" 4 | 5 | //Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. 6 | // 7 | //You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build? 8 | // 9 | //The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n. 10 | // 11 | //Examples: 12 | //findNb(1071225) --> 45 13 | //findNb(91716553919377) --> -1 14 | 15 | func FindNb(m int) int { 16 | for n := 1; m > 0; n++ { 17 | m -= n * n * n 18 | fmt.Println("the m : ", m) 19 | if m == 0 { 20 | return n 21 | } 22 | } 23 | return -1 24 | } 25 | 26 | func FindNb2(m int) int { 27 | sum := 0 28 | for i := 1; ; i++ { 29 | sum += i * i * i 30 | if sum == m { 31 | return i 32 | } else if sum > m { 33 | return -1 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /pile_of_cube/pile_of_cube_test.go: -------------------------------------------------------------------------------- 1 | package pile_of_cube 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestFindNb(t *testing.T) { 9 | assert.Equal(t, FindNb(1071225), 45) 10 | } 11 | -------------------------------------------------------------------------------- /polymorphism/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | project1 := FixedBilling{projectName: "Project 1", biddedAmount: 5000} 7 | project2 := FixedBilling{projectName: "project 2", biddedAmount: 10000} 8 | project3 := TimeAndMaterial{projectName: "Project 3", noOfHours: 160, hourlyRate: 25} 9 | 10 | incomeStreams := []Income{project1, project2, project3} 11 | 12 | calculateNetIncome(incomeStreams) 13 | 14 | fmt.Println() 15 | //constant example 16 | const mine = 4.5 17 | fmt.Printf("this is the type: %T\n", mine) 18 | 19 | type theStruct struct { 20 | Name string 21 | Age int 22 | } 23 | newer := new(theStruct) 24 | newer.Name = "Ade" 25 | fmt.Println("the struct: ", newer) 26 | 27 | } 28 | 29 | type Income interface { 30 | calculate() int 31 | source() string 32 | } 33 | 34 | type FixedBilling struct { 35 | projectName string 36 | biddedAmount int 37 | } 38 | type TimeAndMaterial struct { 39 | projectName string 40 | noOfHours int 41 | hourlyRate int 42 | } 43 | 44 | func (fb FixedBilling) calculate() int { 45 | return fb.biddedAmount 46 | } 47 | func (fb FixedBilling) source() string { 48 | return fb.projectName 49 | } 50 | 51 | func (tm TimeAndMaterial) calculate() int { 52 | return tm.noOfHours * tm.hourlyRate 53 | } 54 | 55 | func (tm TimeAndMaterial) source() string { 56 | return tm.projectName 57 | } 58 | 59 | //using polymorphism for calculation based on the array of variables of interface type 60 | func calculateNetIncome(ic []Income) { 61 | var netincome int = 0 62 | for _, income := range ic { 63 | fmt.Printf("Income from %s = $%d\n", income.source(), income.calculate()) 64 | netincome += income.calculate() 65 | } 66 | fmt.Printf("Net income of organization = $%d", netincome) 67 | } 68 | -------------------------------------------------------------------------------- /power_of_3/power_of_3.go: -------------------------------------------------------------------------------- 1 | package power_of_3 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | //Given a positive integer N, return the largest integer k such that 3^k < N. 8 | // 9 | //For example, 10 | // 11 | //LargestPower(3) // returns 0 12 | //LargestPower(4) // returns 1 13 | 14 | //You may assume that the input to your function is always a positive integer. 15 | 16 | func LargestPower(n uint64) int { 17 | 18 | largest := 0 19 | 20 | for i := uint64(0); i < n; i++ { 21 | if math.Pow(3, float64(i)) < float64(n) && i > uint64(largest) { 22 | largest = int(i) 23 | } 24 | } 25 | return largest 26 | } 27 | 28 | //more performant solution: 29 | func LargestPower2(n uint64) int { 30 | 31 | k := 0.0 32 | 33 | for math.Pow(3, k) < float64(n) { 34 | k++ 35 | } 36 | 37 | return int(k - 1) 38 | } 39 | 40 | //import . "math" 41 | // 42 | //func LargestPower(n uint64) int { 43 | // k := 0.0 44 | // for Pow(3,k) < float64(n) { 45 | // k++ 46 | // } 47 | // return int(k-1) 48 | //} 49 | 50 | //import "math" 51 | // 52 | //func LargestPower(n uint64) int { 53 | // k := 0 54 | // 55 | // for uint64(math.Pow(3, float64(k))) < n { 56 | // k++ 57 | // } 58 | // 59 | // return k - 1 60 | //} 61 | -------------------------------------------------------------------------------- /power_of_3/power_of_3_test.go: -------------------------------------------------------------------------------- 1 | package power_of_3 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestLargestPower(t *testing.T) { 9 | 10 | assert.Equal(t, LargestPower2(4), 1) 11 | 12 | assert.Equal(t, LargestPower2(3), 0) 13 | 14 | assert.Equal(t, LargestPower2(82), 4) 15 | 16 | assert.Equal(t, LargestPower2(81), 3) 17 | 18 | assert.Equal(t, LargestPower2(7), 1) 19 | } 20 | -------------------------------------------------------------------------------- /prime_number_generator/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //Your task here is to generate a list of prime numbers, starting from 2. 6 | // 7 | //One way of doing this is using python's generators. 8 | // 9 | //In case you choose to use generators, notice that the generator object should contain all the generated prime numbers, from 2 to an upper limit (included) provided as the argument to the function. If the input limit is less than 2 (including negatives), it should return an empty list. 10 | // 11 | //Each iteration of the generator will yield one prime number. See this link for reference. 12 | // 13 | //The generator object will be converted to a list outside the code, within the test cases. 14 | // 15 | //There will be no check if you are using generators or lists, so use the one you feel more confortable with. 16 | 17 | func main() { 18 | fmt.Println("this is the one: ", list(10)) 19 | } 20 | 21 | func list(n int) []int { 22 | 23 | arr := []int{} 24 | for i := 2; i < n; i++ { 25 | if isPrime(i) { 26 | arr = append(arr, i) 27 | } 28 | } 29 | return arr 30 | } 31 | 32 | func isPrime(n int) bool { 33 | for i := 2; i <= n/2; i++ { 34 | if n%i == 0 { 35 | return false 36 | } 37 | } 38 | return true 39 | } 40 | -------------------------------------------------------------------------------- /primes_in_numbers/primes_in_numbers.go: -------------------------------------------------------------------------------- 1 | package primes_in_numbers 2 | 3 | import "fmt" 4 | 5 | //Given a positive number n > 1 find the prime factor decomposition of n. The result will be a string with the following form : 6 | // 7 | // "(p1**n1)(p2**n2)...(pk**nk)" 8 | 9 | //where a ** b means a to the power of b 10 | //with the p(i) in increasing order and n(i) empty if n(i) is 1. 11 | //Example: n = 86240 should return "(2**5)(5)(7**2)(11)" 12 | 13 | //func PrimeFactors(n int) string { 14 | // 15 | // primes := getPrimes(n) 16 | // 17 | // hashMap := make(map[int]int) 18 | // 19 | // result := "" 20 | // for _, v := range primes { 21 | // hashMap[v]++ 22 | // } 23 | // 24 | // fmt.Println("the hash: ", hashMap) 25 | // 26 | // for i, v := range hashMap { 27 | // 28 | // fmt.Println("each: ", i) 29 | // 30 | // if v == 1 { 31 | // result += fmt.Sprintf("(%d)", i) 32 | // } else if v > 1 { 33 | // result += fmt.Sprintf("(%d**%d)", i, v) 34 | // } 35 | // } 36 | // 37 | // fmt.Println("the result now: ", result) 38 | // 39 | // return result 40 | // 41 | //} 42 | // 43 | //func getPrimes(n int) (primes []int) { 44 | // 45 | // div := 2 46 | // 47 | // for n > 1 { 48 | // if n % div == 0 { 49 | // primes = append(primes, div) 50 | // n = n / div 51 | // } else { 52 | // div++ 53 | // } 54 | // } 55 | // return primes 56 | //} 57 | 58 | func PrimeFactors(n int) (ret string) { 59 | for i, m := 2, 0; n > 0; { 60 | if n%i != 0 { 61 | if m == 1 { 62 | ret += fmt.Sprintf("(%d)", i) 63 | } else if m > 1 { 64 | ret += fmt.Sprintf("(%d**%d)", i, m) 65 | } 66 | if n == 1 { 67 | break 68 | } 69 | i, m = i+1, 0 70 | continue 71 | } 72 | n, m = n/i, m+1 73 | } 74 | 75 | fmt.Println("ans: ", ret) 76 | 77 | return ret 78 | } 79 | -------------------------------------------------------------------------------- /primes_in_numbers/primes_in_numbers_test.go: -------------------------------------------------------------------------------- 1 | package primes_in_numbers_test 2 | 3 | import ( 4 | "efficient-algorithms/primes_in_numbers" 5 | "fmt" 6 | "github.com/stretchr/testify/assert" 7 | "testing" 8 | ) 9 | 10 | func TestPrimeFactors(t *testing.T) { 11 | 12 | assert.Equal(t, "(2**5)(5)(7**2)(11)", primes_in_numbers.PrimeFactors(86240)) 13 | 14 | assert.Equal(t, "(2**5)(5)(7**2)(11)", primes_in_numbers.PrimeFactors(86240)) 15 | 16 | ans := primes_in_numbers.PrimeFactors(614031) 17 | 18 | fmt.Println("ans : ", ans) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /printer_error/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func main() { 9 | //fmt.Println(print_error("aaabbbbhaijjjm")) 10 | //fmt.Println(print_error("aaaxbbbbyyhwawiwjjjwwm")) 11 | 12 | fmt.Println(print_error2("aaabbbbhaijjjm")) 13 | fmt.Println(print_error2("aaaxbbbbyyhwawiwjjjwwm")) 14 | } 15 | 16 | func print_error(str string) string { 17 | if len(str) <= 0 { 18 | return "" 19 | } 20 | match := 0 21 | standard := "abcdefghijklm" 22 | //standard := []string{"a","b","c","d","e","f","g","h","i","j","k","l","m"} 23 | for _, v := range str { 24 | for _, w := range standard { 25 | if v == w { 26 | match++ 27 | } 28 | } 29 | } 30 | num := 0 31 | strLen := len(str) 32 | if strLen > match { 33 | num = strLen - match 34 | } else { 35 | num = match - len(str) 36 | } 37 | return strconv.Itoa(num) + "/" + strconv.Itoa(strLen) 38 | } 39 | 40 | //Solution 2 41 | func print_error2(s string) string { 42 | count := 0 43 | for _, c := range s { 44 | if c >= 'a' && c <= 'm' { 45 | continue 46 | } else { 47 | count++ 48 | } 49 | } 50 | return fmt.Sprintf("%d/%d", count, len(s)) 51 | } 52 | -------------------------------------------------------------------------------- /product_of_fib/product_of_fib.go: -------------------------------------------------------------------------------- 1 | package product_of_fib 2 | 3 | import "fmt" 4 | 5 | //The Fibonacci numbers are the numbers in the following integer sequence (Fn): 6 | // 7 | //0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... 8 | // 9 | //such as 10 | // 11 | //F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. 12 | // 13 | //Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying 14 | // 15 | //F(n) * F(n+1) = prod. 16 | // 17 | //Your function productFib takes an integer (prod) and returns an array: 18 | // 19 | //[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True) 20 | //depending on the language if F(n) * F(n+1) = prod. 21 | // 22 | //If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prodyou will return 23 | // 24 | //[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False) 25 | //F(m) being the smallest one such as F(m) * F(m+1) > prod. 26 | // 27 | //Some Examples of Return: 28 | //(depend on the language) 29 | // 30 | //productFib(714) # should return (21, 34, true), 31 | // # since F(8) = 21, F(9) = 34 and 714 = 21 * 34 32 | // 33 | //productFib(800) # should return (34, 55, false), 34 | // # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55 35 | //----- 36 | //productFib(714) # should return [21, 34, true], 37 | //productFib(800) # should return [34, 55, false], 38 | //----- 39 | //productFib(714) # should return {21, 34, 1}, 40 | //productFib(800) # should return {34, 55, 0}, 41 | //----- 42 | //productFib(714) # should return {21, 34, true}, 43 | //productFib(800) # should return {34, 55, false}, 44 | //Note: 45 | //You can see examples for your language in "Sample Tests". 46 | 47 | //func main() { 48 | // ans := genFib(30) 49 | // 50 | // fmt.Println(ans) 51 | // 52 | // ans2 := ProductFib(714) 53 | // fmt.Println(ans2) 54 | //} 55 | 56 | func ProductFib(prod uint64) [3]uint64 { 57 | // your code 58 | f1 := uint64(0) 59 | f2 := uint64(1) 60 | 61 | fmt.Println("initial f1 and f2: ", f1, f2) 62 | 63 | for f1*f2 < prod { 64 | f1, f2 = f2, f1+f2 65 | } 66 | success := uint64(0) 67 | if prod == f1*f2 { 68 | success = 1 69 | } 70 | 71 | return [3]uint64{f1, f2, success} 72 | 73 | } 74 | -------------------------------------------------------------------------------- /product_of_fib/product_of_fib_test.go: -------------------------------------------------------------------------------- 1 | package product_of_fib 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestProductFib(t *testing.T) { 9 | 10 | assert.Equal(t, ProductFib(714), [3]uint64{21, 34, 1}) 11 | assert.Equal(t, ProductFib(800), [3]uint64{34, 55, 0}) 12 | 13 | } 14 | -------------------------------------------------------------------------------- /qualified/main_2.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /rand/rand.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | test() 11 | } 12 | 13 | func test() { 14 | 15 | rand.Seed(time.Now().UnixNano()) 16 | 17 | fmt.Println() 18 | } 19 | -------------------------------------------------------------------------------- /rectangle_into_rectangles/figure_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/rectangle_into_rectangles/figure_1.png -------------------------------------------------------------------------------- /rectangle_into_rectangles/figure_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/rectangle_into_rectangles/figure_2.png -------------------------------------------------------------------------------- /rectangle_into_rectangles/rectangle_into_rectangles_test.go: -------------------------------------------------------------------------------- 1 | package rectangle_into_rectangles 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestRectIntoRectangle1(t *testing.T) { 9 | 10 | assert.Equal(t, RectIntoRectangle4(20, 8), []string{"(16*8)", "(8*4)", "(20*8)", "(12*8)"}) 11 | 12 | assert.Equal(t, RectIntoRectangle4(13, 5), []string{"(10*5)", "(8*5)", "(2*1)", "(3*2)", "(5*3)", "(13*5)"}) 13 | 14 | assert.Equal(t, RectIntoRectangle4(22, 6), []string{"(12*6)", "(18*6)", "(22*6)", "(12*6)", "(16*6)", "(10*6)", "(6*4)", "(4*2)"}) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /rectangle_rotation/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | //A rectangle with sides equal to even integers a and b is drawn on the Cartesian plane. Its center (the intersection point of its diagonals) coincides with the point (0, 0), but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes. 9 | // 10 | //How many points with integer coordinates are located inside the given rectangle (including on its sides)? 11 | 12 | func main() { 13 | 14 | ans := RectangleRotation2(6, 4) 15 | 16 | fmt.Println(ans) 17 | } 18 | 19 | func RectangleRotation2(a, b int) int { 20 | c := math.Sqrt(2) / 2 21 | x, y := int(float64(a)/2/c), int(float64(b)/2/c) 22 | return (x*2+1)*(y*2+1)/2 + (1 - ((x + y) % 2)) 23 | } 24 | -------------------------------------------------------------------------------- /regexp/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | func main() { 9 | s := `100 10 | 00 11 | 0 12 | 1 13 | 0 14 | 15 | 0 16 | 1` 17 | 18 | //pattern := regexp.MustCompile("0(0|\n)*0") 19 | pattern := regexp.MustCompile("(?m:^0(0|\n)*0)") 20 | 21 | s = pattern.ReplaceAllString(s, "0") 22 | fmt.Println(s) 23 | 24 | } 25 | -------------------------------------------------------------------------------- /reverses/reversesentences/reverse_sentence_test.go: -------------------------------------------------------------------------------- 1 | package reversesentences_test 2 | 3 | import ( 4 | "efficient-algorithms/reverses/reversesentences" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestReverseSentence(t *testing.T) { 10 | assert.Equal(t, reversesentences.ReverseSentence("normal_http_call"), "normal_http_call") 11 | assert.Equal(t, reversesentences.ReverseSentence("this is a sentence"), "sentence a is this") 12 | assert.Equal(t, reversesentences.ReverseSentence(" normal_http_call "), " normal_http_call ") 13 | assert.Equal(t, reversesentences.ReverseSentence(" this is a sentence"), "sentence a is this ") 14 | assert.Equal(t, reversesentences.ReverseSentence("What is happening?"), "happening? is What") 15 | assert.Equal(t, reversesentences.ReverseSentence("Hello! How are you?"), "you? are How Hello!") 16 | } 17 | -------------------------------------------------------------------------------- /reverses/reversesentences/reverse_sentences.go: -------------------------------------------------------------------------------- 1 | package reversesentences 2 | 3 | import "efficient-algorithms/reverses/reversestring" 4 | 5 | func ReverseSentence(sentence string) string { 6 | 7 | runes := []rune(sentence) 8 | 9 | size := len(runes) 10 | 11 | //reverse entire string 12 | reversestring.Reverse(runes, 0, size-1) 13 | 14 | start := 0 15 | end := 0 16 | 17 | for start < size && end < size { 18 | if runes[start] == ' ' { 19 | start++ 20 | end++ 21 | continue 22 | } 23 | 24 | if runes[end] != ' ' { 25 | end++ 26 | continue 27 | } 28 | 29 | reversestring.Reverse(runes, start, end-1) 30 | 31 | start = end 32 | } 33 | 34 | reversestring.Reverse(runes, start, end-1) 35 | 36 | return string(runes) 37 | 38 | } 39 | -------------------------------------------------------------------------------- /reverses/reversestring/reversestring.go: -------------------------------------------------------------------------------- 1 | package reversestring 2 | 3 | //ReserveString reverse a string 4 | func ReverseString(text string) string { 5 | 6 | runes := []rune(text) 7 | Reverse(runes, 0, len(runes)-1) 8 | 9 | return string(runes) 10 | } 11 | 12 | func Reverse(runes []rune, start int, end int) { 13 | 14 | for i, j := start, end; i < j; i, j = i+1, j-1 { 15 | 16 | runes[i], runes[j] = runes[j], runes[i] 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /reverses/reversestring/reversestring_test.go: -------------------------------------------------------------------------------- 1 | package reversestring 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestReverseString(t *testing.T) { 9 | assert.Equal(t, ReverseString("normal_http_call"), "olleh") 10 | } 11 | -------------------------------------------------------------------------------- /roman_decoder/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | fmt.Println(Decode("MMVIII")) 9 | fmt.Println(Decode2("MMVIII")) 10 | } 11 | 12 | var ROMAN = map[rune]int{ 13 | 'I': 1, 14 | 'V': 5, 15 | 'X': 10, 16 | 'L': 50, 17 | 'C': 100, 18 | 'D': 500, 19 | 'M': 1000, 20 | } 21 | 22 | func Decode(roman string) int { 23 | result := 0 24 | last_digit := 1000 25 | for _, v := range roman { 26 | fmt.Printf("The type %T\n", v) //this is a rune === int32 27 | digit := ROMAN[v] 28 | if last_digit < digit { 29 | result -= 2 * last_digit 30 | } 31 | last_digit = digit 32 | result += digit 33 | } 34 | return result 35 | } 36 | 37 | func Decode2(roman string) int { 38 | var intern []int 39 | var result int 40 | for _, r := range roman { 41 | intern = append(intern, ROMAN[r]) 42 | } 43 | for i := 1; i < len(intern); i++ { 44 | if intern[i-1] >= intern[i] { 45 | result += intern[i-1] 46 | } else { 47 | result -= intern[i-1] 48 | } 49 | } 50 | result += intern[len(intern)-1] 51 | 52 | return result 53 | } 54 | -------------------------------------------------------------------------------- /rotate_for_max/rotate_for_max_test.go: -------------------------------------------------------------------------------- 1 | package rotate_for_max_test 2 | 3 | import ( 4 | "efficient-algorithms/rotate_for_max" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestMaxRot(t *testing.T) { 10 | 11 | assert.Equal(t, rotate_for_max.MaxRot(56789), int64(68957)) 12 | 13 | } 14 | -------------------------------------------------------------------------------- /same_array_squared/same_array_squared_test.go: -------------------------------------------------------------------------------- 1 | package same_array_squared 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestComp(t *testing.T) { 9 | 10 | a := []int{121, 144, 19, 161, 19, 144, 19, 11} 11 | b := []int{121, 14641, 20736, 361, 25921, 361, 20736, 361} 12 | assert.True(t, Comp(a, b)) 13 | 14 | a2 := []int{121, 144, 19, 161, 19, 144, 19, 11} 15 | b2 := []int{132, 14641, 20736, 361, 25921, 361, 20736, 361} 16 | assert.False(t, Comp(a2, b2)) 17 | 18 | var a3 = []int{121, 144, 19, 161, 19, 144, 19, 11} 19 | var b3 = []int{11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19} 20 | assert.True(t, Comp(a3, b3)) 21 | 22 | a4 := []int{121, 144, 19, 161, 19, 144, 19, 11} 23 | b4 := []int{11 * 21, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19} 24 | assert.False(t, Comp(a4, b4)) 25 | 26 | b5 := []int{11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19} 27 | assert.False(t, Comp(nil, b5)) 28 | } 29 | -------------------------------------------------------------------------------- /shortest_word/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("this is the ans: ", FindShort("normal_http_call my name isdfs assdf")) 10 | } 11 | 12 | func FindShort(s string) int { 13 | if len(s) <= 0 { 14 | return 0 15 | } 16 | words := strings.Split(s, " ") 17 | lowestWord := words[0] 18 | for _, v := range words { 19 | if len(v) < len(lowestWord) { 20 | lowestWord = v 21 | } 22 | } 23 | return len(lowestWord) 24 | } 25 | -------------------------------------------------------------------------------- /simple_string_indices/simple_string_indices.go: -------------------------------------------------------------------------------- 1 | package simple_string_indices 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | //In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based except in Fortran where it is 1-based. An opening brace will always have a closing brace. Return -1 if there is no answer (in Haskell, return Nothing; in Fortran, return 0; in Go, return an error) 8 | // 9 | //Examples 10 | //solve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10 11 | //solve("((1)23(45))(aB)", 1) = 3 12 | //solve("((1)23(45))(aB)", 2) = -1 // there is no opening bracket at index 2, so return -1 13 | //solve("((1)23(45))(aB)", 6) = 9 14 | //solve("((1)23(45))(aB)", 11) = 14 15 | //solve("((>)|?(*'))(yZ)", 11) = 14 16 | //Input will consist of letters, numbers and special characters, but no spaces. The only brackets will be ( and ). 17 | // 18 | //More examples in the test cases. 19 | // 20 | //Good luck! 21 | 22 | func Solution(str string, idx uint) (uint, error) { 23 | 24 | if str[idx] != '(' { 25 | return 0, errors.New("Not an opening bracket") 26 | } 27 | 28 | stack := 1 29 | for i := idx + 1; i < uint(len(str)); i++ { 30 | if str[i] == '(' { 31 | stack++ 32 | } else if str[i] == ')' { 33 | stack-- 34 | } 35 | if stack == 0 { 36 | return i, nil 37 | } 38 | } 39 | 40 | return 0, nil 41 | } 42 | 43 | func Solution2(s string, i uint) (uint, error) { 44 | if s[i] == '(' { 45 | open := 0 46 | for ; int(i) < len(s); i++ { 47 | switch s[i] { 48 | case '(': 49 | open++ 50 | case ')': 51 | open-- 52 | } 53 | if open == 0 { 54 | return i, nil 55 | } 56 | } 57 | } 58 | return 0, errors.New("Not an opening bracket") 59 | } 60 | -------------------------------------------------------------------------------- /simple_string_indices/simple_string_indices_test.go: -------------------------------------------------------------------------------- 1 | package simple_string_indices 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSolution(t *testing.T) { 9 | 10 | result1, _ := Solution("((1)23(45))(aB)", 0) 11 | result2, _ := Solution2("((1)23(45))(aB)", 11) 12 | 13 | assert.Equal(t, int(result1), 10) 14 | assert.Equal(t, int(result2), 14) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /smallest_positive_integer/smallest_integer.go: -------------------------------------------------------------------------------- 1 | package smallest_positive_integer 2 | 3 | import "sort" 4 | 5 | //This is a demo task. 6 | // 7 | //Write a function: 8 | // 9 | //func Solution(A []int) int 10 | // 11 | //that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. 12 | // 13 | //For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. 14 | // 15 | //Given A = [1, 2, 3], the function should return 4. 16 | // 17 | //Given A = [−1, −3], the function should return 1. 18 | // 19 | //Write an efficient algorithm for the following assumptions: 20 | // 21 | //N is an integer within the range [1..100,000]; 22 | //each element of array A is an integer within the range [−1,000,000..1,000,000]. 23 | //Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. 24 | 25 | func Solution(A []int) int { 26 | 27 | //sort the array: 28 | sort.Ints(A) 29 | 30 | //let the smallest positive integer be 1 31 | x := 1 32 | 33 | for i := 0; i < len(A); i++ { 34 | if A[i] == x { 35 | x++ 36 | } 37 | } 38 | 39 | return x 40 | 41 | } 42 | -------------------------------------------------------------------------------- /smallest_positive_integer/smallest_integer_test.go: -------------------------------------------------------------------------------- 1 | package smallest_positive_integer_test 2 | 3 | import ( 4 | "efficient-algorithms/smallest_positive_integer" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolution(t *testing.T) { 10 | 11 | A := []int{-1, -3} 12 | 13 | ans := smallest_positive_integer.Solution(A) 14 | 15 | assert.EqualValues(t, ans, 1) 16 | } 17 | -------------------------------------------------------------------------------- /smallest_possible_sum/smallest_possible_sum.go: -------------------------------------------------------------------------------- 1 | package smallest_possible_sum 2 | 3 | //Output 4 | //Description 5 | //Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required: 6 | // 7 | //if X[i] > X[j] then X[i] = X[i] - X[j] 8 | // 9 | //When no more transformations are possible, return its sum ("smallest possible sum"). 10 | // 11 | //For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below: 12 | // 13 | //X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9 14 | //X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6 15 | //X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6 16 | //X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3 17 | //X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3 18 | //The returning output is the sum of the final transformation (here 9). 19 | // 20 | //Example 21 | //Solution([]int{6,9,21}) ;-> 9 22 | //Solution steps: 23 | //[6 9 12] //-> X[2] = 21 - 9 24 | //[6 9 6] //-> X[2] = 12 - 6 25 | //[6 3 6] //-> X[1] = 9 - 6 26 | //[6 3 3] //-> X[2] = 6 - 3 27 | //[3 3 3] //-> X[1] = 6 - 3 28 | //Additional notes: 29 | //There are performance tests consisted of very big numbers and arrays of size at least 30000. Please write an efficient algorithm to prevent timeout. 30 | 31 | func Solution(ar []int) int { 32 | result := ar[len(ar)-1] 33 | 34 | for i := len(ar) - 2; i >= 0; i-- { 35 | result = gcd(ar[i], result) 36 | } 37 | return result * len(ar) 38 | } 39 | 40 | func gcd(x, y int) int { 41 | for y != 0 { 42 | x, y = y, x%y 43 | } 44 | return x 45 | } 46 | -------------------------------------------------------------------------------- /smallest_possible_sum/smallest_possible_sum_test.go: -------------------------------------------------------------------------------- 1 | package smallest_possible_sum 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSolution(t *testing.T) { 9 | 10 | assert.Equal(t, Solution([]int{6, 9, 12}), 9) 11 | } 12 | -------------------------------------------------------------------------------- /snail_sort/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Snail(snailMap [][]int) []int { 6 | x := len(snailMap[0]) 7 | myLen := x * x 8 | res := []int{} 9 | 10 | round := 0 11 | 12 | for myLen > 0 { 13 | 14 | for i := round; i < x-round; i++ { 15 | res = append(res, snailMap[round][i]) 16 | myLen -= 1 17 | } 18 | 19 | for i := round + 1; i < x-round; i++ { 20 | res = append(res, snailMap[i][x-1-round]) 21 | myLen -= 1 22 | } 23 | 24 | for i := x - 2 - round; i >= round; i-- { 25 | res = append(res, snailMap[x-1-round][i]) 26 | myLen -= 1 27 | } 28 | 29 | for i := x - 2 - round; i > round; i-- { 30 | res = append(res, snailMap[i][round]) 31 | myLen -= 1 32 | } 33 | round += 1 34 | } 35 | return res 36 | } 37 | 38 | func main() { 39 | 40 | array1 := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} 41 | ans1 := Snail(array1) 42 | fmt.Println(ans1) 43 | } 44 | -------------------------------------------------------------------------------- /snakes_and_ladders/Screenshot 2020-10-13 at 17.56.50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorsteven/golang-algorithm-and-datastructure/6d67dbaf208d0287b8cbffa79cfe6462c08f841c/snakes_and_ladders/Screenshot 2020-10-13 at 17.56.50.png -------------------------------------------------------------------------------- /snakes_and_ladders/snakes_and_ladders_test.go: -------------------------------------------------------------------------------- 1 | package snakes_and_ladders 2 | 3 | // It( fmt.Sprintf("Testing Roll with (%v, %v) to obtain \"%v\"",1, 1,"Player 1 is on square 38"),func() {Expect(game.Play(1, 1)).To(Equal("Player 1 is on square 38"))} ) 4 | 5 | // It( fmt.Sprintf("Testing Roll with (%v, %v) to obtain \"%v\"",1, 5,"Player 1 is on square 44"),func() {Expect(game.Play(1, 5)).To(Equal("Player 1 is on square 44"))} ) 6 | 7 | // It( fmt.Sprintf("Testing Roll with (%v, %v) to obtain \"%v\"",6, 2,"Player 2 is on square 31"),func() {Expect(game.Play(6, 2)).To(Equal("Player 2 is on square 31"))} ) 8 | 9 | // It( fmt.Sprintf("Testing Roll with (%v, %v) to obtain \"%v\"",1, 1,"Player 1 is on square 25"),func() {Expect(game.Play(1, 1)).To(Equal("Player 1 is on square 25"))} ) 10 | -------------------------------------------------------------------------------- /sort/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | //a := []int{1,8,3,9,2} 10 | //fmt.Println(sortInt(a)) 11 | // 12 | //str := []string{"normal_http_call man", "steven", "this", "is a good piece"} 13 | //fmt.Println(sortString(str)) 14 | 15 | fmt.Println(Sort("normal_http_call")) 16 | 17 | } 18 | 19 | func sortInt(a []int) []int { 20 | sort.Slice(a, func(i, j int) bool { 21 | return a[i] < a[j] 22 | }) 23 | return a 24 | } 25 | 26 | //sort the sentence according to the length of the string 27 | func sortString(str []string) []string { 28 | sort.Slice(str, func(i, j int) bool { 29 | return len(str[i]) < len(str[j]) 30 | }) 31 | return str 32 | } 33 | 34 | func sortString2(str []string) []string { 35 | sort.Slice(str, func(i, j int) bool { 36 | return len(str[i]) < len(str[j]) 37 | }) 38 | return str 39 | } 40 | 41 | func Sort(str string) string { 42 | runes := []rune(str) 43 | sort.Slice(runes, func(i, j int) bool { 44 | return runes[i] < runes[j] 45 | }) 46 | return string(runes) 47 | } 48 | -------------------------------------------------------------------------------- /sort_slice/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | ls := []int{12, 34, 79} 10 | sort.Slice(ls, func(i, j int) bool { 11 | return ls[i] > ls[j] 12 | }) 13 | fmt.Println(ls) 14 | } 15 | -------------------------------------------------------------------------------- /split_string_distinct/split_string_distinct.go: -------------------------------------------------------------------------------- 1 | package split_string_distinct 2 | 3 | //Given a string s. Let k be the maximum number of partitions possible of the given string with each partition starts with distinct character. The task is to find the number of ways string s can be split into k partition (non-empty) such that each partition start with distinct character. 4 | 5 | func Solution(s string) int { 6 | 7 | count := make([]int, 26) //the length of the string is the length of alphabets 8 | 9 | //check how many times the same character occurs: 10 | for _, v := range s { 11 | count[v-'a']++ 12 | } 13 | 14 | //making frequency of first character of string equal to 1 15 | count[s[0]-'a'] = 1 16 | 17 | // Finding the product of frequency of occurrence of each character. 18 | ans := 1 19 | 20 | //get the others: 21 | for i := 0; i < 26; i++ { 22 | if count[i] != 0 { 23 | ans *= count[i] 24 | } 25 | } 26 | 27 | return ans 28 | } 29 | -------------------------------------------------------------------------------- /split_string_distinct/split_string_distinct_test.go: -------------------------------------------------------------------------------- 1 | package split_string_distinct_test 2 | 3 | import ( 4 | "efficient-algorithms/split_string_distinct" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestSolution(t *testing.T) { 10 | 11 | samples := []struct { 12 | s string 13 | k int 14 | }{ 15 | { 16 | "acbbcc", 17 | 6, 18 | }, 19 | { 20 | "abb", 21 | 2, 22 | }, 23 | } 24 | 25 | for _, v := range samples { 26 | result := split_string_distinct.Solution(v.s) 27 | 28 | assert.EqualValues(t, result, v.k) 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /string_builder/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | var str strings.Builder 10 | for i := 0; i < 1000; i++ { 11 | str.WriteString("a") 12 | } 13 | fmt.Println(str.String()) 14 | } 15 | -------------------------------------------------------------------------------- /string_ending/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(string_ending("abc", "bc")) 10 | fmt.Println(string_ending("abc", "d")) 11 | 12 | fmt.Println(string_ending2("abc", "bc")) 13 | 14 | } 15 | 16 | func string_ending(str, ending string) bool { 17 | return strings.HasSuffix(str, ending) 18 | } 19 | func string_ending2(str, ending string) bool { 20 | if len(ending) > len(str) { 21 | return false 22 | } 23 | fmt.Println("this is the print first: ", str[len(ending):]) 24 | fmt.Println("this is the print: ", str[len(str)-len(ending):]) 25 | return str[len(str)-len(ending):] == ending 26 | } 27 | -------------------------------------------------------------------------------- /string_revert/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(SpinWords("this is the mainstream grand")) 10 | fmt.Println(SpinWords2("this is the mainstream grand")) 11 | } 12 | 13 | func SpinWords(str string) string { 14 | ans := "" 15 | for _, v := range strings.Split(str, " ") { 16 | if len(v) >= 5 { 17 | var c = strings.Split(v, "") 18 | for i, j := 0, len(c)-1; i < j; i, j = i+1, j-1 { 19 | c[i], c[j] = c[j], c[i] 20 | } 21 | ans += strings.Join(c, "") 22 | ans += " " 23 | } else { 24 | ans += v + " " 25 | } 26 | } 27 | return strings.TrimSpace(ans) 28 | } 29 | 30 | func SpinWords2(str string) string { 31 | ans := "" 32 | for _, v := range strings.Split(str, " ") { 33 | if len(v) >= 5 { 34 | result := "" 35 | for _, w := range v { 36 | result = string(w) + result 37 | } 38 | ans += result 39 | ans += " " 40 | } else { 41 | ans += v + " " 42 | } 43 | } 44 | return strings.TrimSpace(ans) 45 | } 46 | 47 | // this is the quickest way to reverse a word 48 | //func Reserve(s string) (result string) { 49 | // for _, v := range s { 50 | // result = string(v) + result 51 | // } 52 | // return result 53 | //} 54 | -------------------------------------------------------------------------------- /string_to_int/string_to_int.go: -------------------------------------------------------------------------------- 1 | package string_to_int 2 | 3 | import "strings" 4 | 5 | func atoi(s string) (int, error) { 6 | var n []int 7 | origString := s 8 | if s[0] == '-' { 9 | s = s[1:] 10 | } 11 | for _, v := range s { 12 | switch v { 13 | case '1','2','3','4','5','6','7','8','9','0': 14 | n = append(n, int(v - '0')) 15 | default: 16 | return 0, nil 17 | } 18 | } 19 | res := 0 20 | op := 1 21 | for i := len(n) - 1; i >=0; i-- { 22 | res += n[i] * op 23 | op *= 10 24 | } 25 | 26 | if strings.Contains(origString, "-") { 27 | res = res * -1 28 | } 29 | return res, nil 30 | } 31 | -------------------------------------------------------------------------------- /string_to_int/string_to_int_test.go: -------------------------------------------------------------------------------- 1 | package string_to_int 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | 9 | func test_atoi(s string, expected int) { 10 | res, err := atoi(s) 11 | if res != expected { 12 | fmt.Printf("got %d expected %d", res, expected) 13 | } 14 | if err != nil { 15 | fmt.Printf("got %v expected nil", err) 16 | } 17 | } 18 | 19 | func TestAtoi(t *testing.T) { 20 | test_atoi("123", 123) 21 | test_atoi("sew", 0) 22 | test_atoi("-543", -543) 23 | } 24 | -------------------------------------------------------------------------------- /strings/reverse_string.go: -------------------------------------------------------------------------------- 1 | package strings 2 | 3 | func reverse_string(s string) string { 4 | runes := []rune(s) 5 | n := len(runes) 6 | for i,j := 0, n-1; i < j; i,j = i + 1, j-1 { 7 | runes[i], runes[j] = runes[j], runes[i] 8 | } 9 | return string(runes) 10 | } 11 | -------------------------------------------------------------------------------- /strings/reverse_string_test.go: -------------------------------------------------------------------------------- 1 | package strings 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestReverseString(t *testing.T) { 9 | assert.Equal(t, "yebba", reverse_string("abbey")) 10 | } 11 | -------------------------------------------------------------------------------- /strings/vowel_count.go: -------------------------------------------------------------------------------- 1 | package strings 2 | 3 | func vowel_count(s string) int { 4 | sum := 0 5 | for _, v := range s { 6 | switch v { 7 | case 'a','e','i','o','u': 8 | sum++ 9 | } 10 | } 11 | return sum 12 | } 13 | -------------------------------------------------------------------------------- /strings/vowel_count_test.go: -------------------------------------------------------------------------------- 1 | package strings 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestVowelCount(t *testing.T) { 9 | assert.Equal(t, 6, vowel_count("aweruhedbage")) 10 | } 11 | -------------------------------------------------------------------------------- /struct_to_json/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type Customer struct { 9 | Name string `json:"name"` 10 | Age int `json:"age"` 11 | } 12 | 13 | func main() { 14 | cus := Customer{ 15 | Name: "Mike", 16 | Age: 30, 17 | } 18 | str, err := struct_to_json(cus) 19 | if err != nil { 20 | fmt.Printf("the input must be of type Customer struct, but '%T' was given\n", cus) 21 | } 22 | fmt.Println(str) 23 | 24 | jsonValue := `{"name": "oke", "age": 60}` 25 | 26 | the_struct, err := json_to_struct(jsonValue) 27 | if err != nil { 28 | fmt.Println("Cannot convert json to struct") 29 | } 30 | fmt.Println(the_struct) 31 | } 32 | 33 | func struct_to_json(val interface{}) (string, error) { 34 | theByte, err := json.Marshal(val.(Customer)) //make sure the interface is a Customer struct 35 | if err != nil { 36 | return "", err 37 | } 38 | return string(theByte), nil 39 | } 40 | 41 | func json_to_struct(str string) (Customer, error) { 42 | the_struct := Customer{} 43 | err := json.Unmarshal([]byte(str), &the_struct) 44 | if err != nil { 45 | return the_struct, err 46 | } 47 | return the_struct, nil 48 | } 49 | -------------------------------------------------------------------------------- /subsequence/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | fmt.Println("This is the lcs: ", LCS("AGGTAB", "GXTXAYB")) 9 | 10 | fmt.Println("this is one string: ", runner("asdf")) 11 | } 12 | 13 | func runner(s string) string { 14 | 15 | return string(s[0]) 16 | } 17 | 18 | func LCS(s1, s2 string) string { 19 | m := len(s1) 20 | n := len(s2) 21 | if m == 0 || n == 0 { 22 | return "" 23 | } else if s1[m-1] == s2[n-1] { 24 | return LCS(s1[:m-1], s2[:n-1]) + string(s1[m-1]) 25 | } 26 | v1 := LCS(s1, s2[:n-1]) 27 | v2 := LCS(s1[:m-1], s2) 28 | if len(v1) > len(v2) { 29 | return v1 30 | } 31 | return v2 32 | } 33 | -------------------------------------------------------------------------------- /subsequence_product_sum/subsequence_product_sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //package subsequence_product_sum 4 | 5 | import "fmt" 6 | 7 | //Given an array of integers and an integer m, return the sum of the product of its subsequences of length m. 8 | // 9 | //Ex1: 10 | // 11 | //a := []int{1, 2, 3} 12 | //m := 2 13 | //the subsequences(of length 2) are (1,2) (1,3) (2,3), you should multiply the numbers of each subsequence and take their sum 14 | // 15 | //ProductSum = (1*2) + (1*3) + (2*3) //=> 11 16 | //Ex2: 17 | // 18 | //a := []int{2,3,4,5} 19 | //m := 3 20 | //the subsequences(of length 3) are (2,3,4) (2,4,5) (2,3,5) (3,4,5) 21 | // 22 | //ProductSum = (2*3*4) + (2*3*5) + (2*4*5) + (3*4*5) //=> 154 23 | //Task: 24 | //Write a function productSum(a, m) that does as described above 25 | // 26 | //The sum can be really large, so return the result in modulo 109+7 27 | // 28 | //Constraints 29 | //0 <= A[i] < 1000000 30 | // 31 | //1 < k <= 50 32 | //99 random tests |A| = 10^5 33 | //1 big test |A| = 10^6 34 | //k < |A| 35 | 36 | func main() { 37 | a := ProductSum([]int{1, 2, 3}, 2) 38 | 39 | b := ProductSum([]int{2, 3, 4, 5}, 3) 40 | 41 | fmt.Println(a) 42 | fmt.Println(b) 43 | } 44 | 45 | //func ProductSum(a []int, m int) int { 46 | // 47 | // //result := 0 48 | // 49 | // for i := 0; i < len(a); i++ { 50 | // 51 | // rel := a[i:m] 52 | // 53 | // fmt.Println(rel) 54 | // 55 | // //result = 56 | // 57 | // } 58 | // 59 | // return -1 60 | //} 61 | 62 | func ProductSum(a []int, m int) int { 63 | sm, n, M := make([]int, len(a)), len(a), 1000000007 64 | 65 | p := make([][]int, n+1) 66 | 67 | copy(sm, a) 68 | 69 | for i := 0; i <= n; i++ { 70 | p[i] = make([]int, m+1) 71 | } 72 | for i := n - 2; i >= 0; i-- { 73 | sm[i] = (sm[i] + sm[i+1]) % M 74 | } 75 | for i := n - 1; i >= 0; i-- { 76 | for k := 1; k < m+1; k++ { 77 | if k == 1 { 78 | p[i][k] = sm[i] 79 | continue 80 | } 81 | p[i][k] = ((a[i] * p[i+1][k-1] % M) + p[i+1][k]) % M 82 | } 83 | } 84 | return p[0][m] 85 | } 86 | -------------------------------------------------------------------------------- /subsequence_product_sum/subsequence_product_sum_test.go: -------------------------------------------------------------------------------- 1 | //package subsequence_product_sum 2 | package main 3 | -------------------------------------------------------------------------------- /temp/fibonacci.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | func fibonacci(n int) int { 4 | if n < 2 { 5 | return n 6 | } 7 | result := fibonacci(n-1) + fibonacci(n-2) 8 | return result 9 | } 10 | 11 | func loopFib(n int) int { 12 | fibBox := []int{0,1} 13 | for i := 0; i < n; i++ { 14 | value := fibBox[i] + fibBox[i+1] 15 | fibBox = append(fibBox, value) 16 | } 17 | return fibBox[n] 18 | } 19 | -------------------------------------------------------------------------------- /temp/fibonacci_test.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestFibonacci(t *testing.T) { 9 | assert.Equal(t, 13, fibonacci(7)) 10 | assert.Equal(t, 13, loopFib(7)) 11 | } 12 | -------------------------------------------------------------------------------- /temp/fizzbuzz.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func fizzbuzz(n int) string { 8 | result := "" 9 | for i := 1; i < n; i++ { 10 | switch { 11 | case i % 5 == 0 && i % 3 == 0: 12 | result += "fizzbuzz" 13 | case i % 3 == 0: 14 | result += "fizz" 15 | case i % 5 == 0: 16 | result += "buzz" 17 | default: 18 | result += strconv.Itoa(i) 19 | } 20 | } 21 | return result 22 | } 23 | -------------------------------------------------------------------------------- /temp/fizzbuzz_test.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestFizzBuzz(t *testing.T) { 9 | assert.Equal(t, "12fizz4buzzfizz78fizz", fizzbuzz(10)) 10 | assert.Equal(t, "12fizz4buzzfizz78fizzbuzz11fizz1314", fizzbuzz(15)) 11 | } -------------------------------------------------------------------------------- /temp/palindrome.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | const ( 4 | capitalA rune = 'A' 5 | capitalZ rune = 'Z' 6 | smallA rune = 'a' 7 | smallZ rune = 'z' 8 | ) 9 | 10 | func Palindrome(s string) bool { 11 | runes := []rune(s) 12 | i := 0 13 | j := len(runes) - 1 14 | 15 | for i < j { 16 | if !isCharacter(runes[i]) { 17 | i++ 18 | continue 19 | } 20 | if !isCharacter(runes[j]) { 21 | j-- 22 | continue 23 | } 24 | if runes[i] != runes[j] { 25 | return false 26 | } 27 | i++ 28 | j-- 29 | } 30 | return true 31 | } 32 | 33 | func isCharacter(char rune) bool { 34 | if char >= capitalA && char <= capitalZ { 35 | return true 36 | } 37 | if char >= smallA && char <= smallZ { 38 | return true 39 | } 40 | return false 41 | } 42 | 43 | func isCaseInsensitive(char rune) bool { 44 | if char >= smallA && char <= capitalZ { 45 | return true 46 | } 47 | return false 48 | } 49 | 50 | func Pali(s string) bool { 51 | runes := []rune(s) 52 | i := 0 53 | j := len(runes) - 1 54 | 55 | for i < j { 56 | if isCaseInsensitive(runes[i]) { 57 | i++ 58 | continue 59 | } 60 | if isCaseInsensitive(runes[j]) { 61 | j-- 62 | continue 63 | } 64 | if runes[i] != runes[j] { 65 | return false 66 | } 67 | i++ 68 | j-- 69 | } 70 | return true 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /temp/palindrome_test.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPalindrome(t *testing.T) { 9 | assert.False(t, Palindrome("hello")) 10 | assert.True(t, Palindrome("ada")) 11 | assert.True(t, Palindrome("hannah")) 12 | 13 | assert.False(t, Pali("hello")) 14 | assert.True(t, Pali("ada")) 15 | assert.True(t, Pali("hannah")) 16 | } 17 | -------------------------------------------------------------------------------- /temp/prime_factor.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | func prime_factors(n int) []int { 4 | divisor := 2 5 | var factors []int 6 | for n > 1 { 7 | if n % divisor == 0 { 8 | factors = append(factors, divisor) 9 | n = n/divisor 10 | } else { 11 | divisor++ 12 | } 13 | } 14 | return factors 15 | } 16 | -------------------------------------------------------------------------------- /temp/prime_factor_test.go: -------------------------------------------------------------------------------- 1 | package temp 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestPrimeFactors(t *testing.T) { 9 | assert.Equal(t, []int{2,5}, prime_factors(10)) 10 | } 11 | -------------------------------------------------------------------------------- /tortoise_racing/tortoise_racing.go: -------------------------------------------------------------------------------- 1 | //package tortoise_racing 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | //Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage. 9 | // 10 | //When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A? 11 | // 12 | //More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A? 13 | // 14 | //The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages. 15 | // 16 | //If v1 >= v2 then return nil, nothing, null, None or {-1, -1, -1} for C++, C, Go, Nim, [] for Kotlin or "-1 -1 -1". 17 | 18 | func Race(v1, v2, g int) [3]int { 19 | // your code 20 | if v1 >= v2 { 21 | return [3]int{-1, -1, -1} 22 | } 23 | 24 | SpeedDiv := v2 - v1 25 | 26 | t := g * 3600 / SpeedDiv 27 | 28 | h := t / 3600 29 | t = t % 3600 //what is left of the hours 30 | 31 | m := t / 60 32 | s := t % 60 //what is left of the minutes 33 | 34 | return [3]int{h, m, s} 35 | } 36 | 37 | func main() { 38 | 39 | ans := Race(720, 850, 70) 40 | 41 | fmt.Println(ans) //Output [0 32 18] 42 | 43 | } 44 | -------------------------------------------------------------------------------- /trees/inverttrees/invertbinarytrees/invert_binary_trees.go: -------------------------------------------------------------------------------- 1 | package invertbinarytrees 2 | 3 | import "efficient-algorithms/datastructures/trees" 4 | 5 | //func InvertTree(node *trees.BinaryNode) *trees.BinaryNode { 6 | // if node == nil { 7 | // return nil 8 | // } 9 | // 10 | // node.Left, node.Right = InvertTree(node.Right), InvertTree(node.Left) 11 | // 12 | // return node 13 | //} 14 | 15 | // InvertTree inverts a binary tree 16 | func InvertTree(node *trees.BinaryNode) *trees.BinaryNode { 17 | if node == nil { 18 | return nil 19 | } 20 | 21 | node.Left, node.Right = InvertTree(node.Right), InvertTree(node.Left) 22 | return node 23 | } 24 | -------------------------------------------------------------------------------- /trees/inverttrees/invertbinarytrees/invert_binary_trees_test.go: -------------------------------------------------------------------------------- 1 | package invertbinarytrees 2 | 3 | import ( 4 | "efficient-algorithms/datastructures/trees" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestInvertTree(t *testing.T) { 10 | 11 | node2 := &trees.BinaryNode{Data: 2} 12 | node3 := &trees.BinaryNode{Data: 3} 13 | node := &trees.BinaryNode{Data: 1, Left: node2, Right: node3} 14 | 15 | node = InvertTree(node) 16 | 17 | assert.Equal(t, node.Left.Data, 3) 18 | assert.Equal(t, node.Right.Data, 2) 19 | } 20 | -------------------------------------------------------------------------------- /tribonacci/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //Well met with Fibonacci bigger brother, AKA Tribonacci. 6 | //As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :( 7 | //So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence: 8 | //[1, 1 ,1, 3, 5, 9, 17, 31, ...] 9 | //But what if we started with [0, 0, 1] as a signature? As starting with [0, 1] instead of [1, 1] basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get: 10 | //[0, 0, 1, 1, 2, 4, 7, 13, 24, ...] 11 | //Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a signature array/list, returns the first n elements - signature included of the so seeded sequence. 12 | //Signature will always contain 3 numbers; n will always be a non-negative number; if n == 0, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;) 13 | 14 | func main() { 15 | //fmt.Println(Tribonacci([3]float64{1,1,1}, 2)) 16 | //fmt.Println(Tribonacci2([]float64{1,1,1}, 10)) 17 | fmt.Println(Tribonacci3([3]float64{1, 1, 1}, 2)) 18 | } 19 | func Tribonacci(signature [3]float64, n int) (r []float64) { 20 | r = signature[:] 21 | for i := 0; i < n; i++ { 22 | l := len(r) 23 | r = append(r, r[l-1]+r[l-2]+r[l-3]) 24 | } 25 | return r[:n] 26 | } 27 | 28 | //func Tribonacci2(signature []float64, n int) (r []float64) { 29 | // r = signature 30 | // for i := 0; i < n; i++ { 31 | // l := len(r) 32 | // r = append(r, r[l-1] + r[l-2] + r[l-3]) 33 | // } 34 | // return r[:n] 35 | //} 36 | 37 | //more readable 38 | func Tribonacci3(signature [3]float64, n int) []float64 { 39 | result := signature[:] 40 | if n <= 3 { 41 | return result[:n] 42 | } 43 | for i := 3; i < n; i++ { 44 | sum := result[i-3] + result[i-2] + result[i-1] 45 | result = append(result, sum) 46 | } 47 | return result 48 | } 49 | -------------------------------------------------------------------------------- /turing/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | func makeSquares(array [10]int) { 9 | for index, elem := range array { 10 | array[index] = elem * elem 11 | } 12 | } 13 | 14 | func makeSquaresInt(slice []int) { 15 | for index, elem := range slice { 16 | slice[index] = elem * elem 17 | } 18 | } 19 | 20 | func main() { 21 | s10 := make([]int, 2, 4) 22 | fmt.Printf("The print: s10=%v\n", s10) 23 | sy := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 24 | fmt.Println(sy[2:]) 25 | fmt.Println(sy[:4]) 26 | fmt.Println(sy[2:4]) 27 | fmt.Println(sy[:]) 28 | sc := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 29 | makeSquaresInt(sc) 30 | fmt.Println(sc) 31 | 32 | a := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 33 | makeSquares(a) 34 | fmt.Println("the a's: ", a) //the remain the same as the above a, i think because an array was used in its square method 35 | 36 | s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 37 | s = append(s[:2], s[3:]...) 38 | fmt.Println(s) 39 | 40 | //s1 := []int{0, 1, 2, 3} 41 | //s2 := []int{0, 1, 2, 3} 42 | //fmt.Println(s1 == s2) //compilation error. you dont check slices this way 43 | 44 | var sp Shape 45 | fmt.Println("value of s is", sp) 46 | fmt.Printf("type of s is %T\n", sp) 47 | 48 | var sa Shape 49 | sa = Rect{5.0, 4.0} 50 | r := Rect{5.0, 4.0} 51 | fmt.Println(sa == r) //true 52 | 53 | var sb Shape = Rect{10, 3} 54 | fmt.Println(sb) 55 | 56 | fmt.Println("main() started") 57 | var wg sync.WaitGroup 58 | //wg.Add(1) 59 | go service(wg) 60 | 61 | wg.Wait() 62 | select {} 63 | fmt.Println("main() stopped") 64 | } 65 | 66 | type Shape interface { 67 | Area() float64 68 | Perimeter() float64 69 | } 70 | 71 | type Rect struct { 72 | width float64 73 | height float64 74 | } 75 | 76 | func (r Rect) Area() float64 { 77 | return r.width * r.height 78 | } 79 | 80 | func (r Rect) Perimeter() float64 { 81 | return 2 * (r.width + r.height) 82 | } 83 | 84 | func service(wg sync.WaitGroup) { 85 | wg.Add(1) 86 | fmt.Println("Hello from service!") 87 | wg.Done() 88 | 89 | } 90 | -------------------------------------------------------------------------------- /twice_linear/twice_linear.go: -------------------------------------------------------------------------------- 1 | package twice_linear 2 | 3 | //Consider a sequence u where u is defined as follows: 4 | // 5 | //The number u(0) = 1 is the first one in u. 6 | //For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too. 7 | //There are no other numbers in u. 8 | //Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...] 9 | // 10 | //1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on... 11 | // 12 | //Task: 13 | //Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates). 14 | // 15 | //Example: 16 | //dbl_linear(10) should return 22 17 | // 18 | //Note: 19 | //Focus attention on efficiency 20 | 21 | func DblLinear(n int) int { 22 | // your code 23 | u := []int{1} 24 | i := 0 25 | j := 0 26 | 27 | var y int 28 | var z int 29 | 30 | for len(u) <= n { 31 | y = 2*u[i] + 1 32 | z = 3*u[j] + 1 33 | 34 | if y < z { 35 | u = append(u, y) 36 | i++ 37 | } else if y > z { 38 | u = append(u, z) 39 | j++ 40 | } else { 41 | u = append(u, y) 42 | i++ 43 | j++ 44 | } 45 | } 46 | //fmt.Println(u) 47 | return u[len(u)-1] 48 | } 49 | 50 | func DblLinear2(n int) int { 51 | 52 | u := make([]int, 0) 53 | 54 | u = append(u, 1) 55 | x, y := 0, 0 56 | 57 | for i := 0; i < n; i++ { 58 | 59 | next := 2*u[x] + 1 60 | neyt := 3*u[y] + 1 61 | 62 | if next <= neyt { 63 | u = append(u, next) 64 | x++ 65 | if next == neyt { 66 | y++ 67 | } 68 | } else { 69 | u = append(u, neyt) 70 | y++ 71 | } 72 | } 73 | return u[n] 74 | } 75 | -------------------------------------------------------------------------------- /twice_linear/twice_linear_test.go: -------------------------------------------------------------------------------- 1 | package twice_linear 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestDblLinear(t *testing.T) { 9 | 10 | assert.Equal(t, DblLinear(50), 175) 11 | assert.Equal(t, DblLinear(100), 447) 12 | assert.Equal(t, DblLinear2(500), 3355) 13 | assert.Equal(t, DblLinear2(1000), 8488) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /two_oldest_ages/main.go: -------------------------------------------------------------------------------- 1 | package two_oldest_ages 2 | 3 | import "sort" 4 | 5 | //The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age]. 6 | // 7 | //The order of the numbers passed in could be any order. The array will always include at least 2 items. 8 | // 9 | //For example: 10 | // 11 | //TwoOldestAges([]int{1, 5, 87, 45, 8, 8}) // should return [2]int{45, 87} 12 | 13 | func TwoOldestAges(ages []int) [2]int { 14 | a, b := 0, 0 15 | for _, v := range ages { 16 | if v > b { 17 | a, b = b, v 18 | } else if v > a { 19 | a = v 20 | } 21 | } 22 | return [2]int{a, b} 23 | } 24 | 25 | func TwoOldestAges2(ages []int) [2]int { 26 | 27 | sort.Sort(sort.Reverse(sort.IntSlice(ages))) 28 | 29 | return [2]int{ages[1], ages[0]} 30 | } 31 | 32 | func TwoOldestAges3(ages []int) [2]int { 33 | 34 | sort.Ints(ages) 35 | 36 | first, second := ages[len(ages)-1], ages[len(ages)-2] 37 | 38 | return [2]int{second, first} 39 | 40 | } 41 | -------------------------------------------------------------------------------- /two_sum/two_sum.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | //Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2). 4 | // 5 | //For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted. 6 | // 7 | //The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array). 8 | // 9 | //Based on: http://oj.leetcode.com/problems/two-sum/ 10 | // 11 | //twoSum [1, 2, 3] 4 === (0, 2) 12 | 13 | func TwoSum(numbers []int, target int) [2]int { 14 | 15 | for i := 0; i < len(numbers)-1; i++ { 16 | for j := i + 1; j < len(numbers); j++ { 17 | if numbers[i]+numbers[j] == target { 18 | return [2]int{i, j} 19 | } 20 | } 21 | } 22 | return [2]int{} 23 | } 24 | 25 | func TwoSum2(numbers []int, target int) [2]int { 26 | 27 | for i, num1 := range numbers { 28 | for j, num2 := range numbers { 29 | if i != j && num1+num2 == target { 30 | return [2]int{i, j} 31 | } 32 | } 33 | } 34 | return [2]int{} 35 | } 36 | -------------------------------------------------------------------------------- /two_sum/two_sum_test.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestTwoSum(t *testing.T) { 9 | 10 | assert.Equal(t, TwoSum([]int{1, 2, 3}, 4), [2]int{0, 2}) 11 | 12 | assert.Equal(t, TwoSum2([]int{1234, 5678, 9012}, 14690), [2]int{1, 2}) 13 | 14 | } 15 | -------------------------------------------------------------------------------- /two_to_one/two_to_one.go: -------------------------------------------------------------------------------- 1 | package two_to_one 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strings" 7 | ) 8 | 9 | //Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, 10 | // 11 | //each taken only once - coming from s1 or s2. 12 | //Examples: 13 | //a = "xyaabbbccccdefww" 14 | //b = "xxxxyyyyabklmopq" 15 | //longest(a, b) -> "abcdefklmopqwxy" 16 | // 17 | //a = "abcdefghijklmnopqrstuvwxyz" 18 | //longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" 19 | 20 | func distinct(s string) string { 21 | 22 | dis := make(map[rune]bool) 23 | 24 | str := "" 25 | 26 | for _, v := range s { 27 | if val := dis[v]; !val { 28 | dis[v] = true 29 | str += fmt.Sprintf("%c", v) 30 | } 31 | } 32 | return str 33 | } 34 | 35 | func TwoToOne(s1 string, s2 string) string { 36 | 37 | totalString := s1 + s2 38 | 39 | finalString := distinct(totalString) 40 | 41 | strArr := strings.Split(finalString, "") 42 | 43 | sort.Strings(strArr) 44 | 45 | return strings.Join(strArr, "") 46 | 47 | } 48 | 49 | func TwoToOne2(s1, s2 string) string { 50 | 51 | strArr := strings.Split(s1+s2, "") 52 | sort.Strings(strArr) 53 | 54 | result := "" 55 | 56 | for _, s := range strArr { 57 | if !strings.Contains(result, s) { 58 | result += s 59 | } 60 | } 61 | return result 62 | } 63 | 64 | func TwoToOne3(s1, s2 string) string { 65 | 66 | result := "" 67 | for _, char := range strings.Split("abcdefghijklmnopqrstuvwxyz", "") { 68 | if strings.Contains(s1+s2, char) { 69 | result += char 70 | } 71 | } 72 | return result 73 | } 74 | -------------------------------------------------------------------------------- /two_to_one/two_to_one_test.go: -------------------------------------------------------------------------------- 1 | package two_to_one 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestTwoToOne(t *testing.T) { 9 | 10 | assert.Equal(t, TwoToOne("aretheyhere", "yestheyarehere"), "aehrsty") 11 | 12 | assert.Equal(t, TwoToOne2("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu") 13 | 14 | assert.Equal(t, TwoToOne3("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu") 15 | 16 | } 17 | -------------------------------------------------------------------------------- /upside_down/upside_down.go: -------------------------------------------------------------------------------- 1 | package upside_down 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | //Consider the numbers 6969 and 9116. When you rotate them 180 degrees (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as 2 or 5 don't yield numbers when rotated. 9 | // 10 | //Given a range, return the count of upside down numbers within that range. For example, solve(0,10) = 3, because there are only 3 upside down numbers >= 0 and < 10. They are 0, 1, 8. 11 | // 12 | //More examples in the test cases. 13 | // 14 | //Good luck! 15 | // 16 | //If you like this Kata, please try 17 | // 18 | //Simple Prime Streaming 19 | // 20 | //Life without primes 21 | // 22 | //Please also try the performance version of this kata at Upside down numbers - Challenge Edition 23 | 24 | func Solution(a, b int) int { 25 | 26 | count := 0 27 | 28 | for i := a; i < b; i++ { 29 | if upsideDown(i) { 30 | count++ 31 | } 32 | } 33 | return count 34 | } 35 | 36 | func upsideDown(x int) bool { 37 | 38 | str := strconv.Itoa(x) 39 | 40 | strRev := reverse(str) 41 | strArr := strings.Split(strRev, "") 42 | 43 | result := "" 44 | for _, v := range strArr { 45 | result += upsideNumbers(v) 46 | } 47 | 48 | value, _ := strconv.Atoi(result) 49 | 50 | return value == x 51 | } 52 | 53 | func upsideNumbers(s string) string { 54 | switch s { 55 | case "0": 56 | return "0" 57 | case "1": 58 | return "1" 59 | case "6": 60 | return "9" 61 | case "8": 62 | return "8" 63 | case "9": 64 | return "6" 65 | } 66 | return "" 67 | } 68 | 69 | func reverse(s string) string { 70 | 71 | runes := []rune(s) 72 | for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 73 | runes[i], runes[j] = runes[j], runes[i] 74 | } 75 | 76 | return string(runes) 77 | } 78 | -------------------------------------------------------------------------------- /upside_down/upside_down_test.go: -------------------------------------------------------------------------------- 1 | package upside_down 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSolution(t *testing.T) { 9 | 10 | assert.Equal(t, Solution(0, 10), 3) 11 | assert.Equal(t, Solution(10, 100), 4) 12 | assert.Equal(t, Solution(1000, 10000), 20) 13 | assert.Equal(t, Solution(10000, 15000), 6) 14 | assert.Equal(t, Solution(15000, 20000), 9) 15 | assert.Equal(t, Solution(60000, 70000), 15) 16 | assert.Equal(t, Solution(60000, 130000), 55) 17 | 18 | } 19 | 20 | //func TestReverseNow(t *testing.T) { 21 | // 22 | // assert.Equal(t, ReverseNow("green"), "neerg") 23 | //} 24 | -------------------------------------------------------------------------------- /upside_down_2/upside_down_2_test.go: -------------------------------------------------------------------------------- 1 | package upside_down_2 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestUpsideDown(t *testing.T) { 9 | 10 | assert.Equal(t, UpsideDown("0", "10"), uint64(3)) 11 | assert.Equal(t, UpsideDown("0", "10"), uint64(3)) 12 | assert.Equal(t, UpsideDown("6", "25"), uint64(2)) 13 | assert.Equal(t, UpsideDown("10", "100"), uint64(4)) 14 | assert.Equal(t, UpsideDown("100", "1000"), uint64(12)) 15 | //assert.Equal(t, UpsideDown("100000","12345678900000000"), uint64(718650)) 16 | } 17 | -------------------------------------------------------------------------------- /utf8_length/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unicode/utf8" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(utf8.RuneCountInString("你好")) 10 | } 11 | -------------------------------------------------------------------------------- /valid_braces/valid_braces_test.go: -------------------------------------------------------------------------------- 1 | package valid_braces 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestValidBraces(t *testing.T) { 9 | 10 | assert.Equal(t, ValidBraces("(){}[]"), true) 11 | 12 | assert.Equal(t, ValidBraces("([{}])"), true) 13 | 14 | assert.Equal(t, ValidBraces("(}"), false) 15 | 16 | assert.Equal(t, ValidBraces("[(])"), false) 17 | // 18 | //assert.Equal(t, ValidBraces("[({})](]"), false) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /valid_parentheses/valid_parentheses.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | ) 7 | 8 | //Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. 9 | 10 | //Examples 11 | //"()" => true 12 | //")(()))" => false 13 | //"(" => false 14 | //"(())((()())())" => true 15 | 16 | //Constraints 17 | //0 <= input.length <= 100 18 | 19 | func ValidParentheses(parens string) bool { 20 | 21 | if len(parens) >= 100 { 22 | return false 23 | } 24 | 25 | b := 0 26 | for _, c := range parens { 27 | if c == '(' { 28 | b++ 29 | } else { 30 | b-- 31 | } 32 | if b < 0 { 33 | return false 34 | } 35 | } 36 | return b == 0 37 | } 38 | 39 | func ValidParentheses2(parens string) bool { 40 | 41 | if len(parens) >= 100 { 42 | return false 43 | } 44 | 45 | _, err := regexp.Compile(parens) 46 | 47 | return err == nil 48 | } 49 | 50 | func ValidParentheses3(parens string) bool { 51 | 52 | if len(parens) >= 100 { 53 | return false 54 | } 55 | 56 | for strings.Contains(parens, "()") { 57 | parens = strings.Replace(parens, "()", "", -1) 58 | } 59 | return len(parens) == 0 60 | } 61 | 62 | func ValidParentheses4(parens string) bool { 63 | 64 | n := 0 65 | 66 | for _, char := range parens { 67 | switch char { 68 | case '(': 69 | n++ 70 | case ')': 71 | n-- 72 | } 73 | if n < 0 { 74 | return false 75 | } 76 | } 77 | return n == 0 78 | } 79 | -------------------------------------------------------------------------------- /valid_parentheses/valid_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses_test 2 | 3 | import ( 4 | "efficient-algorithms/valid_parentheses" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestValidParentheses(t *testing.T) { 10 | 11 | assert.False(t, valid_parentheses.ValidParentheses(")")) 12 | assert.False(t, valid_parentheses.ValidParentheses2(")(()))")) 13 | assert.True(t, valid_parentheses.ValidParentheses2("()")) 14 | assert.True(t, valid_parentheses.ValidParentheses3("(())((()())())")) 15 | 16 | assert.True(t, valid_parentheses.ValidParentheses4("(())((()())())")) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /variadic_sum/variadic_sum.go: -------------------------------------------------------------------------------- 1 | package variadic_sum 2 | 3 | //Sum function sums any number of elements given to it: 4 | 5 | func Sum(nums ...int) int { 6 | 7 | total := 0 8 | 9 | for _, num := range nums { 10 | 11 | total += num 12 | } 13 | return total 14 | } 15 | -------------------------------------------------------------------------------- /variadic_sum/variadic_sum_test.go: -------------------------------------------------------------------------------- 1 | package variadic_sum 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSum(t *testing.T) { 9 | 10 | assert.Equal(t, Sum(3, 4, 5), 12) 11 | assert.Equal(t, Sum(1, 4, 5), 10) 12 | assert.Equal(t, Sum(5), 5) 13 | 14 | nums := []int{1, 2, 3, 4, 5} 15 | 16 | assert.Equal(t, Sum(nums...), 15) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /vasya_clerk/vasya_clerk_test.go: -------------------------------------------------------------------------------- 1 | package vasya_clerk 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestTickets(t *testing.T) { 9 | 10 | assert.Equal(t, Tickets([]int{25, 25, 50}), "YES") 11 | assert.Equal(t, Tickets2([]int{25, 100}), "NO") 12 | assert.Equal(t, Tickets3([]int{25, 25, 50, 50, 100}), "NO") 13 | 14 | } 15 | -------------------------------------------------------------------------------- /vowel_count/vowel_count.go: -------------------------------------------------------------------------------- 1 | package vowel_count 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | ) 7 | 8 | //Return the number (count) of vowels in the given string. 9 | // 10 | //We will consider a, e, i, o, u as vowels for this Kata (but not y). 11 | // 12 | //The input string will only consist of lower case letters and/or spaces. 13 | 14 | func GetCount(str string) (count int) { 15 | 16 | count = 0 17 | for _, v := range strings.ToLower(str) { 18 | switch v { 19 | case 'a': 20 | count++ 21 | case 'e': 22 | count++ 23 | case 'i': 24 | count++ 25 | case 'o': 26 | count++ 27 | case 'u': 28 | count++ 29 | } 30 | } 31 | 32 | return count 33 | } 34 | 35 | func GetCount2(str string) (count int) { 36 | for _, c := range str { 37 | switch c { 38 | case 'a', 'e', 'i', 'o', 'u': 39 | count++ 40 | } 41 | } 42 | return count 43 | } 44 | 45 | func GetCount3(strn string) int { 46 | count := 0 47 | vowels := []string{"a", "e", "i", "o", "u"} 48 | 49 | for _, vowel := range vowels { 50 | count += strings.Count(strn, vowel) 51 | } 52 | return count 53 | } 54 | 55 | func GetCount4(str string) int { 56 | 57 | r := regexp.MustCompile("[aeiou]") 58 | 59 | vowels := r.FindAllString(str, -1) 60 | 61 | return len(vowels) 62 | } 63 | -------------------------------------------------------------------------------- /vowel_count/vowel_count_test.go: -------------------------------------------------------------------------------- 1 | package vowel_count_test 2 | 3 | import ( 4 | "efficient-algorithms/vowel_count" 5 | "github.com/stretchr/testify/assert" 6 | "testing" 7 | ) 8 | 9 | func TestGetCount(t *testing.T) { 10 | 11 | assert.Equal(t, vowel_count.GetCount("hellomme"), 3) 12 | 13 | assert.Equal(t, vowel_count.GetCount4(" uethhztm sggi rprrxl risbs hsclup"), 5) 14 | } 15 | -------------------------------------------------------------------------------- /vowels/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(vowel("hellohellohelloa")) 7 | 8 | //fmt.Println("ans: ", vowel("I wonder how many vowels?")) 9 | 10 | //if vowel("I wonder how many vowels?") == 7 && vowel("Ethan likes cheddar cheese") == 9 { 11 | // fmt.Println(":) Correct! :)") 12 | //} else { 13 | // fmt.Println(":(") 14 | //} 15 | 16 | } 17 | 18 | func vowel(myString string) int { 19 | count := 0 20 | //for _, value := range myString { 21 | // switch value { 22 | // case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U': 23 | // count++ 24 | // } 25 | //} 26 | 27 | for _, v := range myString { 28 | switch { 29 | case string(v) == "a": 30 | count++ 31 | case string(v) == "e": 32 | count++ 33 | case string(v) == "i": 34 | count++ 35 | case string(v) == "o": 36 | count++ 37 | case string(v) == "u": 38 | count++ 39 | case string(v) == "A": 40 | count++ 41 | case string(v) == "E": 42 | count++ 43 | case string(v) == "I": 44 | count++ 45 | case string(v) == "O": 46 | count++ 47 | case string(v) == "U": 48 | count++ 49 | } 50 | } 51 | return count 52 | } 53 | -------------------------------------------------------------------------------- /wait_group/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | boysData := "Mike 3rd, Victor 2nd, Kalu 1st, Ode 4th, Grand 5th" 10 | fmt.Println(boys(boysData)) 11 | } 12 | 13 | func boys(b string) map[string]string { 14 | ans := make(map[string]string) 15 | bSlice := strings.Split(b, ",") 16 | for _, v := range bSlice { 17 | w := strings.Split(v, " ") 18 | ans[w[0]] = w[1] 19 | } 20 | return ans 21 | } 22 | -------------------------------------------------------------------------------- /word_values/word_values_test.go: -------------------------------------------------------------------------------- 1 | package word_values 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestNameValue(t *testing.T) { 9 | 10 | //input := []string{"abc","abc","abc","abc"} 11 | //result := NameValue(input) 12 | //assert.Equal(t, result, []int{6,12,18,24}) 13 | 14 | input2 := []string{"abc", "abc abc"} 15 | 16 | result2 := NameValue(input2) 17 | 18 | assert.Equal(t, result2, []int{6, 24}) 19 | } 20 | -------------------------------------------------------------------------------- /words_to_marks/words_to_marks.go: -------------------------------------------------------------------------------- 1 | package words_to_marks 2 | 3 | //If a = 1, b = 2, c = 3 ... z = 26 4 | // 5 | //Then l + o + v + e = 54 6 | // 7 | //and f + r + i + e + n + d + s + h + i + p = 108 8 | // 9 | //So friendship is twice stronger than love :-) 10 | // 11 | //The input will always be in lowercase and never be empty. 12 | 13 | func WordsToMarks(s string) int { 14 | 15 | hash := map[rune]int{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26} 16 | 17 | count := 0 18 | for _, v := range s { 19 | count += hash[v] 20 | } 21 | return count 22 | } 23 | 24 | func WordsToMarks2(s string) int { 25 | count := 0 26 | for _, i := range s { 27 | count += int(i) - 'a' + 1 28 | } 29 | return count 30 | } 31 | 32 | func WordsToMarks3(s string) int { 33 | var result int 34 | for _, i := range s { 35 | result += int(i - 96) 36 | } 37 | return result 38 | } 39 | -------------------------------------------------------------------------------- /words_to_marks/words_to_marks_test.go: -------------------------------------------------------------------------------- 1 | package words_to_marks 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestWordsToMarks(t *testing.T) { 9 | 10 | assert.Equal(t, WordsToMarks("attitude"), 100) 11 | assert.Equal(t, WordsToMarks2("friends"), 75) 12 | assert.Equal(t, WordsToMarks3("family"), 66) 13 | } 14 | --------------------------------------------------------------------------------