|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +func main() { |
| 8 | + // Example slice for testing |
| 9 | + numbers := []int{3, 1, 4, 1, 5, 9, 2, 6} |
| 10 | + |
| 11 | + // Test FindMax |
| 12 | + max := FindMax(numbers) |
| 13 | + fmt.Printf("Maximum value: %d\n", max) |
| 14 | + |
| 15 | + // Test RemoveDuplicates |
| 16 | + unique := RemoveDuplicates(numbers) |
| 17 | + fmt.Printf("After removing duplicates: %v\n", unique) |
| 18 | + |
| 19 | + // Test ReverseSlice |
| 20 | + reversed := ReverseSlice(numbers) |
| 21 | + fmt.Printf("Reversed: %v\n", reversed) |
| 22 | + |
| 23 | + // Test FilterEven |
| 24 | + evenOnly := FilterEven(numbers) |
| 25 | + fmt.Printf("Even numbers only: %v\n", evenOnly) |
| 26 | +} |
| 27 | + |
| 28 | +// FindMax returns the maximum value in a slice of integers. |
| 29 | +// If the slice is empty, it returns 0. |
| 30 | +func FindMax(numbers []int) int { |
| 31 | + // TODO: Implement this function |
| 32 | + if len(numbers) == 0 { |
| 33 | + return 0 |
| 34 | + } |
| 35 | + |
| 36 | + max := numbers[0] |
| 37 | + |
| 38 | + for i := 1; i < len(numbers); i++ { |
| 39 | + if numbers[i] > max { |
| 40 | + max = numbers[i] |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return max |
| 45 | +} |
| 46 | + |
| 47 | +// RemoveDuplicates returns a new slice with duplicate values removed, |
| 48 | +// preserving the original order of elements. |
| 49 | +func RemoveDuplicates(numbers []int) []int { |
| 50 | + // TODO: Implement this function |
| 51 | + |
| 52 | + if len(numbers) == 0 { |
| 53 | + return []int{} |
| 54 | + } |
| 55 | + |
| 56 | + var res []int |
| 57 | + m := make(map[int]struct{}) |
| 58 | + |
| 59 | + for _, e := range numbers { |
| 60 | + _, exists := m[e] |
| 61 | + if !exists{ |
| 62 | + m[e] = struct{}{} |
| 63 | + res = append(res, e) |
| 64 | + } |
| 65 | + } |
| 66 | + return res |
| 67 | +} |
| 68 | + |
| 69 | +// ReverseSlice returns a new slice with elements in reverse order. |
| 70 | +func ReverseSlice(slice []int) []int { |
| 71 | + // TODO: Implement this function |
| 72 | + |
| 73 | + if len(slice) == 0 { |
| 74 | + return []int{} |
| 75 | + } |
| 76 | + |
| 77 | + var res []int |
| 78 | + |
| 79 | + for i := len(slice) -1; i >= 0; i--{ |
| 80 | + res = append(res, slice[i]) |
| 81 | + } |
| 82 | + return res |
| 83 | +} |
| 84 | + |
| 85 | +// FilterEven returns a new slice containing only the even numbers |
| 86 | +// from the original slice. |
| 87 | +func FilterEven(numbers []int) []int { |
| 88 | + // TODO: Implement this function |
| 89 | + if len(numbers) == 0 { |
| 90 | + return []int{} |
| 91 | + } |
| 92 | + |
| 93 | + var res []int |
| 94 | + for _, e := range numbers { |
| 95 | + if e % 2 == 0 { |
| 96 | + res = append(res, e) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + if len(res) == 0 { |
| 101 | + return []int{} |
| 102 | + } |
| 103 | + |
| 104 | + return res |
| 105 | +} |
0 commit comments