|
| 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 | + mx := numbers[0] |
| 36 | + for i:=1 ; i < len(numbers);i++{ |
| 37 | + if(numbers[i] > mx){ |
| 38 | + mx = numbers[i] |
| 39 | + } |
| 40 | + } |
| 41 | + return mx |
| 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 | + seen := make(map[int]bool) |
| 48 | + n := make([]int, 0, len(numbers)) |
| 49 | + |
| 50 | + for _, num := range numbers { |
| 51 | + if !seen[num] { |
| 52 | + seen[num] = true |
| 53 | + n = append(n, num) |
| 54 | + } |
| 55 | + } |
| 56 | + return n |
| 57 | + } |
| 58 | + |
| 59 | +// ReverseSlice returns a new slice with elements in reverse order. |
| 60 | +func ReverseSlice(slice []int) []int { |
| 61 | + n := make([]int, len(slice)) |
| 62 | + for i:=len(slice) - 1 ; i >= 0 ; i--{ |
| 63 | + // 2 1 0 |
| 64 | + // 0 1 2 |
| 65 | + n[len(slice) - i - 1] = slice[i] |
| 66 | + } |
| 67 | + return n |
| 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 | + n := make([]int , 0, len(numbers)) |
| 74 | + for i:=0 ; i < len(numbers);i++{ |
| 75 | + if(numbers[i] % 2 == 0){ |
| 76 | + n = append(n, numbers[i]) |
| 77 | + } |
| 78 | + } |
| 79 | + // TODO: Implement this function |
| 80 | + return n |
| 81 | +} |
0 commit comments