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