Skip to content

Commit b1df9d2

Browse files
Add solution for Challenge 19 by kiramux (#722)
* Add solution for Challenge 19 * update ReverseSlice() --------- Co-authored-by: go-interview-practice-bot[bot] <230190823+go-interview-practice-bot[bot]@users.noreply.github.com>
1 parent 1157c72 commit b1df9d2

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
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) == 0 {
33+
return 0
34+
}
35+
max := math.MinInt
36+
for _, v := range numbers {
37+
if v > max {
38+
max = v
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+
seen := make(map[int]struct{}, len(numbers))
48+
res := []int{}
49+
for _, v := range numbers {
50+
if _, ok := seen[v]; !ok {
51+
seen[v] = struct{}{}
52+
res = append(res, v)
53+
}
54+
}
55+
return res
56+
}
57+
58+
// ReverseSlice returns a new slice with elements in reverse order.
59+
func ReverseSlice(slice []int) []int {
60+
if len(slice) == 0 {
61+
return []int{}
62+
}
63+
result := make([]int, len(slice))
64+
for i, v := range slice {
65+
result[len(slice)-1-i] = v
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 _, v := range numbers {
75+
if v%2 == 0 {
76+
result = append(result, v)
77+
}
78+
}
79+
return result
80+
}

0 commit comments

Comments
 (0)