From c0d1d68722646378553c6f1d6ef937b6c6c33c58 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Tue, 5 Aug 2025 22:29:47 +0900 Subject: [PATCH 01/58] Add solution for Challenge 1 by t4e1 --- .../submissions/t4e1/solution-template.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 challenge-1/submissions/t4e1/solution-template.go diff --git a/challenge-1/submissions/t4e1/solution-template.go b/challenge-1/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..98e772d3 --- /dev/null +++ b/challenge-1/submissions/t4e1/solution-template.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" +) + +func main() { + var a, b int + // Read two integers from standard input + _, err := fmt.Scanf("%d, %d", &a, &b) + if err != nil { + fmt.Println("Error reading input:", err) + return + } + + // Call the Sum function and print the result + result := Sum(a, b) + fmt.Println(result) +} + +// Sum returns the sum of a and b. +func Sum(a int, b int) int { + // TODO: Implement the function + result := a + b + return result +} From 547250f63f9b2e4f69cd86e32113a5f32d109a9f Mon Sep 17 00:00:00 2001 From: t4e1 Date: Wed, 6 Aug 2025 23:28:25 +0900 Subject: [PATCH 02/58] Add solution for Challenge 2 by t4e1 --- .../submissions/t4e1/solution-template.go | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 challenge-2/submissions/t4e1/solution-template.go diff --git a/challenge-2/submissions/t4e1/solution-template.go b/challenge-2/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..df75faf3 --- /dev/null +++ b/challenge-2/submissions/t4e1/solution-template.go @@ -0,0 +1,34 @@ +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + // Read input from standard input + scanner := bufio.NewScanner(os.Stdin) + if scanner.Scan() { + input := scanner.Text() + + // Call the ReverseString function + output := ReverseString(input) + + // Print the result + fmt.Println(output) + } +} + +// ReverseString returns the reversed string of s. +func ReverseString(s string) string { + // TODO: Implement the function + runes := []rune(s) + + for i := 0; i < len(runes)/2; i++ { + x := len(runes) - (i+1) + runes[i], runes[x] = runes[x], runes[i] + } + + return string(runes) +} From c772c5f190473d16c2673af6b2f8e9b2adfe60ea Mon Sep 17 00:00:00 2001 From: t4e1 Date: Thu, 7 Aug 2025 18:48:24 +0900 Subject: [PATCH 03/58] Add solution for Challenge 3 by t4e1 --- .../submissions/t4e1/solution-template.go | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 challenge-3/submissions/t4e1/solution-template.go diff --git a/challenge-3/submissions/t4e1/solution-template.go b/challenge-3/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..78c2cdec --- /dev/null +++ b/challenge-3/submissions/t4e1/solution-template.go @@ -0,0 +1,69 @@ +package main + +import "fmt" + +type Employee struct { + ID int + Name string + Age int + Salary float64 +} + +type Manager struct { + Employees []Employee +} + +// AddEmployee adds a new employee to the manager's list. +func (m *Manager) AddEmployee(e Employee) { + // TODO: Implement this method + m.Employees = append(m.Employees, e) +} + +// RemoveEmployee removes an employee by ID from the manager's list. +func (m *Manager) RemoveEmployee(id int) { + // TODO: Implement this method + for i, v := range m.Employees { + if id == v.ID { + m.Employees = append(m.Employees[:i], m.Employees[i+1:]...) + break + } + } +} + +// GetAverageSalary calculates the average salary of all employees. +func (m *Manager) GetAverageSalary() float64 { + var total float64 + // TODO: Implement this method + if len(m.Employees) == 0 { + return 0.0 + } + for _, v := range m.Employees { + total += v.Salary + } + return total/float64(len(m.Employees)) +} + +// FindEmployeeByID finds and returns an employee by their ID. +func (m *Manager) FindEmployeeByID(id int) *Employee { + // TODO: Implement this method + for i := range m.Employees { + if m.Employees[i].ID == id { + return &m.Employees[i] + } + } + return nil +} + +func main() { + manager := Manager{} + manager.AddEmployee(Employee{ID: 1, Name: "Alice", Age: 30, Salary: 70000}) + manager.AddEmployee(Employee{ID: 2, Name: "Bob", Age: 25, Salary: 65000}) + manager.RemoveEmployee(1) + averageSalary := manager.GetAverageSalary() + employee := manager.FindEmployeeByID(2) + + fmt.Printf("Average Salary: %f\n", averageSalary) + if employee != nil { + fmt.Printf("Employee found: %+v\n", *employee) + } +} From 766eac170a9405ae3b11b6f59b431af3fa5ef2f6 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Fri, 8 Aug 2025 21:21:37 +0900 Subject: [PATCH 04/58] Add solution for Challenge 6 by t4e1 --- .../submissions/t4e1/solution-template.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 challenge-6/submissions/t4e1/solution-template.go diff --git a/challenge-6/submissions/t4e1/solution-template.go b/challenge-6/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..8d181f1b --- /dev/null +++ b/challenge-6/submissions/t4e1/solution-template.go @@ -0,0 +1,36 @@ +// Package challenge6 contains the solution for Challenge 6. +package challenge6 + +import ( + // Add any necessary imports here + "strings" + "regexp" +) + +// CountWordFrequency takes a string containing multiple words and returns +// a map where each key is a word and the value is the number of times that +// word appears in the string. The comparison is case-insensitive. +// +// Words are defined as sequences of letters and digits. +// All words are converted to lowercase before counting. +// All punctuation, spaces, and other non-alphanumeric characters are ignored. +// +// For example: +// Input: "The quick brown fox jumps over the lazy dog." +// Output: map[string]int{"the": 2, "quick": 1, "brown": 1, "fox": 1, "jumps": 1, "over": 1, "lazy": 1, "dog": 1} +func CountWordFrequency(text string) map[string]int { + // Your implementation here + text = strings.ToLower(text) + result := make(map[string]int) + temp := regexp.MustCompile(`[ \t\n\r.,!?;:"()\-]+`).Split(text, -1) + + for _, v := range temp { + if v == "" { + continue + } + v = strings.ReplaceAll(v, "'", "") + result[v] += 1 + } + + return result +} \ No newline at end of file From d9cc9c4cb758896fffad41731f20e6bf02275ff1 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Sat, 9 Aug 2025 20:34:00 +0900 Subject: [PATCH 05/58] Add solution for Challenge 18 by t4e1 --- .../submissions/t4e1/solution-template.go | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 challenge-18/submissions/t4e1/solution-template.go diff --git a/challenge-18/submissions/t4e1/solution-template.go b/challenge-18/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..699864aa --- /dev/null +++ b/challenge-18/submissions/t4e1/solution-template.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + // Example usage + celsius := 25.0 + fahrenheit := CelsiusToFahrenheit(celsius) + fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit) + + fahrenheit = 68.0 + celsius = FahrenheitToCelsius(fahrenheit) + fmt.Printf("%.2f°F is equal to %.2f°C\n", fahrenheit, celsius) +} + +// CelsiusToFahrenheit converts a temperature from Celsius to Fahrenheit +// Formula: F = C × 9/5 + 32 +func CelsiusToFahrenheit(celsius float64) float64 { + // TODO: Implement this function + // Remember to round to 2 decimal places + f := float64(celsius*9/5 + 32) + f = Round(f, 3) + + return f +} + +// FahrenheitToCelsius converts a temperature from Fahrenheit to Celsius +// Formula: C = (F - 32) × 5/9 +func FahrenheitToCelsius(fahrenheit float64) float64 { + // TODO: Implement this function + // Remember to round to 2 decimal places + c := (fahrenheit - 32) * 5 / 9 + c = Round(c, 3) + + return c +} + +// Round rounds a float64 value to the specified number of decimal places +func Round(value float64, decimals int) float64 { + precision := math.Pow10(decimals) + return math.Round(value*precision) / precision +} From dcf9e495f3fd2e30da2b478aa5c9b1d3fce39f73 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Mon, 11 Aug 2025 00:11:16 +0900 Subject: [PATCH 06/58] Add solution for Challenge 21 by t4e1 --- .../submissions/t4e1/solution-template.go | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 challenge-21/submissions/t4e1/solution-template.go diff --git a/challenge-21/submissions/t4e1/solution-template.go b/challenge-21/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..00747711 --- /dev/null +++ b/challenge-21/submissions/t4e1/solution-template.go @@ -0,0 +1,81 @@ +package main + +import ( + "fmt" +) + +func main() { + // Example sorted array for testing + arr := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} + + // Test binary search + target := 7 + index := BinarySearch(arr, target) + fmt.Printf("BinarySearch: %d found at index %d\n", target, index) + + // Test recursive binary search + recursiveIndex := BinarySearchRecursive(arr, target, 0, len(arr)-1) + fmt.Printf("BinarySearchRecursive: %d found at index %d\n", target, recursiveIndex) + + // Test find insert position + insertTarget := 8 + insertPos := FindInsertPosition(arr, insertTarget) + fmt.Printf("FindInsertPosition: %d should be inserted at index %d\n", insertTarget, insertPos) +} + +// BinarySearch performs a standard binary search to find the target in the sorted array. +// Returns the index of the target if found, or -1 if not found. +func BinarySearch(arr []int, target int) int { + // TODO: Implement this function + left, right := 0, len(arr)-1 + + for left <= right { + mid := left + (right - left)/2 + if arr[mid] == target { + return mid + } else if arr[mid] < target { + left = mid+1 + } else { + right = mid-1 + } + } + return -1 +} + +// BinarySearchRecursive performs binary search using recursion. +// Returns the index of the target if found, or -1 if not found. +func BinarySearchRecursive(arr []int, target int, left int, right int) int { + // TODO: Implement this function + mid := left + (right - left)/2 + + if left > right { + return -1 + } + + if arr[mid] == target { + return mid + } else if arr[mid] > target { + right = mid - 1 + return BinarySearchRecursive(arr, target, left, right) + } else { + left = mid + 1 + return BinarySearchRecursive(arr, target, left, right) + } + return -1 +} + +// FindInsertPosition returns the index where the target should be inserted +// to maintain the sorted order of the array. +func FindInsertPosition(arr []int, target int) int { + // TODO: Implement this function + left, right := 0, len(arr) + for left < right { + mid := (left + right)/2 + if arr[mid] < target { + left = mid+1 + } else { + right = mid + } + } + return left +} From 9f7ece712c4661bb31589c5d3ef686f44634379f Mon Sep 17 00:00:00 2001 From: t4e1 Date: Wed, 13 Aug 2025 23:13:32 +0900 Subject: [PATCH 07/58] Add solution for Challenge 22 by t4e1 --- .../submissions/t4e1/solution-template.go | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 challenge-22/submissions/t4e1/solution-template.go diff --git a/challenge-22/submissions/t4e1/solution-template.go b/challenge-22/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..b8646101 --- /dev/null +++ b/challenge-22/submissions/t4e1/solution-template.go @@ -0,0 +1,71 @@ +package main + +import ( + "fmt" +) + +func main() { + // Standard U.S. coin denominations in cents + denominations := []int{1, 5, 10, 25, 50} + + // Test amounts + amounts := []int{87, 42, 99, 33, 7} + + for _, amount := range amounts { + // Find minimum number of coins + minCoins := MinCoins(amount, denominations) + + // Find coin combination + coinCombo := CoinCombination(amount, denominations) + + // Print results + fmt.Printf("Amount: %d cents\n", amount) + fmt.Printf("Minimum coins needed: %d\n", minCoins) + fmt.Printf("Coin combination: %v\n", coinCombo) + fmt.Println("---------------------------") + } +} + +// MinCoins returns the minimum number of coins needed to make the given amount. +// If the amount cannot be made with the given denominations, return -1. +func MinCoins(amount int, denominations []int) int { + // TODO: Implement this function + + count := 0 + for i := range denominations { + lastNum := denominations[len(denominations)-i-1] + if amount >= lastNum { + num := amount / lastNum + amount = amount - (lastNum * num) + count += num + } + if amount == 0 { + return count + } + } + + return -1 +} + +// CoinCombination returns a map with the specific combination of coins that gives +// the minimum number. The keys are coin denominations and values are the number of +// coins used for each denomination. +// If the amount cannot be made with the given denominations, return an empty map. +func CoinCombination(amount int, denominations []int) map[int]int { + // TODO: Implement this function + + result := make(map[int]int) + for i := range denominations { + lastNum := denominations[len(denominations)-i-1] + if amount >= lastNum { + num := amount / lastNum + amount = amount - (lastNum * num) + result[lastNum] = num + } + if amount == 0 { + return result + } + } + + return map[int]int{} +} From c062ea11a6099e296e05b7b232c2e2548506e89c Mon Sep 17 00:00:00 2001 From: t4e1 Date: Fri, 15 Aug 2025 00:52:58 +0900 Subject: [PATCH 08/58] Add solution for Challenge 4 by t4e1 --- .../submissions/t4e1/solution-template.go | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 challenge-4/submissions/t4e1/solution-template.go diff --git a/challenge-4/submissions/t4e1/solution-template.go b/challenge-4/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..9085a356 --- /dev/null +++ b/challenge-4/submissions/t4e1/solution-template.go @@ -0,0 +1,80 @@ +package main + +// ConcurrentBFSQueries concurrently processes BFS queries on the provided graph. +// - graph: adjacency list, e.g., graph[u] = []int{v1, v2, ...} +// - queries: a list of starting nodes for BFS. +// - numWorkers: how many goroutines can process BFS queries simultaneously. +// +// Return a map from the query (starting node) to the BFS order as a slice of nodes. +// YOU MUST use concurrency (goroutines + channels) to pass the performance tests. +type BFSResult struct { + StartNode int + Order []int +} + +func ConcurrentBFSQueries(graph map[int][]int, queries []int, numWorkers int) map[int][]int { + // TODO: Implement concurrency-based BFS for multiple queries. + // Return an empty map so the code compiles but fails tests if unchanged. + if numWorkers <= 0 { + return map[int][]int{} + } + + jobs := make(chan int, len(queries)) + results := make(chan BFSResult, len(queries)) + + for i := 0; i < numWorkers; i++ { + go worker(graph, jobs, results) + } + + for _, query := range queries { + jobs <- query + } + close(jobs) + + resultMap := make(map[int][]int) + + for i := 0; i < len(queries); i++ { + result := <-results + resultMap[result.StartNode] = result.Order + } + + return resultMap +} + +func worker(graph map[int][]int, jobs <-chan int, results chan<- BFSResult) { + for start := range jobs { + order := bfs(graph, start) + results <- BFSResult{StartNode: start, Order: order} + } +} + +func bfs(graph map[int][]int, start int) []int { + visited := make(map[int]bool) + queue := []int{start} + order := []int{} + + for len(queue) > 0 { + + node := queue[0] + queue = queue[1:] + + if visited[node] { + continue + } + + visited[node] = true + order = append(order, node) + + for _, neighbor := range graph[node] { + if !visited[neighbor] { + queue = append(queue, neighbor) + } + } + } + + return order +} + +func main() { + // You can insert optional local tests here if desired. +} From 2fb4b310976dbfd04e71b02c72628a6d255b13b6 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Sat, 16 Aug 2025 23:18:47 +0900 Subject: [PATCH 09/58] Add solution for Challenge 10 by t4e1 --- .../submissions/t4e1/solution-template.go | 243 ++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 challenge-10/submissions/t4e1/solution-template.go diff --git a/challenge-10/submissions/t4e1/solution-template.go b/challenge-10/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..0882b364 --- /dev/null +++ b/challenge-10/submissions/t4e1/solution-template.go @@ -0,0 +1,243 @@ +// Package challenge10 contains the solution for Challenge 10. +package challenge10 + +import ( + "fmt" + "cmp" + "errors" + "math" + "slices" + // Add any necessary imports here +) + +// Shape interface defines methods that all shapes must implement +type Shape interface { + Area() float64 + Perimeter() float64 + fmt.Stringer // Includes String() string method +} + +// Rectangle represents a four-sided shape with perpendicular sides +type Rectangle struct { + Width float64 + Height float64 +} + +// NewRectangle creates a new Rectangle with validation +func NewRectangle(width, height float64) (*Rectangle, error) { + // TODO: Implement validation and construction + switch { + case width <= 0: + return nil, errors.New("width must be > 0") + case height <= 0: + return nil, errors.New("height must be > 0") + } + + return &Rectangle{ + Width: width, + Height: height}, nil +} + +// Area calculates the area of the rectangle +func (r *Rectangle) Area() float64 { + // TODO: Implement area calculation + return r.Height * r.Width +} + +// Perimeter calculates the perimeter of the rectangle +func (r *Rectangle) Perimeter() float64 { + // TODO: Implement perimeter calculation + return (r.Height + r.Width) * 2 +} + +// String returns a string representation of the rectangle +func (r *Rectangle) String() string { + // TODO: Implement string representation + return fmt.Sprintf("A rectangle consisting of %f widths and %f heights.", r.Width, r.Height) +} + +// Circle represents a perfectly round shape +type Circle struct { + Radius float64 +} + +// NewCircle creates a new Circle with validation +func NewCircle(radius float64) (*Circle, error) { + // TODO: Implement validation and construction + if radius <= 0 { + return nil, errors.New("radius must be > 0") + } + return &Circle{ + Radius: radius, + }, nil +} + +// Area calculates the area of the circle +func (c *Circle) Area() float64 { + // TODO: Implement area calculation + return c.Radius * c.Radius * math.Pi +} + +// Perimeter calculates the circumference of the circle +func (c *Circle) Perimeter() float64 { + // TODO: Implement perimeter calculation + return c.Radius * 2 * math.Pi +} + +// String returns a string representation of the circle +func (c *Circle) String() string { + // TODO: Implement string representation + return fmt.Sprintf("A circle consisting of %f radius", c.Radius) +} + +// Triangle represents a three-sided polygon +type Triangle struct { + SideA float64 + SideB float64 + SideC float64 +} + +// NewTriangle creates a new Triangle with validation +func NewTriangle(a, b, c float64) (*Triangle, error) { + // TODO: Implement validation and construction + if a <= 0 || b <= 0 || c <= 0 { + return nil, errors.New("side must be > 0") + } + + if a+b <= c || a+c <= b || b+c <= a { + return nil, errors.New("invalid triangle side") + } + + return &Triangle{ + SideA: a, + SideB: b, + SideC: c, + }, nil +} + +// Area calculates the area of the triangle using Heron's formula +func (t *Triangle) Area() float64 { + // TODO: Implement area calculation using Heron's formula + s := (t.SideA + t.SideB + t.SideC) / 2 + return math.Sqrt(s * (s - t.SideA) * (s - t.SideB) * (s - t.SideC)) +} + +// Perimeter calculates the perimeter of the triangle +func (t *Triangle) Perimeter() float64 { + // TODO: Implement perimeter calculation + return t.SideA + t.SideB + t.SideC +} + +// String returns a string representation of the triangle +func (t *Triangle) String() string { + // TODO: Implement string representation + return fmt.Sprintf("A triangle consisting of three sides: %f, %f, %f", t.SideA, t.SideB, t.SideC) +} + +// ShapeCalculator provides utility functions for shapes +type ShapeCalculator struct{} + +// NewShapeCalculator creates a new ShapeCalculator +func NewShapeCalculator() *ShapeCalculator { + // TODO: Implement constructor + return &ShapeCalculator{} +} + +// PrintProperties prints the properties of a shape +func (sc *ShapeCalculator) PrintProperties(s Shape) { + // TODO: Implement printing shape properties + fmt.Println(s.String()) +} + +// TotalArea calculates the sum of areas of all shapes +func (sc *ShapeCalculator) TotalArea(shapes []Shape) float64 { + // TODO: Implement total area calculation + sum := 0.0 + ch := make(chan float64, len(shapes)) + + for _, s := range shapes { + go func(sh Shape) { + ch <- sh.Area() + }(s) + } + + for i := 0; i < len(shapes); i++ { + sum += <-ch + } + + return sum +} + +// LargestShape finds the shape with the largest area +func (sc *ShapeCalculator) LargestShape(shapes []Shape) Shape { + // TODO: Implement finding largest shape + + type result struct { + shape Shape + area float64 + } + + ch := make(chan result, len(shapes)) + sl := []result{} + + for _, s := range shapes { + go func(sh Shape) { + r := result{ + shape: sh, + area: sh.Area(), + } + ch <- r + }(s) + } + + for i := 0; i < len(shapes); i++ { + sl = append(sl, <-ch) + } + + slices.SortFunc(sl, func(a, b result) int { + return cmp.Compare(a.area, b.area) + }) + + return sl[len(sl)-1].shape +} + +// SortByArea sorts shapes by area in ascending or descending order +func (sc *ShapeCalculator) SortByArea(shapes []Shape, ascending bool) []Shape { + // TODO: Implement sorting shapes by area + type result struct { + shape Shape + area float64 + } + + ch := make(chan result, len(shapes)) + sl := []result{} + rv := []Shape{} + + for _, s := range shapes { + go func(sh Shape) { + r := result{ + shape: sh, + area: sh.Area(), + } + ch <- r + }(s) + } + + for i := 0; i < len(shapes); i++ { + sl = append(sl, <-ch) + } + + slices.SortFunc(sl, func(a, b result) int { + return cmp.Compare(a.area, b.area) + }) + + for _, s := range sl { + rv = append(rv, s.shape) + } + + if !ascending { + slices.Reverse(rv) + } + + return rv +} \ No newline at end of file From c3e3451c049d171efc8ce9b19a21d2d976ba8afb Mon Sep 17 00:00:00 2001 From: t4e1 Date: Sun, 17 Aug 2025 23:23:21 +0900 Subject: [PATCH 10/58] Add solution for Challenge 5 by t4e1 --- .../submissions/t4e1/solution-template.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 challenge-5/submissions/t4e1/solution-template.go diff --git a/challenge-5/submissions/t4e1/solution-template.go b/challenge-5/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..86f83adf --- /dev/null +++ b/challenge-5/submissions/t4e1/solution-template.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "net/http" +) + +const validToken = "secret" + +// AuthMiddleware checks the "X-Auth-Token" header. +// If it's "secret", call the next handler. +// Otherwise, respond with 401 Unauthorized. +func AuthMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // TODO: Implement the logic: + // 1) Grab the "X-Auth-Token" header + // 2) Compare against validToken + // 3) If mismatch or missing, respond with 401 + // 4) Otherwise pass to next handler + if r.Header.Get("X-Auth-Token") != validToken { + http.Error(w, "", 401) + return + } + + next.ServeHTTP(w, r) + }) +} + +// helloHandler returns "Hello!" on GET /hello +func helloHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello!") +} + +// secureHandler returns "You are authorized!" on GET /secure +func secureHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "You are authorized!") +} + +// SetupServer configures the HTTP routes with the authentication middleware. +func SetupServer() http.Handler { + mux := http.NewServeMux() + + // Public route: /hello (no auth required) + mux.HandleFunc("/hello", helloHandler) + + // Secure route: /secure + // Wrap with AuthMiddleware + secureRoute := http.HandlerFunc(secureHandler) + mux.Handle("/secure", AuthMiddleware(secureRoute)) + + return mux +} + +func main() { + // Optional: you can run a real server for local testing + // http.ListenAndServe(":10001", SetupServer()) +} From 1f9d49d7682069e141a4b56d0b9c7cbdec7a8fc0 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Mon, 18 Aug 2025 23:36:45 +0900 Subject: [PATCH 11/58] Add solution for Challenge 7 by t4e1 --- .../submissions/t4e1/solution-template.go | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 challenge-7/submissions/t4e1/solution-template.go diff --git a/challenge-7/submissions/t4e1/solution-template.go b/challenge-7/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..5d37d6bf --- /dev/null +++ b/challenge-7/submissions/t4e1/solution-template.go @@ -0,0 +1,168 @@ +// Package challenge7 contains the solution for Challenge 7: Bank Account with Error Handling. +package challenge7 + +import ( + "fmt" + "sync" + // Add any other necessary imports +) + +// BankAccount represents a bank account with balance management and minimum balance requirements. +type BankAccount struct { + ID string + Owner string + Balance float64 + MinBalance float64 + mu sync.Mutex // For thread safety +} + +// Constants for account operations +const ( + MaxTransactionAmount = 10000.0 // Example limit for deposits/withdrawals +) + +// Custom error types + +// AccountError is a general error type for bank account operations. +type AccountError struct { + // Implement this error type + Id string + Owner string +} + +func (e *AccountError) Error() string { + // Implement error message + return "Account error: " + e.Id + " owned by " + e.Owner +} + +// InsufficientFundsError occurs when a withdrawal or transfer would bring the balance below minimum. +type InsufficientFundsError struct { + // Implement this error type + MinBalance float64 +} + +func (e *InsufficientFundsError) Error() string { + // Implement error message + return "Insufficient funds: minimum balance required is " + fmt.Sprintf("%.2f", e.MinBalance) +} + +// NegativeAmountError occurs when an amount for deposit, withdrawal, or transfer is negative. +type NegativeAmountError struct { + // Implement this error type + Amount float64 +} + +func (e *NegativeAmountError) Error() string { + // Implement error message + return "Negative amount error: " + fmt.Sprintf("amount cannot be negative: %.2f", e.Amount) +} + +// ExceedsLimitError occurs when a deposit or withdrawal amount exceeds the defined limit. +type ExceedsLimitError struct { + // Implement this error type + Amount float64 +} + +func (e *ExceedsLimitError) Error() string { + // Implement error message + return "Exceeds limit error: " + fmt.Sprintf("amount exceeds limit: %.2f", e.Amount) +} + +// NewBankAccount creates a new bank account with the given parameters. +// It returns an error if any of the parameters are invalid. +func NewBankAccount(id, owner string, initialBalance, minBalance float64) (*BankAccount, error) { + // Implement account creation with validation + if id == "" || owner == "" { + return nil, &AccountError{ + Id: id, + Owner: owner, + } + } + + if minBalance < 0 || initialBalance < 0 { + return nil, &NegativeAmountError{ + Amount: minBalance, + } + } + + if initialBalance < minBalance { + return nil, &InsufficientFundsError{ + MinBalance: minBalance, + } + } + + return &BankAccount{ + ID: id, + Owner: owner, + Balance: initialBalance, + MinBalance: minBalance, + }, nil +} + +// Deposit adds the specified amount to the account balance. +// It returns an error if the amount is invalid or exceeds the transaction limit. +func (a *BankAccount) Deposit(amount float64) error { + // Implement deposit functionality with proper error handling + a.mu.Lock() + defer a.mu.Unlock() + + if amount < 0 { + return &NegativeAmountError{Amount: amount} + } + if amount > MaxTransactionAmount { + return &ExceedsLimitError{Amount: amount} + } + + a.Balance += amount + + return nil +} + +// Withdraw removes the specified amount from the account balance. +// It returns an error if the amount is invalid, exceeds the transaction limit, +// or would bring the balance below the minimum required balance. +func (a *BankAccount) Withdraw(amount float64) error { + // Implement withdrawal functionality with proper error handling + a.mu.Lock() + defer a.mu.Unlock() + + if amount < 0 { + return &NegativeAmountError{Amount: amount} + } + if amount > MaxTransactionAmount { + return &ExceedsLimitError{Amount: amount} + } + if a.Balance-amount < a.MinBalance { + return &InsufficientFundsError{MinBalance: a.MinBalance} + } + + a.Balance -= amount + + return nil +} + +// Transfer moves the specified amount from this account to the target account. +// It returns an error if the amount is invalid, exceeds the transaction limit, +// or would bring the balance below the minimum required balance. +func (a *BankAccount) Transfer(amount float64, target *BankAccount) error { + // Implement transfer functionality with proper error handling + a.mu.Lock() + target.mu.Lock() + defer target.mu.Unlock() + defer a.mu.Unlock() + + if amount < 0 { + return &NegativeAmountError{Amount: amount} + } + if amount > MaxTransactionAmount { + return &ExceedsLimitError{Amount: amount} + } + if a.Balance-amount < a.MinBalance { + return &InsufficientFundsError{MinBalance: a.MinBalance} + } + + a.Balance -= amount + target.Balance += amount + + return nil +} \ No newline at end of file From 61f72286aac27b908bb3fc6e58f270d090abe881 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Wed, 20 Aug 2025 23:51:11 +0900 Subject: [PATCH 12/58] Add solution for Challenge 13 by t4e1 --- .../submissions/t4e1/solution-template.go | 205 ++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 challenge-13/submissions/t4e1/solution-template.go diff --git a/challenge-13/submissions/t4e1/solution-template.go b/challenge-13/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..9ef373f2 --- /dev/null +++ b/challenge-13/submissions/t4e1/solution-template.go @@ -0,0 +1,205 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "modernc.org/sqlite" +) + +// Product represents a product in the inventory system +type Product struct { + ID int64 + Name string + Price float64 + Quantity int + Category string +} + +// ProductStore manages product operations +type ProductStore struct { + db *sql.DB +} + +// NewProductStore creates a new ProductStore with the given database connection +func NewProductStore(db *sql.DB) *ProductStore { + return &ProductStore{db: db} +} + +// InitDB sets up a new SQLite database and creates the products table +func InitDB(dbPath string) (*sql.DB, error) { + // TODO: Open a SQLite database connection + // TODO: Create the products table if it doesn't exist + // The table should have columns: id, name, price, quantity, category + db, err := sql.Open("sqlite", dbPath) + if err != nil { + return nil, err + } + + // Test the connection + if err = db.Ping(); err != nil { + return nil, err + } + + _, err = db.Exec("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL, quantity INTEGER, category TEXT)") + if err != nil { + return nil, err + } + + return db, nil +} + +// CreateProduct adds a new product to the database +func (ps *ProductStore) CreateProduct(product *Product) error { + // TODO: Insert the product into the database + // TODO: Update the product.ID with the database-generated ID + result, err := ps.db.Exec("INSERT INTO products (name, price, quantity, category) VALUES (?, ?, ?, ?)", + product.Name, product.Price, product.Quantity, product.Category) + if err != nil { + return err + } + + id, err := result.LastInsertId() + if err != nil { + return err + } + product.ID = id + + return nil +} + +// GetProduct retrieves a product by ID +func (ps *ProductStore) GetProduct(id int64) (*Product, error) { + // TODO: Query the database for a product with the given ID + // TODO: Return a Product struct populated with the data or an error if not found + row := ps.db.QueryRow("SELECT id, name, price, quantity, category FROM products WHERE id = ?", id) + + p := &Product{} + err := row.Scan(&p.ID, &p.Name, &p.Price, &p.Quantity, &p.Category) + if err != nil { + if err == sql.ErrNoRows { + return nil, fmt.Errorf("product with ID %d not found", id) + } + return nil, err + } + + return p, nil +} + +// UpdateProduct updates an existing product +func (ps *ProductStore) UpdateProduct(product *Product) error { + // TODO: Update the product in the database + // TODO: Return an error if the product doesn't exist + result, err := ps.db.Exec("Update products SET name = ? , price = ?, quantity = ?, category = ? WHERE id = ?", + product.Name, product.Price, product.Quantity, product.Category, product.ID) + + row, err := result.RowsAffected() + if err != nil { + if row == 0 { + return fmt.Errorf("product with ID %d not found", product.ID) + } + return err + } + + return nil +} + +// DeleteProduct removes a product by ID +func (ps *ProductStore) DeleteProduct(id int64) error { + // TODO: Delete the product from the database + // TODO: Return an error if the product doesn't exist + result, err := ps.db.Exec("DELETE FROM products WHERE id = ?", id) + + row, err := result.RowsAffected() + if err != nil { + if row == 0 { + return fmt.Errorf("product with ID %d not found", id) + } + return err + } + + result.RowsAffected() + + return nil +} + +// ListProducts returns all products with optional filtering by category +func (ps *ProductStore) ListProducts(category string) ([]*Product, error) { + // TODO: Query the database for products + // TODO: If category is not empty, filter by category + // TODO: Return a slice of Product pointers + result := []*Product{} + + var rows *sql.Rows + var err error + + if category == "" { + rows, err = ps.db.Query("SELECT id, name, price, quantity, category FROM products") + } else { + rows, err = ps.db.Query("SELECT id, name, price, quantity, category FROM products WHERE category = ?", category) + } + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + p := &Product{} + err := rows.Scan(&p.ID, &p.Name, &p.Price, &p.Quantity, &p.Category) + if err != nil { + return nil, err + } + result = append(result, p) + } + + if err = rows.Err(); err != nil { + return nil, err + } + + return result, nil +} + +// BatchUpdateInventory updates the quantity of multiple products in a single transaction +func (ps *ProductStore) BatchUpdateInventory(updates map[int64]int) error { + // TODO: Start a transaction + // TODO: For each product ID in the updates map, update its quantity + // TODO: If any update fails, roll back the transaction + // TODO: Otherwise, commit the transaction + tx, err := ps.db.Begin() + if err != nil { + return err + } + defer func() { + if err != nil { + tx.Rollback() + } + }() + + stmt, err := tx.Prepare("UPDATE products SET quantity = ? WHERE id = ?") + if err != nil { + return err + } + defer stmt.Close() + + for id, quantity := range updates { + result, err := stmt.Exec(quantity, id) + if err != nil { + return err + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return err + } + + if rowsAffected == 0 { + return fmt.Errorf("product with ID %d not found", id) + } + } + + return tx.Commit() +} + +func main() { + // Optional: you can write code here to test your implementation +} From af3f0144e42d53596d82f835b33c1fbb385b1188 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Thu, 21 Aug 2025 23:33:49 +0900 Subject: [PATCH 13/58] Add solution for Challenge 17 by t4e1 --- .../submissions/t4e1/solution-template.go | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 challenge-17/submissions/t4e1/solution-template.go diff --git a/challenge-17/submissions/t4e1/solution-template.go b/challenge-17/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..581370fc --- /dev/null +++ b/challenge-17/submissions/t4e1/solution-template.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +func main() { + // Get input from the user + var input string + fmt.Print("Enter a string to check if it's a palindrome: ") + fmt.Scanln(&input) + + // Call the IsPalindrome function and print the result + result := IsPalindrome(input) + if result { + fmt.Println("The string is a palindrome.") + } else { + fmt.Println("The string is not a palindrome.") + } +} + +// IsPalindrome checks if a string is a palindrome. +// A palindrome reads the same backward as forward, ignoring case, spaces, and punctuation. +func IsPalindrome(s string) bool { + // TODO: Implement this function + // 1. Clean the string (remove spaces, punctuation, and convert to lowercase) + // 2. Check if the cleaned string is the same forwards and backwards + var result strings.Builder + for _, r := range s { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + result.WriteRune(unicode.ToLower(r)) + } + } + s = result.String() + + rs := []rune(s) + for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 { + rs[i], rs[j] = rs[j], rs[i] + } + + if s == string(rs) { + return true + } + return false +} From 9edeeed8eb93bf3473a18f1b364240450d8f1eb9 Mon Sep 17 00:00:00 2001 From: t4e1 Date: Tue, 26 Aug 2025 00:17:34 +0900 Subject: [PATCH 14/58] Add solution for Challenge 19 by t4e1 --- .../submissions/t4e1/solution-template.go | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 challenge-19/submissions/t4e1/solution-template.go diff --git a/challenge-19/submissions/t4e1/solution-template.go b/challenge-19/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..32eff0ea --- /dev/null +++ b/challenge-19/submissions/t4e1/solution-template.go @@ -0,0 +1,98 @@ +package main + +import ( + "fmt" +) + +func main() { + // Example slice for testing + numbers := []int{3, 1, 4, 1, 5, 9, 2, 6} + + // Test FindMax + max := FindMax(numbers) + fmt.Printf("Maximum value: %d\n", max) + + // Test RemoveDuplicates + unique := RemoveDuplicates(numbers) + fmt.Printf("After removing duplicates: %v\n", unique) + + // Test ReverseSlice + reversed := ReverseSlice(numbers) + fmt.Printf("Reversed: %v\n", reversed) + + // Test FilterEven + evenOnly := FilterEven(numbers) + fmt.Printf("Even numbers only: %v\n", evenOnly) +} + +// FindMax returns the maximum value in a slice of integers. +// If the slice is empty, it returns 0. +func FindMax(numbers []int) int { + // TODO: Implement this function + if len(numbers) == 0 { + return 0 + } + + result := numbers[0] + + for _, num := range numbers { + if num > result { + result = num + } + } + return result +} + +// RemoveDuplicates returns a new slice with duplicate values removed, +// preserving the original order of elements. +func RemoveDuplicates(numbers []int) []int { + // TODO: Implement this function + if len(numbers) == 0 { + return []int{} + } + + chekcedNum := make(map[int]bool) + var result []int + for _, num := range numbers { + if !chekcedNum[num] { + result = append(result, num) + chekcedNum[num] = true + } + } + + return result +} + +// ReverseSlice returns a new slice with elements in reverse order. +func ReverseSlice(slice []int) []int { + // TODO: Implement this function + if len(slice) == 0 { + return []int{} + } + + var result []int + for i := len(slice) - 1; i >= 0; i-- { + result = append(result, slice[i]) + } + + return result +} + +// FilterEven returns a new slice containing only the even numbers +// from the original slice. +func FilterEven(numbers []int) []int { + // TODO: Implement this function + var result []int + + for _, num := range numbers { + if num % 2 == 0 { + result = append(result, num) + } + } + + if len(result) == 0 || len(numbers) == 0 { + return []int{} + } + + return result +} From 2bc177fe9bd72fa472c39ab0c4ce3a7e575b290d Mon Sep 17 00:00:00 2001 From: t4e1 Date: Sun, 31 Aug 2025 23:51:43 +0900 Subject: [PATCH 15/58] Add solution for Challenge 27 by t4e1 --- .../submissions/t4e1/solution-template.go | 320 ++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 challenge-27/submissions/t4e1/solution-template.go diff --git a/challenge-27/submissions/t4e1/solution-template.go b/challenge-27/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..795a78bd --- /dev/null +++ b/challenge-27/submissions/t4e1/solution-template.go @@ -0,0 +1,320 @@ +package generics + +import "errors" + +// ErrEmptyCollection is returned when an operation cannot be performed on an empty collection +var ErrEmptyCollection = errors.New("collection is empty") + +// +// 1. Generic Pair +// + +// Pair represents a generic pair of values of potentially different types +type Pair[T, U any] struct { + First T + Second U +} + +// NewPair creates a new pair with the given values +func NewPair[T, U any](first T, second U) Pair[T, U] { + // TODO: Implement this function + return Pair[T, U]{First: first, Second: second} +} + +// Swap returns a new pair with the elements swapped +func (p Pair[T, U]) Swap() Pair[U, T] { + // TODO: Implement this method + return Pair[U, T]{First: p.Second, Second: p.First} +} + +// +// 2. Generic Stack +// + +// Stack is a generic Last-In-First-Out (LIFO) data structure +type Stack[T any] struct { + // TODO: Add necessary fields + elements []T +} + +// NewStack creates a new empty stack +func NewStack[T any]() *Stack[T] { + // TODO: Implement this function + return &Stack[T]{elements: []T{}} +} + +// Push adds an element to the top of the stack +func (s *Stack[T]) Push(value T) { + // TODO: Implement this method + s.elements = append(s.elements, value) +} + +// Pop removes and returns the top element from the stack +// Returns an error if the stack is empty +func (s *Stack[T]) Pop() (T, error) { + // TODO: Implement this method + var zero T + if len(s.elements) == 0 { + return zero, ErrEmptyCollection + } + zero = s.elements[len(s.elements)-1] + s.elements = s.elements[:len(s.elements)-1] + + return zero, nil +} + +// Peek returns the top element without removing it +// Returns an error if the stack is empty +func (s *Stack[T]) Peek() (T, error) { + // TODO: Implement this method + var zero T + if len(s.elements) == 0 { + return zero, ErrEmptyCollection + } + zero = s.elements[len(s.elements)-1] + + return zero, nil +} + +// Size returns the number of elements in the stack +func (s *Stack[T]) Size() int { + // TODO: Implement this method + return len(s.elements) +} + +// IsEmpty returns true if the stack contains no elements +func (s *Stack[T]) IsEmpty() bool { + // TODO: Implement this method + if len(s.elements) != 0 { + return false + } + return true +} + +// +// 3. Generic Queue +// + +// Queue is a generic First-In-First-Out (FIFO) data structure +type Queue[T any] struct { + // TODO: Add necessary fields + elements []T +} + +// NewQueue creates a new empty queue +func NewQueue[T any]() *Queue[T] { + // TODO: Implement this function + return &Queue[T]{elements: []T{}} +} + +// Enqueue adds an element to the end of the queue +func (q *Queue[T]) Enqueue(value T) { + // TODO: Implement this method + q.elements = append(q.elements, value) +} + +// Dequeue removes and returns the front element from the queue +// Returns an error if the queue is empty +func (q *Queue[T]) Dequeue() (T, error) { + // TODO: Implement this method + var zero T + if len(q.elements) == 0 { + return zero, ErrEmptyCollection + } + zero = q.elements[0] + q.elements = q.elements[1:] + + return zero, nil +} + +// Front returns the front element without removing it +// Returns an error if the queue is empty +func (q *Queue[T]) Front() (T, error) { + // TODO: Implement this method + var zero T + if len(q.elements) == 0 { + return zero, ErrEmptyCollection + } + zero = q.elements[0] + + return zero, nil +} + +// Size returns the number of elements in the queue +func (q *Queue[T]) Size() int { + // TODO: Implement this method + return len(q.elements) +} + +// IsEmpty returns true if the queue contains no elements +func (q *Queue[T]) IsEmpty() bool { + // TODO: Implement this method + if len(q.elements) != 0 { + return false + } + return true +} + +// +// 4. Generic Set +// + +// Set is a generic collection of unique elements +type Set[T comparable] struct { + // TODO: Add necessary fields + elements map[T]struct{} +} + +// NewSet creates a new empty set +func NewSet[T comparable]() *Set[T] { + // TODO: Implement this function + return &Set[T]{elements: make(map[T]struct{})} +} + +// Add adds an element to the set if it's not already present +func (s *Set[T]) Add(value T) { + // TODO: Implement this method + s.elements[value] = struct{}{} +} + +// Remove removes an element from the set if it exists +func (s *Set[T]) Remove(value T) { + // TODO: Implement this method + if _, exists := s.elements[value]; exists { + delete(s.elements, value) + } +} + +// Contains returns true if the set contains the given element +func (s *Set[T]) Contains(value T) bool { + // TODO: Implement this method + if _, exists := s.elements[value]; exists { + return true + } + + return false +} + +// Size returns the number of elements in the set +func (s *Set[T]) Size() int { + // TODO: Implement this method + return len(s.elements) +} + +// Elements returns a slice containing all elements in the set +func (s *Set[T]) Elements() []T { + // TODO: Implement this method + sv := make([]T, 0, len(s.elements)) + for k, _ := range s.elements { + sv = append(sv, k) + } + + return sv +} + +// Union returns a new set containing all elements from both sets +func Union[T comparable](s1, s2 *Set[T]) *Set[T] { + // TODO: Implement this function + us := make(map[T]struct{}) + for k, _ := range s1.elements { + us[k] = struct{}{} + } + + for k, _ := range s2.elements { + us[k] = struct{}{} + } + + return &Set[T]{elements: us} +} + +// Intersection returns a new set containing only elements that exist in both sets +func Intersection[T comparable](s1, s2 *Set[T]) *Set[T] { + interSet := make(map[T]struct{}) + for k1 := range s1.elements { + if _, exists := s2.elements[k1]; exists { + interSet[k1] = struct{}{} + } + } + return &Set[T]{elements: interSet} +} + +// Difference returns a new set with elements in s1 that are not in s2 +func Difference[T comparable](s1, s2 *Set[T]) *Set[T] { + diff := make(map[T]struct{}) + for k := range s1.elements { + if _, exists := s2.elements[k]; !exists { + diff[k] = struct{}{} + } + } + return &Set[T]{elements: diff} +} + +// +// 5. Generic Utility Functions +// + + // Filter returns a new slice containing only the elements for which the predicate returns true + func Filter[T any](slice []T, predicate func(T) bool) []T { + // TODO: Implement this function + result := make([]T, 0, len(slice)) + for _, v := range slice { + if predicate(v) { + result = append(result, v) + } + } + + return result + } + + // Map applies a function to each element in a slice and returns a new slice with the results + func Map[T, U any](slice []T, mapper func(T) U) []U { + // TODO: Implement this function + result := make([]U, 0, len(slice)) + for _, v := range slice { + result = append(result, mapper(v)) + } + + return result + } + + // Reduce reduces a slice to a single value by applying a function to each element + func Reduce[T, U any](slice []T, initial U, reducer func(U, T) U) U { + acc := initial + for _, v := range slice { + acc = reducer(acc, v) + } + return acc + } + + // Contains returns true if the slice contains the given element + func Contains[T comparable](slice []T, element T) bool { + for _, v := range slice { + if v == element { + return true + } + } + return false + } + + // FindIndex returns the index of the first occurrence of the given element or -1 if not found + func FindIndex[T comparable](slice []T, element T) int { + for i, v := range slice { + if v == element { + return i + } + } + return -1 + } + + // RemoveDuplicates returns a new slice with duplicate elements removed, preserving order + func RemoveDuplicates[T comparable](slice []T) []T { + seen := make(map[T]struct{}) + result := make([]T, 0, len(slice)) + for _, v := range slice { + if _, exists := seen[v]; !exists { + seen[v] = struct{}{} + result = append(result, v) + } + } + return result + } From 99d07a0226191dcb891db48355b797b54f9be569 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 21:57:10 +0000 Subject: [PATCH 16/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-5=20challenge-6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-5/SCOREBOARD.md | 1 + challenge-6/SCOREBOARD.md | 1 + 2 files changed, 2 insertions(+) diff --git a/challenge-5/SCOREBOARD.md b/challenge-5/SCOREBOARD.md index f1d0cab1..486f4fdf 100644 --- a/challenge-5/SCOREBOARD.md +++ b/challenge-5/SCOREBOARD.md @@ -2,6 +2,7 @@ | Username | Passed Tests | Total Tests | |------------|--------------|-------------| | AkifhanIlgaz | 9 | 9 | +| Ashutosh652 | 9 | 9 | | JackDalberg | 9 | 9 | | MYK12397 | 9 | 9 | | PolinaSvet | 9 | 9 | diff --git a/challenge-6/SCOREBOARD.md b/challenge-6/SCOREBOARD.md index 1d833c86..d4e2a9b5 100644 --- a/challenge-6/SCOREBOARD.md +++ b/challenge-6/SCOREBOARD.md @@ -2,6 +2,7 @@ | Username | Passed Tests | Total Tests | |------------|--------------|-------------| | AkifhanIlgaz | 7 | 7 | +| Ashutosh652 | 7 | 7 | | Cpoing | 7 | 7 | | Gandook | 7 | 7 | | GinVlad | 7 | 7 | From b454177f768b86f56f86c55257e7bddba5514fdd Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 21:57:40 +0000 Subject: [PATCH 17/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/Ashutosh652.json | 2 +- badges/Ashutosh652.svg | 4 ++-- badges/Ashutosh652_badges.md | 6 +++--- badges/Ashutosh652_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/Ashutosh652.json b/badges/Ashutosh652.json index c4e1b39b..d9ae943c 100644 --- a/badges/Ashutosh652.json +++ b/badges/Ashutosh652.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (4/30)", + "message": "\ud83c\udf31 Beginner (6/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/Ashutosh652.svg b/badges/Ashutosh652.svg index 5551a5ae..5f473f53 100644 --- a/badges/Ashutosh652.svg +++ b/badges/Ashutosh652.svg @@ -46,10 +46,10 @@ - + - 4/30 (13.3%) + 6/30 (20.0%) Ready for diff --git a/badges/Ashutosh652_badges.md b/badges/Ashutosh652_badges.md index 98fc8bf1..ce04c9d1 100644 --- a/badges/Ashutosh652_badges.md +++ b/badges/Ashutosh652_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/Ashutosh652.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-4%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-6%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-13.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-20.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @Ashutosh652 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 4/30 (13.3% complete) +**📊 Classic Challenges:** 6/30 (20.0% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/Ashutosh652_compact.svg b/badges/Ashutosh652_compact.svg index 7d58860b..f3529336 100644 --- a/badges/Ashutosh652_compact.svg +++ b/badges/Ashutosh652_compact.svg @@ -33,10 +33,10 @@ - + - 4/30 (13.3%) + 6/30 (20.0%) 🌱 \ No newline at end of file From 444f562b1ed15844885c3fbf8a2400a3404e1adf Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 21:58:16 +0000 Subject: [PATCH 18/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-27?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-27/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-27/SCOREBOARD.md b/challenge-27/SCOREBOARD.md index 3965e0bd..57c604fb 100644 --- a/challenge-27/SCOREBOARD.md +++ b/challenge-27/SCOREBOARD.md @@ -11,4 +11,5 @@ | diyorich | 28 | 28 | | mick4711 | 28 | 28 | | odelbos | 28 | 28 | +| t4e1 | 28 | 28 | | y1hao | 28 | 28 | From 761578a2d84d37efbcd49af0f0428d4413e0dace Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Tue, 2 Sep 2025 21:58:31 +0000 Subject: [PATCH 19/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1a72f7ed..dadb7d7f 100644 --- a/README.md +++ b/README.md @@ -85,9 +85,9 @@ Our most accomplished Go developers, ranked by number of challenges completed: | 5 |
**[Gandook](https://github.com/Gandook)** | **20**/30 | **66.7%** | Master | ✅✅✅✅⬜✅✅✅✅✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅✅✅⬜✅⬜⬜✅ | | 6 |
**[JackDalberg](https://github.com/JackDalberg)** | **20**/30 | **66.7%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
⬜✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | | 7 |
**[ashwinipatankar](https://github.com/ashwinipatankar)** ❤️ | **18**/30 | **60.0%** | Expert | ✅✅✅⬜✅✅✅⬜✅✅⬜⬜✅✅⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜✅⬜⬜✅ | -| 8 |
**[KhaledMosaad](https://github.com/KhaledMosaad)** | **14**/30 | **46.7%** | Advanced | ✅✅✅⬜⬜✅⬜⬜⬜⬜⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜✅✅⬜⬜✅ | -| 9 |
**[RezaSi](https://github.com/RezaSi)** | **14**/30 | **46.7%** | Advanced | ✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜⬜⬜⬜⬜ | -| 10 |
**[t4e1](https://github.com/t4e1)** | **14**/30 | **46.7%** | Advanced | ✅✅✅✅✅✅✅⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅⬜⬜⬜⬜⬜⬜⬜⬜ | +| 8 |
**[t4e1](https://github.com/t4e1)** | **15**/30 | **50.0%** | Expert | ✅✅✅✅✅✅✅⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅⬜⬜⬜⬜✅⬜⬜⬜ | +| 9 |
**[KhaledMosaad](https://github.com/KhaledMosaad)** | **14**/30 | **46.7%** | Advanced | ✅✅✅⬜⬜✅⬜⬜⬜⬜⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜✅✅⬜⬜✅ | +| 10 |
**[RezaSi](https://github.com/RezaSi)** | **14**/30 | **46.7%** | Advanced | ✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜⬜⬜⬜⬜ |
From 573299af79d0ff29ce8b5c0ffe89115df90453f1 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 21:58:40 +0000 Subject: [PATCH 20/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/t4e1.json | 4 ++-- badges/t4e1.svg | 18 +++++++++--------- badges/t4e1_badges.md | 10 +++++----- badges/t4e1_compact.svg | 14 +++++++------- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/badges/t4e1.json b/badges/t4e1.json index cba40b57..f337b845 100644 --- a/badges/t4e1.json +++ b/badges/t4e1.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\u26a1 Advanced (14/30)", - "color": "orange", + "message": "\ud83c\udfaf Expert (15/30)", + "color": "blue", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/t4e1.svg b/badges/t4e1.svg index 5c28acb7..1d967521 100644 --- a/badges/t4e1.svg +++ b/badges/t4e1.svg @@ -7,13 +7,13 @@ - - + + - - + + @@ -34,11 +34,11 @@ github.com/RezaSi/go-interview-practice - + 🎯 @t4e1 - ⚡ Advanced Developer + 🎯 Expert Developer Classic Challenges @@ -46,12 +46,12 @@ - + - 14/30 (46.7%) + 15/30 (50.0%) Ready for - Package Challenges! + Package Challenges! \ No newline at end of file diff --git a/badges/t4e1_badges.md b/badges/t4e1_badges.md index be76bdaf..a00c4c17 100644 --- a/badges/t4e1_badges.md +++ b/badges/t4e1_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/t4e1.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-14%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Achievement Level](https://img.shields.io/badge/Level-⚡_Advanced-orange?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-46.7%25-orange?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-15%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Achievement Level](https://img.shields.io/badge/Level-🎯_Expert-blue?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-50.0%25-blue?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -27,6 +27,6 @@ ### 📈 Your Achievement Summary **👤 Username:** @t4e1 -**🏅 Achievement Level:** ⚡ **Advanced Developer** -**📊 Classic Challenges:** 14/30 (46.7% complete) +**🏅 Achievement Level:** 🎯 **Expert Developer** +**📊 Classic Challenges:** 15/30 (50.0% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/t4e1_compact.svg b/badges/t4e1_compact.svg index df1a0fe6..3f4ba2a6 100644 --- a/badges/t4e1_compact.svg +++ b/badges/t4e1_compact.svg @@ -1,8 +1,8 @@ - - + + @@ -26,17 +26,17 @@ @t4e1 - ⚡ Advanced Developer + 🎯 Expert Developer Classic Progress - + - 14/30 (46.7%) - - + 15/30 (50.0%) + + 🎯 \ No newline at end of file From 541ce4e219487b0025ea63a88a3f3af705cb51d1 Mon Sep 17 00:00:00 2001 From: Polina <88816018+PolinaSvet@users.noreply.github.com> Date: Wed, 3 Sep 2025 02:00:16 +0400 Subject: [PATCH 21/58] Add solution for Challenges by PolinaSvet (#342) * Add solution for Challenge 25 by PolinaSvet * Add solution for Challenge 26 by PolinaSvet * Add solution for Challenge 28 by PolinaSvet --- .../PolinaSvet/solution-template.go | 219 ++++++ .../PolinaSvet/solution-template.go | 239 ++++++ .../PolinaSvet/solution-template.go | 108 +++ .../PolinaSvet/solution-template.go | 713 ++++++++++++++++++ 4 files changed, 1279 insertions(+) create mode 100644 challenge-24/submissions/PolinaSvet/solution-template.go create mode 100644 challenge-25/submissions/PolinaSvet/solution-template.go create mode 100644 challenge-26/submissions/PolinaSvet/solution-template.go create mode 100644 challenge-28/submissions/PolinaSvet/solution-template.go diff --git a/challenge-24/submissions/PolinaSvet/solution-template.go b/challenge-24/submissions/PolinaSvet/solution-template.go new file mode 100644 index 00000000..240dca3f --- /dev/null +++ b/challenge-24/submissions/PolinaSvet/solution-template.go @@ -0,0 +1,219 @@ +package main + +import ( + "fmt" + "math/rand" + "runtime" + "time" +) + +func main() { + // Test cases + testCases := []struct { + name string + nums []int + }{ + {"Example 01: 4", []int{10, 9, 2, 5, 3, 7, 101, 18}}, + {"Example 02: 4", []int{0, 1, 0, 3, 2, 3}}, + {"Example 03: 1", []int{7, 7, 7, 7, 7, 7, 7}}, + {"Example 04: 3", []int{4, 10, 4, 3, 8, 9}}, + {"Example 05: 0", []int{}}, + {"Example 06: 1", []int{5}}, + {"Example 07: 1", []int{5, 4, 3, 2, 1}}, + {"Example 08: 5", []int{1, 2, 3, 4, 5}}, + {"Example 09: 3", []int{3, 10, 2, 1, 20}}, + {"Example 10: 4", []int{50, 3, 10, 7, 40, 80}}, + } + + // Test each approach + for _, tc := range testCases { + dpLength := DPLongestIncreasingSubsequence(tc.nums) + fmt.Printf("Standart%s = %d, %v\n", tc.name, dpLength, tc.nums) + + optLength := OptimizedLIS(tc.nums) + fmt.Printf("OPT_____%s = %d, %v\n", tc.name, optLength, tc.nums) + + lisElements := GetLISElements(tc.nums) + fmt.Printf("LIS Elements: %v\n", lisElements) + fmt.Println("-----------------------------------") + } + + fmt.Println("\n=== Performance Tests ===") + runPerformanceTests() + + fmt.Println("\n=== Memory Usage Tests ===") + runMemoryTests() +} + +// DPLongestIncreasingSubsequence finds the length of the longest increasing subsequence +// using a standard dynamic programming approach with O(n²) time complexity. +func DPLongestIncreasingSubsequence(nums []int) int { + // TODO: Implement this function + if len(nums) == 0 { + return 0 + } + + dp := make([]int, len(nums)) + for i := range dp { + dp[i] = 1 + } + + maxLength := 1 + for i := 1; i < len(nums); i++ { + for j := 0; j < i; j++ { + if nums[i] > nums[j] { + if dp[j]+1 > dp[i] { + dp[i] = dp[j] + 1 + } + } + } + if dp[i] > maxLength { + maxLength = dp[i] + } + } + + return maxLength +} + +// OptimizedLIS finds the length of the longest increasing subsequence +// using an optimized approach with O(n log n) time complexity. +func OptimizedLIS(nums []int) int { + // TODO: Implement this function + if len(nums) == 0 { + return 0 + } + + tails := make([]int, 0) + tails = append(tails, nums[0]) + + for i := 1; i < len(nums); i++ { + if nums[i] > tails[len(tails)-1] { + tails = append(tails, nums[i]) + } else { + + left, right := 0, len(tails)-1 + for left < right { + mid := left + (right-left)/2 + if tails[mid] < nums[i] { + left = mid + 1 + } else { + right = mid + } + } + tails[left] = nums[i] + } + } + + return len(tails) +} + +// GetLISElements returns one possible longest increasing subsequence +// (not just the length, but the actual elements). +func GetLISElements(nums []int) []int { + // TODO: Implement this function + if len(nums) == 0 { + return nil + } + + dp := make([]int, len(nums)) + prev := make([]int, len(nums)) + for i := range dp { + dp[i] = 1 + prev[i] = -1 + } + + maxLength := 1 + maxIndex := 0 + + for i := 1; i < len(nums); i++ { + for j := 0; j < i; j++ { + if nums[i] > nums[j] && dp[j]+1 > dp[i] { + dp[i] = dp[j] + 1 + prev[i] = j + } + } + if dp[i] > maxLength { + maxLength = dp[i] + maxIndex = i + } + } + + lis := make([]int, maxLength) + for i := maxLength - 1; i >= 0; i-- { + lis[i] = nums[maxIndex] + maxIndex = prev[maxIndex] + if maxIndex == -1 { + break + } + } + + return lis +} + +func generateTestData(size int) []int { + rand.Seed(time.Now().UnixNano()) + data := make([]int, size) + for i := range data { + data[i] = rand.Intn(size * 2) + } + return data +} + +func runPerformanceTests() { + sizes := []int{100, 500, 1000, 2000, 5000} + iterations := 10 + + for _, size := range sizes { + fmt.Printf("\nTesting with size %d (%d iterations):\n", size, iterations) + testData := generateTestData(size) + + var totalTime1, totalTime2 time.Duration + + for i := 0; i < iterations; i++ { + start := time.Now() + DPLongestIncreasingSubsequence(testData) + totalTime1 += time.Since(start) + } + + for i := 0; i < iterations; i++ { + start := time.Now() + OptimizedLIS(testData) + totalTime2 += time.Since(start) + } + + avgTime1 := totalTime1 / time.Duration(iterations) + avgTime2 := totalTime2 / time.Duration(iterations) + + fmt.Printf("Standart: avg time: %v\n", avgTime1) + fmt.Printf("OPT_____: avg time: %v\n", avgTime2) + + } +} + +// Memory test function +func runMemoryTests() { + sizes := []int{100, 500, 1000, 2000} + + for _, size := range sizes { + fmt.Printf("\nMemory test with size %d:\n", size) + testData := generateTestData(size) + + var m1, m2 runtime.MemStats + + runtime.GC() + runtime.ReadMemStats(&m1) + mResult1 := DPLongestIncreasingSubsequence(testData) + runtime.ReadMemStats(&m2) + mMemory1 := m2.Alloc - m1.Alloc + + runtime.GC() + runtime.ReadMemStats(&m1) + mResult2 := OptimizedLIS(testData) + runtime.ReadMemStats(&m2) + mMemory2 := m2.Alloc - m1.Alloc + + fmt.Printf("Standart: result=%d, memory=%d bytes\n", mResult1, mMemory1) + fmt.Printf("OPT_____: result=%d, memory=%d bytes\n", mResult2, mMemory2) + + } +} diff --git a/challenge-25/submissions/PolinaSvet/solution-template.go b/challenge-25/submissions/PolinaSvet/solution-template.go new file mode 100644 index 00000000..a6b55bbc --- /dev/null +++ b/challenge-25/submissions/PolinaSvet/solution-template.go @@ -0,0 +1,239 @@ +package main + +import ( + "fmt" +) + +func main() { + // Example 1: Unweighted graph for BFS + unweightedGraph := [][]int{ + {1, 2}, // Vertex 0 has edges to vertices 1 and 2 + {0, 3, 4}, // Vertex 1 has edges to vertices 0, 3, and 4 + {0, 5}, // Vertex 2 has edges to vertices 0 and 5 + {1}, // Vertex 3 has an edge to vertex 1 + {1}, // Vertex 4 has an edge to vertex 1 + {2}, // Vertex 5 has an edge to vertex 2 + } + + // Test BFS + distances, predecessors := BreadthFirstSearch(unweightedGraph, 0) + fmt.Println("BFS Results:") + fmt.Printf("Distances: %v\n", distances) + fmt.Printf("Predecessors: %v\n", predecessors) + fmt.Println() + + // Example 2: Weighted graph for Dijkstra + weightedGraph := [][]int{ + {1, 2}, // Vertex 0 has edges to vertices 1 and 2 + {0, 3, 4}, // Vertex 1 has edges to vertices 0, 3, and 4 + {0, 5}, // Vertex 2 has edges to vertices 0 and 5 + {1}, // Vertex 3 has an edge to vertex 1 + {1}, // Vertex 4 has an edge to vertex 1 + {2}, // Vertex 5 has an edge to vertex 2 + } + weights := [][]int{ + {5, 10}, // Edge from 0 to 1 has weight 5, edge from 0 to 2 has weight 10 + {5, 3, 2}, // Edge weights from vertex 1 + {10, 2}, // Edge weights from vertex 2 + {3}, // Edge weights from vertex 3 + {2}, // Edge weights from vertex 4 + {2}, // Edge weights from vertex 5 + } + + // Test Dijkstra + dijkstraDistances, dijkstraPredecessors := Dijkstra(weightedGraph, weights, 0) + fmt.Println("Dijkstra Results:") + fmt.Printf("Distances: %v\n", dijkstraDistances) + fmt.Printf("Predecessors: %v\n", dijkstraPredecessors) + fmt.Println() + + // Example 3: Graph with negative weights for Bellman-Ford + negativeWeightGraph := [][]int{ + {1, 2}, + {3}, + {1, 3}, + {4}, + {}, + } + negativeWeights := [][]int{ + {6, 7}, // Edge weights from vertex 0 + {5}, // Edge weights from vertex 1 + {-2, 4}, // Edge weights from vertex 2 (note the negative weight) + {2}, // Edge weights from vertex 3 + {}, // Edge weights from vertex 4 + } + + // Test Bellman-Ford + bfDistances, hasPath, bfPredecessors := BellmanFord(negativeWeightGraph, negativeWeights, 0) + fmt.Println("Bellman-Ford Results:") + fmt.Printf("Distances: %v\n", bfDistances) + fmt.Printf("Has Path: %v\n", hasPath) + fmt.Printf("Predecessors: %v\n", bfPredecessors) +} + +const ( + inf = 1000000000 +) + +// BreadthFirstSearch implements BFS for unweighted graphs to find shortest paths +// from a source vertex to all other vertices. +// Returns: +// - distances: slice where distances[i] is the shortest distance from source to vertex i +// - predecessors: slice where predecessors[i] is the vertex that comes before i in the shortest path +func BreadthFirstSearch(graph [][]int, source int) ([]int, []int) { + // TODO: Implement this function + + l := len(graph) + distances := make([]int, l) + predecessors := make([]int, l) + + mark := make(map[int]bool) + + for i := 0; i < l; i++ { + distances[i] = inf + predecessors[i] = -1 + } + + queue := []int{source} + mark[source] = true + distances[source] = 0 + + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + for _, v := range graph[curr] { + if _, ok := mark[v]; !ok { + mark[v] = true + distances[v] = distances[curr] + 1 + predecessors[v] = curr + queue = append(queue, v) + } + } + + } + + return distances, predecessors +} + +// Dijkstra implements Dijkstra's algorithm for weighted graphs with non-negative weights +// to find shortest paths from a source vertex to all other vertices. +// Returns: +// - distances: slice where distances[i] is the shortest distance from source to vertex i +// - predecessors: slice where predecessors[i] is the vertex that comes before i in the shortest path +func Dijkstra(graph [][]int, weights [][]int, source int) ([]int, []int) { + // TODO: Implement this function + l := len(graph) + distances := make([]int, l) + predecessors := make([]int, l) + + mark := make(map[int]bool) + + for i := 0; i < l; i++ { + distances[i] = inf + predecessors[i] = -1 + } + + queue := []int{source} + mark[source] = true + distances[source] = 0 + + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + for i, v := range graph[curr] { + if _, ok := mark[v]; !ok { + mark[v] = true + distances[v] = distances[curr] + weights[curr][i] + predecessors[v] = curr + queue = append(queue, v) + } + } + + } + + return distances, predecessors +} + +// BellmanFord implements the Bellman-Ford algorithm for weighted graphs that may contain +// negative weight edges to find shortest paths from a source vertex to all other vertices. +// Returns: +// - distances: slice where distances[i] is the shortest distance from source to vertex i +// - hasPath: slice where hasPath[i] is true if there is a path from source to i without a negative cycle +// - predecessors: slice where predecessors[i] is the vertex that comes before i in the shortest path +func BellmanFord(graph [][]int, weights [][]int, source int) ([]int, []bool, []int) { + // TODO: Implement this function + l := len(graph) + distances := make([]int, l) + predecessors := make([]int, l) + hasPath := make([]bool, l) + + for i := 0; i < l; i++ { + distances[i] = inf + predecessors[i] = -1 + hasPath[i] = false + } + + distances[source] = 0 + hasPath[source] = true + + for i := 0; i < l-1; i++ { + changed := false + for u := 0; u < l; u++ { + if distances[u] == inf { + continue + } + for j, v := range graph[u] { + w := weights[u][j] + if distances[u]+w < distances[v] { + distances[v] = distances[u] + w + predecessors[v] = u + hasPath[v] = true + changed = true + } + } + } + if !changed { + break + } + } + + visited := make([]bool, l) + for u := 0; u < l; u++ { + if distances[u] == inf { + continue + } + for j, v := range graph[u] { + w := weights[u][j] + if distances[u]+w < distances[v] { + markReachableFromCycle(graph, u, distances, hasPath, visited) + } + } + } + + return distances, hasPath, predecessors +} + +func markReachableFromCycle(graph [][]int, start int, distances []int, hasPath []bool, visited []bool) { + + for i := range visited { + visited[i] = false + } + + queue := []int{start} + visited[start] = true + + for len(queue) > 0 { + u := queue[0] + queue = queue[1:] + + distances[u] = -inf + hasPath[u] = false + + for _, v := range graph[u] { + if !visited[v] { + visited[v] = true + queue = append(queue, v) + } + } + } +} diff --git a/challenge-26/submissions/PolinaSvet/solution-template.go b/challenge-26/submissions/PolinaSvet/solution-template.go new file mode 100644 index 00000000..4d51f69a --- /dev/null +++ b/challenge-26/submissions/PolinaSvet/solution-template.go @@ -0,0 +1,108 @@ +package regex + +import ( + "regexp" + "strings" +) + +// ExtractEmails extracts all valid email addresses from a text +func ExtractEmails(text string) []string { + // TODO: Implement this function + // 1. Create a regular expression to match email addresses + // 2. Find all matches in the input text + // 3. Return the matched emails as a slice of strings + + // Email validation (simplified) + re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`) + result := re.FindAllString(text, -1) + + if result == nil { + return []string{} + } + return result +} + +// ValidatePhone checks if a string is a valid phone number in format (XXX) XXX-XXXX +func ValidatePhone(phone string) bool { + // TODO: Implement this function + // 1. Create a regular expression to match the specified phone format + // 2. Check if the input string matches the pattern + // 3. Return true if it's a match, false otherwise + + // Phone number validation (US format) + re := regexp.MustCompile(`^\(\d{3}\) \d{3}-\d{4}$`) + result := re.MatchString(phone) // true + + return result +} + +// MaskCreditCard replaces all but the last 4 digits of a credit card number with "X" +// Example: "1234-5678-9012-3456" -> "XXXX-XXXX-XXXX-3456" +func MaskCreditCard(cardNumber string) string { + // TODO: Implement this function + // 1. Create a regular expression to identify the parts of the card number to mask + // 2. Use ReplaceAllString or similar method to perform the replacement + // 3. Return the masked card number + + re := regexp.MustCompile(`^(.*)(\d{4})([^\d]*)$`) + return re.ReplaceAllStringFunc(cardNumber, func(s string) string { + parts := re.FindStringSubmatch(s) + if len(parts) != 4 { + return s + } + + masked := regexp.MustCompile(`\d`).ReplaceAllString(parts[1], "X") + return masked + parts[2] + parts[3] + }) +} + +// ParseLogEntry parses a log entry with format: +// "YYYY-MM-DD HH:MM:SS LEVEL Message" +// Returns a map with keys: "date", "time", "level", "message" +func ParseLogEntry(logLine string) map[string]string { + // TODO: Implement this function + // 1. Create a regular expression with capture groups for each component + // 2. Use FindStringSubmatch to extract the components + // 3. Populate a map with the extracted values + // 4. Return the populated map + + // Define regex to parse log entries + logPattern := regexp.MustCompile(`^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+) (.+)$`) + + matches := logPattern.FindStringSubmatch(logLine) + if len(matches) == 5 { + date := matches[1] + time := matches[2] + level := matches[3] + message := matches[4] + + return map[string]string{ + "date": date, + "time": time, + "level": level, + "message": message, + } + + } + + return nil +} + +// ExtractURLs extracts all valid URLs from a text +func ExtractURLs(text string) []string { + // TODO: Implement this function + // 1. Create a regular expression to match URLs (both http and https) + // 2. Find all matches in the input text + // 3. Return the matched URLs as a slice of strings + + re := regexp.MustCompile(`https?://[^\s<>"']+`) + matches := re.FindAllString(text, -1) + result := make([]string, 0, len(matches)) + for _, url := range matches { + url = strings.TrimRight(url, ".,;:!?')]}\"") + result = append(result, url) + } + + return result + +} diff --git a/challenge-28/submissions/PolinaSvet/solution-template.go b/challenge-28/submissions/PolinaSvet/solution-template.go new file mode 100644 index 00000000..a9b529fc --- /dev/null +++ b/challenge-28/submissions/PolinaSvet/solution-template.go @@ -0,0 +1,713 @@ +package cache + +import ( + "sync" +) + +// Cache interface defines the contract for all cache implementations +type Cache interface { + Get(key string) (value interface{}, found bool) + Put(key string, value interface{}) + Delete(key string) bool + Clear() + Size() int + Capacity() int + HitRate() float64 +} + +// CachePolicy represents the eviction policy type +type CachePolicy int + +const ( + LRU CachePolicy = iota + LFU + FIFO +) + +// +// LRU Cache Implementation +// + +type NodeLRU struct { + key string + value interface{} + prev *NodeLRU + next *NodeLRU +} + +type LRUCache struct { + // TODO: Add necessary fields for LRU implementation + // Hint: Use a doubly-linked list + hash map + capacity int + cache map[string]*NodeLRU + head *NodeLRU // Most recently used + tail *NodeLRU // Least recently used + mu sync.RWMutex + hits int + misses int +} + +// NewLRUCache creates a new LRU cache with the specified capacity +func NewLRUCache(capacity int) *LRUCache { + // TODO: Implement LRU cache constructor + if capacity <= 0 { + return nil + } + + return &LRUCache{ + capacity: capacity, + cache: make(map[string]*NodeLRU), + head: nil, + tail: nil, + hits: 0, + misses: 0, + } +} + +func (c *LRUCache) removeNode(node *NodeLRU) { + if node.prev != nil { + node.prev.next = node.next + } else { + c.head = node.next + } + + if node.next != nil { + node.next.prev = node.prev + } else { + c.tail = node.prev + } + + node.prev = nil + node.next = nil +} + +func (c *LRUCache) addToFront(node *NodeLRU) { + node.next = c.head + node.prev = nil + + if c.head != nil { + c.head.prev = node + } + c.head = node + + if c.tail == nil { + c.tail = node + } +} + +func (c *LRUCache) moveToFront(node *NodeLRU) { + if node == c.head { + return + } + + c.removeNode(node) + c.addToFront(node) +} + +func (c *LRUCache) Get(key string) (interface{}, bool) { + // TODO: Implement LRU get operation + // Should move accessed item to front (most recently used position) + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.moveToFront(node) + c.hits++ + return node.value, true + } + + c.misses++ + return nil, false +} + +func (c *LRUCache) Put(key string, value interface{}) { + // TODO: Implement LRU put operation + // Should add new item to front and evict least recently used if at capacity + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + node.value = value + c.moveToFront(node) + return + } + + newNode := &NodeLRU{ + key: key, + value: value, + } + + if len(c.cache) >= c.capacity { + if c.tail != nil { + delete(c.cache, c.tail.key) + c.removeNode(c.tail) + } + } + + c.addToFront(newNode) + c.cache[key] = newNode + +} + +func (c *LRUCache) Delete(key string) bool { + // TODO: Implement delete operation + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.removeNode(node) + delete(c.cache, key) + return true + } + return false +} + +func (c *LRUCache) Clear() { + // TODO: Implement clear operation + c.mu.Lock() + defer c.mu.Unlock() + + c.cache = make(map[string]*NodeLRU) + c.head = nil + c.tail = nil + c.hits = 0 + c.misses = 0 +} + +func (c *LRUCache) Size() int { + // TODO: Return current cache size + c.mu.RLock() + defer c.mu.RUnlock() + + return len(c.cache) +} + +func (c *LRUCache) Capacity() int { + // TODO: Return cache capacity + return c.capacity +} + +func (c *LRUCache) HitRate() float64 { + // TODO: Calculate and return hit rate + c.mu.RLock() + defer c.mu.RUnlock() + + total := c.hits + c.misses + if total == 0 { + return 0.0 + } + return float64(c.hits) / float64(total) +} + +// +// LFU Cache Implementation +// + +type NodeLFU struct { + key string + value interface{} + freq int + prev *NodeLFU + next *NodeLFU + freqGroup *FreqGroup +} + +type FreqGroup struct { + freq int + head *NodeLFU + tail *NodeLFU + count int +} + +type LFUCache struct { + // TODO: Add necessary fields for LFU implementation + // Hint: Use frequency tracking with efficient eviction + capacity int + minFreq int + cache map[string]*NodeLFU + freqGroups map[int]*FreqGroup + mu sync.RWMutex + hits int + misses int +} + +// NewLFUCache creates a new LFU cache with the specified capacity +func NewLFUCache(capacity int) *LFUCache { + // TODO: Implement LFU cache constructor + if capacity <= 0 { + return nil + } + return &LFUCache{ + capacity: capacity, + minFreq: 1, + cache: make(map[string]*NodeLFU), + freqGroups: make(map[int]*FreqGroup), + hits: 0, + misses: 0, + } +} + +func (c *LFUCache) createFreqGroup(freq int) *FreqGroup { + group := &FreqGroup{ + freq: freq, + head: nil, + tail: nil, + count: 0, + } + c.freqGroups[freq] = group + return group +} + +func (c *LFUCache) removeNodeFromGroup(node *NodeLFU) { + if node.freqGroup == nil { + return + } + + group := node.freqGroup + + if node.prev != nil { + node.prev.next = node.next + } else { + group.head = node.next + } + + if node.next != nil { + node.next.prev = node.prev + } else { + group.tail = node.prev + } + + group.count-- + node.prev = nil + node.next = nil + + if group.count == 0 { + delete(c.freqGroups, group.freq) + if group.freq == c.minFreq { + c.minFreq++ + } + } +} + +func (c *LFUCache) addNodeToGroup(node *NodeLFU, group *FreqGroup) { + node.freqGroup = group + node.freq = group.freq + + node.next = group.head + node.prev = nil + + if group.head != nil { + group.head.prev = node + } + group.head = node + + if group.tail == nil { + group.tail = node + } + + group.count++ +} + +func (c *LFUCache) moveNodeToNewFreq(node *NodeLFU) { + oldFreq := node.freq + newFreq := oldFreq + 1 + + c.removeNodeFromGroup(node) + + newGroup, exists := c.freqGroups[newFreq] + if !exists { + newGroup = c.createFreqGroup(newFreq) + } + + c.addNodeToGroup(node, newGroup) + + if oldFreq == c.minFreq { + if _, exists := c.freqGroups[oldFreq]; !exists { + c.minFreq = newFreq + } + } +} + +func (c *LFUCache) evictLFU() { + minGroup, exists := c.freqGroups[c.minFreq] + if !exists || minGroup.tail == nil { + return + } + + nodeToEvict := minGroup.tail + delete(c.cache, nodeToEvict.key) + c.removeNodeFromGroup(nodeToEvict) +} + +func (c *LFUCache) Get(key string) (interface{}, bool) { + // TODO: Implement LFU get operation + // Should increment frequency count of accessed item + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.moveNodeToNewFreq(node) + c.hits++ + return node.value, true + } + + c.misses++ + return nil, false +} + +func (c *LFUCache) Put(key string, value interface{}) { + // TODO: Implement LFU put operation + // Should evict least frequently used item if at capacity + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + node.value = value + c.moveNodeToNewFreq(node) + return + } + + if len(c.cache) >= c.capacity { + c.evictLFU() + } + + newNode := &NodeLFU{ + key: key, + value: value, + freq: 1, + } + + group, exists := c.freqGroups[1] + if !exists { + group = c.createFreqGroup(1) + } + c.addNodeToGroup(newNode, group) + + c.cache[key] = newNode + c.minFreq = 1 +} + +func (c *LFUCache) Delete(key string) bool { + // TODO: Implement delete operation + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.removeNodeFromGroup(node) + delete(c.cache, key) + return true + } + return false +} + +func (c *LFUCache) Clear() { + // TODO: Implement clear operation + c.mu.Lock() + defer c.mu.Unlock() + + c.cache = make(map[string]*NodeLFU) + c.freqGroups = make(map[int]*FreqGroup) + c.minFreq = 1 + c.hits = 0 + c.misses = 0 +} + +func (c *LFUCache) Size() int { + // TODO: Return current cache size + c.mu.RLock() + defer c.mu.RUnlock() + + return len(c.cache) +} + +func (c *LFUCache) Capacity() int { + // TODO: Return cache capacity + return c.capacity +} + +func (c *LFUCache) HitRate() float64 { + // TODO: Calculate and return hit rate + c.mu.RLock() + defer c.mu.RUnlock() + + total := c.hits + c.misses + if total == 0 { + return 0.0 + } + return float64(c.hits) / float64(total) +} + +// FIFO Cache Implementation +type NodeFIFO struct { + key string + value interface{} + prev *NodeFIFO + next *NodeFIFO +} + +type FIFOCache struct { + // TODO: Add necessary fields for FIFO implementation + // Hint: Use a queue or circular buffer + capacity int + cache map[string]*NodeFIFO + head *NodeFIFO // Newest item + tail *NodeFIFO // Oldest item + mu sync.RWMutex + hits int + misses int +} + +// NewFIFOCache creates a new FIFO cache with the specified capacity +func NewFIFOCache(capacity int) *FIFOCache { + // TODO: Implement FIFO cache constructor + if capacity <= 0 { + return nil + } + + return &FIFOCache{ + capacity: capacity, + cache: make(map[string]*NodeFIFO), + head: nil, + tail: nil, + hits: 0, + misses: 0, + } +} + +func (c *FIFOCache) removeNode(node *NodeFIFO) { + if node.prev != nil { + node.prev.next = node.next + } else { + c.head = node.next + } + + if node.next != nil { + node.next.prev = node.prev + } else { + c.tail = node.prev + } + + node.prev = nil + node.next = nil +} + +func (c *FIFOCache) addToFront(node *NodeFIFO) { + node.next = c.head + node.prev = nil + + if c.head != nil { + c.head.prev = node + } + c.head = node + + if c.tail == nil { + c.tail = node + } +} + +func (c *FIFOCache) moveToFront(node *NodeFIFO) { + if node == c.head { + return + } + + c.removeNode(node) + c.addToFront(node) +} + +func (c *FIFOCache) Get(key string) (interface{}, bool) { + // TODO: Implement FIFO get operation + // Note: Get operations don't affect eviction order in FIFO + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.hits++ + return node.value, true + } + + c.misses++ + return nil, false +} + +func (c *FIFOCache) Put(key string, value interface{}) { + // TODO: Implement FIFO put operation + // Should evict first-in item if at capacity + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + node.value = value + return + } + + newNode := &NodeFIFO{ + key: key, + value: value, + } + + if len(c.cache) >= c.capacity { + if c.tail != nil { + delete(c.cache, c.tail.key) + c.removeNode(c.tail) + } + } + + c.addToFront(newNode) + c.cache[key] = newNode +} + +func (c *FIFOCache) Delete(key string) bool { + // TODO: Implement delete operation + c.mu.Lock() + defer c.mu.Unlock() + + if node, exists := c.cache[key]; exists { + c.removeNode(node) + delete(c.cache, key) + return true + } + return false +} + +func (c *FIFOCache) Clear() { + // TODO: Implement clear operation + c.mu.Lock() + defer c.mu.Unlock() + + c.cache = make(map[string]*NodeFIFO) + c.head = nil + c.tail = nil + c.hits = 0 + c.misses = 0 +} + +func (c *FIFOCache) Size() int { + // TODO: Return current cache size + c.mu.RLock() + defer c.mu.RUnlock() + + return len(c.cache) +} + +func (c *FIFOCache) Capacity() int { + // TODO: Return cache capacity + return c.capacity +} + +func (c *FIFOCache) HitRate() float64 { + // TODO: Calculate and return hit rate + c.mu.RLock() + defer c.mu.RUnlock() + + total := c.hits + c.misses + if total == 0 { + return 0.0 + } + return float64(c.hits) / float64(total) +} + +// +// Thread-Safe Cache Wrapper +// + +type ThreadSafeCache struct { + cache Cache + mu sync.RWMutex + // TODO: Add any additional fields if needed +} + +// NewThreadSafeCache wraps any cache implementation to make it thread-safe +func NewThreadSafeCache(cache Cache) *ThreadSafeCache { + // TODO: Implement thread-safe wrapper constructor + if cache == nil { + return nil + } + return &ThreadSafeCache{cache: cache} +} + +func (c *ThreadSafeCache) Get(key string) (interface{}, bool) { + // TODO: Implement thread-safe get operation + // Hint: Use read lock for better performance + c.mu.RLock() + defer c.mu.RUnlock() + + return c.cache.Get(key) +} + +func (c *ThreadSafeCache) Put(key string, value interface{}) { + // TODO: Implement thread-safe put operation + // Hint: Use write lock + c.mu.Lock() + defer c.mu.Unlock() + c.cache.Put(key, value) +} + +func (c *ThreadSafeCache) Delete(key string) bool { + // TODO: Implement thread-safe delete operation + c.mu.Lock() + defer c.mu.Unlock() + return c.cache.Delete(key) +} + +func (c *ThreadSafeCache) Clear() { + // TODO: Implement thread-safe clear operation + c.mu.Lock() + defer c.mu.Unlock() + c.cache.Clear() +} + +func (c *ThreadSafeCache) Size() int { + // TODO: Implement thread-safe size operation + c.mu.RLock() + defer c.mu.RUnlock() + return c.cache.Size() +} + +func (c *ThreadSafeCache) Capacity() int { + // TODO: Implement thread-safe capacity operation + c.mu.RLock() + defer c.mu.RUnlock() + return c.cache.Capacity() +} + +func (c *ThreadSafeCache) HitRate() float64 { + // TODO: Implement thread-safe hit rate operation + c.mu.RLock() + defer c.mu.RUnlock() + return c.cache.HitRate() +} + +// +// Cache Factory Functions +// + +// NewCache creates a cache with the specified policy and capacity +func NewCache(policy CachePolicy, capacity int) Cache { + // TODO: Implement cache factory + // Should create appropriate cache type based on policy + switch policy { + case LRU: + return NewLRUCache(capacity) + case LFU: + // TODO: Return LFU cache + return NewLFUCache(capacity) + case FIFO: + // TODO: Return FIFO cache + return NewFIFOCache(capacity) + default: + // TODO: Return default cache or handle error + return NewFIFOCache(capacity) + } + +} + +// NewThreadSafeCacheWithPolicy creates a thread-safe cache with the specified policy +func NewThreadSafeCacheWithPolicy(policy CachePolicy, capacity int) Cache { + // TODO: Implement thread-safe cache factory + // Should create cache with policy and wrap it with thread safety + cache := NewCache(policy, capacity) + if cache == nil { + return nil + } + return NewThreadSafeCache(cache) +} From 116f671b2c8cc2e970b2b155f7c39fe99b39b027 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 22:00:47 +0000 Subject: [PATCH 22/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-24=20challenge-25=20challenge-26=20challenge-28?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-24/SCOREBOARD.md | 1 + challenge-25/SCOREBOARD.md | 1 + challenge-26/SCOREBOARD.md | 1 + challenge-28/SCOREBOARD.md | 1 + 4 files changed, 4 insertions(+) diff --git a/challenge-24/SCOREBOARD.md b/challenge-24/SCOREBOARD.md index 3d030961..617fa44a 100644 --- a/challenge-24/SCOREBOARD.md +++ b/challenge-24/SCOREBOARD.md @@ -3,4 +3,5 @@ |------------|--------------|-------------| | Gandook | 33 | 33 | | MYK12397 | 33 | 33 | +| PolinaSvet | 33 | 33 | | odelbos | 33 | 33 | diff --git a/challenge-25/SCOREBOARD.md b/challenge-25/SCOREBOARD.md index 900b6dc2..35da6beb 100644 --- a/challenge-25/SCOREBOARD.md +++ b/challenge-25/SCOREBOARD.md @@ -2,4 +2,5 @@ | Username | Passed Tests | Total Tests | |------------|--------------|-------------| | Gandook | 15 | 15 | +| PolinaSvet | 15 | 15 | | odelbos | 15 | 15 | diff --git a/challenge-26/SCOREBOARD.md b/challenge-26/SCOREBOARD.md index 8e1b2a27..3f843136 100644 --- a/challenge-26/SCOREBOARD.md +++ b/challenge-26/SCOREBOARD.md @@ -2,5 +2,6 @@ | Username | Passed Tests | Total Tests | |------------|--------------|-------------| | KhaledMosaad | 31 | 31 | +| PolinaSvet | 31 | 31 | | mick4711 | 31 | 31 | | odelbos | 31 | 31 | diff --git a/challenge-28/SCOREBOARD.md b/challenge-28/SCOREBOARD.md index b5d83886..937c9215 100644 --- a/challenge-28/SCOREBOARD.md +++ b/challenge-28/SCOREBOARD.md @@ -1,4 +1,5 @@ # Scoreboard for challenge-28 | Username | Passed Tests | Total Tests | |------------|--------------|-------------| +| PolinaSvet | 26 | 26 | | odelbos | 26 | 26 | From 49258f0d64bf555a1eb49eb1390be864d70ae3ac Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Tue, 2 Sep 2025 22:01:03 +0000 Subject: [PATCH 23/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dadb7d7f..4e281208 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Our most accomplished Go developers, ranked by number of challenges completed: | 🏅 | Developer | Solved | Rate | Achievement | Progress | |:---:|:---:|:---:|:---:|:---:|:---| | 🥇 |
**[odelbos](https://github.com/odelbos)** | **30**/30 | **100.0%** | Master | ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅ | -| 🥈 |
**[PolinaSvet](https://github.com/PolinaSvet)** | **25**/30 | **83.3%** | Master | ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
✅✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | +| 🥈 |
**[PolinaSvet](https://github.com/PolinaSvet)** | **29**/30 | **96.7%** | Master | ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
✅✅✅✅✅✅✅✅✅✅✅✅✅⬜✅ | | 🥉 |
**[mick4711](https://github.com/mick4711)** | **23**/30 | **76.7%** | Master | ✅✅✅✅✅✅✅✅✅✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜✅✅⬜⬜✅ | | 4 |
**[y1hao](https://github.com/y1hao)** | **21**/30 | **70.0%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | | 5 |
**[Gandook](https://github.com/Gandook)** | **20**/30 | **66.7%** | Master | ✅✅✅✅⬜✅✅✅✅✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅✅✅⬜✅⬜⬜✅ | From faa7fc29cddc898fe72f967913a6551cebad87c7 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Tue, 2 Sep 2025 22:01:18 +0000 Subject: [PATCH 24/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/PolinaSvet.json | 2 +- badges/PolinaSvet.svg | 4 ++-- badges/PolinaSvet_badges.md | 6 +++--- badges/PolinaSvet_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/PolinaSvet.json b/badges/PolinaSvet.json index eefde0e6..7dc4320f 100644 --- a/badges/PolinaSvet.json +++ b/badges/PolinaSvet.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udfc6 Master (25/30)", + "message": "\ud83c\udfc6 Master (29/30)", "color": "gold", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/PolinaSvet.svg b/badges/PolinaSvet.svg index b226538a..485b451d 100644 --- a/badges/PolinaSvet.svg +++ b/badges/PolinaSvet.svg @@ -46,10 +46,10 @@ - + - 25/30 (83.3%) + 29/30 (96.7%) Ready for diff --git a/badges/PolinaSvet_badges.md b/badges/PolinaSvet_badges.md index 277e736b..56bc6387 100644 --- a/badges/PolinaSvet_badges.md +++ b/badges/PolinaSvet_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/PolinaSvet.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-25%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-29%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🏆_Master-gold?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-83.3%25-gold?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-96.7%25-gold?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @PolinaSvet **🏅 Achievement Level:** 🏆 **Master Developer** -**📊 Classic Challenges:** 25/30 (83.3% complete) +**📊 Classic Challenges:** 29/30 (96.7% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/PolinaSvet_compact.svg b/badges/PolinaSvet_compact.svg index 61b7c66d..69412892 100644 --- a/badges/PolinaSvet_compact.svg +++ b/badges/PolinaSvet_compact.svg @@ -33,10 +33,10 @@ - + - 25/30 (83.3%) + 29/30 (96.7%) \ No newline at end of file From 932c2a69b98ba0578eaf3dbdea9e38bea85ca9e3 Mon Sep 17 00:00:00 2001 From: Mehrad Zamani <33395604+Gandook@users.noreply.github.com> Date: Wed, 3 Sep 2025 20:10:22 +0200 Subject: [PATCH 25/58] Add solution for Challenges by Gandook (#343) * Add solution for Challenge 26 by Gandook * Add solution for Challenge 5 by Gandook --- .../submissions/Gandook/solution-template.go | 95 +++++++++++++++++++ .../submissions/Gandook/solution-template.go | 53 +++++++++++ 2 files changed, 148 insertions(+) create mode 100644 challenge-26/submissions/Gandook/solution-template.go create mode 100644 challenge-5/submissions/Gandook/solution-template.go diff --git a/challenge-26/submissions/Gandook/solution-template.go b/challenge-26/submissions/Gandook/solution-template.go new file mode 100644 index 00000000..262a427b --- /dev/null +++ b/challenge-26/submissions/Gandook/solution-template.go @@ -0,0 +1,95 @@ +package regex + +import ( + "regexp" + "unicode" +) + +// ExtractEmails extracts all valid email addresses from a text +func ExtractEmails(text string) []string { + re, err := regexp.Compile(`(?i)[a-z\d._]+(\+[a-z\d]+)?@[a-z\d-]+(\.[a-z]+)+`) + if err != nil { + panic("the regexp did not compile") + } + + result := re.FindAllString(text, -1) + + if result == nil { + return []string{} + } else { + return result + } +} + +// ValidatePhone checks if a string is a valid phone number in format (XXX) XXX-XXXX +func ValidatePhone(phone string) bool { + re, err := regexp.Compile(`\(\d{3}\) \d{3}-\d{4}`) + if err != nil { + panic("the regexp did not compile") + } + + return len(phone) == 14 && re.MatchString(phone) +} + +// MaskCreditCard replaces all but the last 4 digits of a credit card number with "X" +// Example: "1234-5678-9012-3456" -> "XXXX-XXXX-XXXX-3456" +func MaskCreditCard(cardNumber string) string { + re, err := regexp.Compile(`(\d{4}-?)*\d{4}`) + if err != nil { + panic("the regexp did not compile") + } + + matchIndices := re.FindAllStringIndex(cardNumber, -1) + + if matchIndices == nil { + return cardNumber + } + + cardNumRunes := []rune(cardNumber) + for _, match := range matchIndices { + for i := match[0]; i < match[1]-4; i++ { + if unicode.IsDigit(cardNumRunes[i]) { + cardNumRunes[i] = 'X' + } + } + } + + return string(cardNumRunes) +} + +// ParseLogEntry parses a log entry with format: +// "YYYY-MM-DD HH:MM:SS LEVEL Message" +// Returns a map with keys: "date", "time", "level", "message" +func ParseLogEntry(logLine string) map[string]string { + re, err := regexp.Compile(`(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) ([A-Z]+) (.+)`) + if err != nil { + panic("the regexp did not compile") + } + + matchedPieces := re.FindStringSubmatch(logLine) + if matchedPieces == nil { + return nil + } + + return map[string]string{ + "date": matchedPieces[1], + "time": matchedPieces[2], + "level": matchedPieces[3], + "message": matchedPieces[4], + } +} + +// ExtractURLs extracts all valid URLs from a text +func ExtractURLs(text string) []string { + re, err := regexp.Compile(`https?://(?i)((([a-z\d_]+:.+@)?([a-z\d\-]+)(\.[a-z\d\-]+)+)|localhost)(:\d{4})?(/(?i)[a-z\d.\-_]+)*(\?(?i)[a-z]+=[a-z\d.\-_]+)*(#(?i)[a-z\d]+)?`) + if err != nil { + panic("the regexp did not compile") + } + + matches := re.FindAllString(text, -1) + if matches == nil { + return []string{} + } else { + return matches + } +} diff --git a/challenge-5/submissions/Gandook/solution-template.go b/challenge-5/submissions/Gandook/solution-template.go new file mode 100644 index 00000000..84b92888 --- /dev/null +++ b/challenge-5/submissions/Gandook/solution-template.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "net/http" +) + +const validToken = "secret" + +// AuthMiddleware checks the "X-Auth-Token" header. +// If it's "secret", call the next handler. +// Otherwise, respond with 401 Unauthorized. +func AuthMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + givenToken := r.Header.Get("X-Auth-Token") + if givenToken == validToken { + w.WriteHeader(http.StatusOK) + next.ServeHTTP(w, r) + } else { + w.WriteHeader(http.StatusUnauthorized) + } + }) +} + +// helloHandler returns "Hello!" on GET /hello +func helloHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello!") +} + +// secureHandler returns "You are authorized!" on GET /secure +func secureHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "You are authorized!") +} + +// SetupServer configures the HTTP routes with the authentication middleware. +func SetupServer() http.Handler { + mux := http.NewServeMux() + + // Public route: /hello (no auth required) + mux.HandleFunc("/hello", helloHandler) + + // Secure route: /secure + // Wrap with AuthMiddleware + secureRoute := http.HandlerFunc(secureHandler) + mux.Handle("/secure", AuthMiddleware(secureRoute)) + + return mux +} + +func main() { + // Optional: you can run a real server for local testing + // http.ListenAndServe(":8080", SetupServer()) +} From e3ce20323f74bdb589ad5370d934a9c5a0599ca0 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Wed, 3 Sep 2025 18:11:01 +0000 Subject: [PATCH 26/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-26=20challenge-5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-26/SCOREBOARD.md | 1 + challenge-5/SCOREBOARD.md | 1 + 2 files changed, 2 insertions(+) diff --git a/challenge-26/SCOREBOARD.md b/challenge-26/SCOREBOARD.md index 3f843136..73f10daf 100644 --- a/challenge-26/SCOREBOARD.md +++ b/challenge-26/SCOREBOARD.md @@ -1,6 +1,7 @@ # Scoreboard for challenge-26 | Username | Passed Tests | Total Tests | |------------|--------------|-------------| +| Gandook | 31 | 31 | | KhaledMosaad | 31 | 31 | | PolinaSvet | 31 | 31 | | mick4711 | 31 | 31 | diff --git a/challenge-5/SCOREBOARD.md b/challenge-5/SCOREBOARD.md index 486f4fdf..9442d8bf 100644 --- a/challenge-5/SCOREBOARD.md +++ b/challenge-5/SCOREBOARD.md @@ -3,6 +3,7 @@ |------------|--------------|-------------| | AkifhanIlgaz | 9 | 9 | | Ashutosh652 | 9 | 9 | +| Gandook | 9 | 9 | | JackDalberg | 9 | 9 | | MYK12397 | 9 | 9 | | PolinaSvet | 9 | 9 | From b224b8bb563682799cdb2c861ed594665ad147db Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Wed, 3 Sep 2025 18:11:19 +0000 Subject: [PATCH 27/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4e281208..8e57ef40 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,8 @@ Our most accomplished Go developers, ranked by number of challenges completed: | 🥇 |
**[odelbos](https://github.com/odelbos)** | **30**/30 | **100.0%** | Master | ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅ | | 🥈 |
**[PolinaSvet](https://github.com/PolinaSvet)** | **29**/30 | **96.7%** | Master | ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
✅✅✅✅✅✅✅✅✅✅✅✅✅⬜✅ | | 🥉 |
**[mick4711](https://github.com/mick4711)** | **23**/30 | **76.7%** | Master | ✅✅✅✅✅✅✅✅✅✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜✅✅⬜⬜✅ | -| 4 |
**[y1hao](https://github.com/y1hao)** | **21**/30 | **70.0%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | -| 5 |
**[Gandook](https://github.com/Gandook)** | **20**/30 | **66.7%** | Master | ✅✅✅✅⬜✅✅✅✅✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅✅✅⬜✅⬜⬜✅ | +| 4 |
**[Gandook](https://github.com/Gandook)** | **22**/30 | **73.3%** | Master | ✅✅✅✅✅✅✅✅✅✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅✅✅✅✅⬜⬜✅ | +| 5 |
**[y1hao](https://github.com/y1hao)** | **21**/30 | **70.0%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | | 6 |
**[JackDalberg](https://github.com/JackDalberg)** | **20**/30 | **66.7%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
⬜✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | | 7 |
**[ashwinipatankar](https://github.com/ashwinipatankar)** ❤️ | **18**/30 | **60.0%** | Expert | ✅✅✅⬜✅✅✅⬜✅✅⬜⬜✅✅⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜✅⬜⬜✅ | | 8 |
**[t4e1](https://github.com/t4e1)** | **15**/30 | **50.0%** | Expert | ✅✅✅✅✅✅✅⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅⬜⬜⬜⬜✅⬜⬜⬜ | From 4ca9b7569588d0b9ad535cd4902140bd756740c2 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Wed, 3 Sep 2025 18:11:33 +0000 Subject: [PATCH 28/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/Gandook.json | 2 +- badges/Gandook.svg | 4 ++-- badges/Gandook_badges.md | 6 +++--- badges/Gandook_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/Gandook.json b/badges/Gandook.json index 27289099..21347a28 100644 --- a/badges/Gandook.json +++ b/badges/Gandook.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udfc6 Master (20/30)", + "message": "\ud83c\udfc6 Master (22/30)", "color": "gold", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/Gandook.svg b/badges/Gandook.svg index d4c74a92..7696d9a1 100644 --- a/badges/Gandook.svg +++ b/badges/Gandook.svg @@ -46,10 +46,10 @@ - + - 20/30 (66.7%) + 22/30 (73.3%) Ready for diff --git a/badges/Gandook_badges.md b/badges/Gandook_badges.md index ac161584..a017f9dd 100644 --- a/badges/Gandook_badges.md +++ b/badges/Gandook_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/Gandook.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-20%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-22%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🏆_Master-gold?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-66.7%25-gold?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-73.3%25-gold?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @Gandook **🏅 Achievement Level:** 🏆 **Master Developer** -**📊 Classic Challenges:** 20/30 (66.7% complete) +**📊 Classic Challenges:** 22/30 (73.3% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/Gandook_compact.svg b/badges/Gandook_compact.svg index c9bcc9ba..5f0d7e9a 100644 --- a/badges/Gandook_compact.svg +++ b/badges/Gandook_compact.svg @@ -33,10 +33,10 @@ - + - 20/30 (66.7%) + 22/30 (73.3%) \ No newline at end of file From b55f9e708e344e4813b9ca1d0d1418ee6f99020d Mon Sep 17 00:00:00 2001 From: Quang Long <39556130+longbui98@users.noreply.github.com> Date: Thu, 4 Sep 2025 12:06:39 +0700 Subject: [PATCH 29/58] Add solution for Challenge 17 by longbui98 (#339) --- .../longbui98/solution-template.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 challenge-17/submissions/longbui98/solution-template.go diff --git a/challenge-17/submissions/longbui98/solution-template.go b/challenge-17/submissions/longbui98/solution-template.go new file mode 100644 index 00000000..cc441c2f --- /dev/null +++ b/challenge-17/submissions/longbui98/solution-template.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "regexp" + "strings" +) + +func main() { + // Get input from the user + var input string + fmt.Print("Enter a string to check if it's a palindrome: ") + fmt.Scanln(&input) + + // Call the IsPalindrome function and print the result + result := IsPalindrome(input) + if result { + fmt.Println("The string is a palindrome.") + } else { + fmt.Println("The string is not a palindrome.") + } +} + +// IsPalindrome checks if a string is a palindrome. +// A palindrome reads the same backward as forward, ignoring case, spaces, and punctuation. +func IsPalindrome(s string) bool { + // TODO: Implement this function + // 1. Clean the string (remove spaces, punctuation, and convert to lowercase) + // 2. Check if the cleaned string is the same forwards and backwards + reg := regexp.MustCompile(`[^a-zA-Z0-9]+`) + s = reg.ReplaceAllString(s, "") + s = strings.TrimSpace(s) + + reverseStr := make([]string, 0, len(s)) + for i := len(s) - 1; i >= 0; i-- { + reverseStr = append(reverseStr, string(s[i])) + } + + return strings.EqualFold(s, strings.Join(reverseStr, "")) +} From a909ee4cde46b72a738c9cd571c6aec027b8402b Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:07:06 +0000 Subject: [PATCH 30/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-17/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-17/SCOREBOARD.md b/challenge-17/SCOREBOARD.md index 1a13191b..d80cb2a6 100644 --- a/challenge-17/SCOREBOARD.md +++ b/challenge-17/SCOREBOARD.md @@ -13,6 +13,7 @@ | cep-ter | 18 | 18 | | jordanhimawan | 18 | 18 | | lanmanul | 18 | 18 | +| longbui98 | 18 | 18 | | mick4711 | 18 | 18 | | odelbos | 18 | 18 | | skx | 18 | 18 | From d8b2120f415ab99ba70f0a3240ffc9571d7fbceb Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:07:32 +0000 Subject: [PATCH 31/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/longbui98.json | 2 +- badges/longbui98.svg | 4 ++-- badges/longbui98_badges.md | 6 +++--- badges/longbui98_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/longbui98.json b/badges/longbui98.json index c4e1b39b..275283dd 100644 --- a/badges/longbui98.json +++ b/badges/longbui98.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (4/30)", + "message": "\ud83c\udf31 Beginner (5/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/longbui98.svg b/badges/longbui98.svg index f7585f5d..f2244649 100644 --- a/badges/longbui98.svg +++ b/badges/longbui98.svg @@ -46,10 +46,10 @@ - + - 4/30 (13.3%) + 5/30 (16.7%) Ready for diff --git a/badges/longbui98_badges.md b/badges/longbui98_badges.md index ea6a0ee5..e2cd5c5f 100644 --- a/badges/longbui98_badges.md +++ b/badges/longbui98_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/longbui98.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-4%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-5%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-13.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-16.7%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @longbui98 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 4/30 (13.3% complete) +**📊 Classic Challenges:** 5/30 (16.7% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/longbui98_compact.svg b/badges/longbui98_compact.svg index f160cdee..dd0ca779 100644 --- a/badges/longbui98_compact.svg +++ b/badges/longbui98_compact.svg @@ -33,10 +33,10 @@ - + - 4/30 (13.3%) + 5/30 (16.7%) 🌱 \ No newline at end of file From 955dbabd404fc0df747d1f5630b7f0a63cc25bb2 Mon Sep 17 00:00:00 2001 From: Quang Long <39556130+longbui98@users.noreply.github.com> Date: Thu, 4 Sep 2025 12:08:27 +0700 Subject: [PATCH 32/58] Add solution for Challenge 18 by longbui98 (#340) --- .../longbui98/solution-template.go | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 challenge-18/submissions/longbui98/solution-template.go diff --git a/challenge-18/submissions/longbui98/solution-template.go b/challenge-18/submissions/longbui98/solution-template.go new file mode 100644 index 00000000..ede5dcbb --- /dev/null +++ b/challenge-18/submissions/longbui98/solution-template.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + // Example usage + celsius := 25.0 + fahrenheit := CelsiusToFahrenheit(celsius) + fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit) + + fahrenheit = 68.0 + celsius = FahrenheitToCelsius(fahrenheit) + fmt.Printf("%.2f°F is equal to %.2f°C\n", fahrenheit, celsius) +} + +// CelsiusToFahrenheit converts a temperature from Celsius to Fahrenheit +// Formula: F = C × 9/5 + 32 +func CelsiusToFahrenheit(celsius float64) float64 { + // TODO: Implement this function + f := celsius*9/5 + 32 + // Remember to round to 2 decimal places + return Round(f, 2) +} + +// FahrenheitToCelsius converts a temperature from Fahrenheit to Celsius +// Formula: C = (F - 32) × 5/9 +func FahrenheitToCelsius(fahrenheit float64) float64 { + // TODO: Implement this function + // Remember to round to 2 decimal places + c := (fahrenheit - 32) * 5 / 9 + return Round(c, 2) +} + +// Round rounds a float64 value to the specified number of decimal places +func Round(value float64, decimals int) float64 { + precision := math.Pow10(decimals) + return math.Round(value*precision) / precision +} From e3e5d247016a4b731c187653da4fe4225717afaa Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:08:56 +0000 Subject: [PATCH 33/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-18/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-18/SCOREBOARD.md b/challenge-18/SCOREBOARD.md index c7329b34..62d40b9e 100644 --- a/challenge-18/SCOREBOARD.md +++ b/challenge-18/SCOREBOARD.md @@ -30,6 +30,7 @@ | jordanhimawan | 23 | 23 | | kuzminprog | 23 | 23 | | lanmanul | 23 | 23 | +| longbui98 | 23 | 23 | | lyb88999 | 23 | 23 | | mayconvm | 23 | 23 | | mick4711 | 23 | 23 | From f83ba941ff77b2434a9d8101d8a3586be02b9648 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:09:21 +0000 Subject: [PATCH 34/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/longbui98.json | 2 +- badges/longbui98.svg | 4 ++-- badges/longbui98_badges.md | 6 +++--- badges/longbui98_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/longbui98.json b/badges/longbui98.json index 275283dd..d9ae943c 100644 --- a/badges/longbui98.json +++ b/badges/longbui98.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (5/30)", + "message": "\ud83c\udf31 Beginner (6/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/longbui98.svg b/badges/longbui98.svg index f2244649..83be711f 100644 --- a/badges/longbui98.svg +++ b/badges/longbui98.svg @@ -46,10 +46,10 @@ - + - 5/30 (16.7%) + 6/30 (20.0%) Ready for diff --git a/badges/longbui98_badges.md b/badges/longbui98_badges.md index e2cd5c5f..624a0faa 100644 --- a/badges/longbui98_badges.md +++ b/badges/longbui98_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/longbui98.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-5%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-6%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-16.7%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-20.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @longbui98 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 5/30 (16.7% complete) +**📊 Classic Challenges:** 6/30 (20.0% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/longbui98_compact.svg b/badges/longbui98_compact.svg index dd0ca779..beb271b7 100644 --- a/badges/longbui98_compact.svg +++ b/badges/longbui98_compact.svg @@ -33,10 +33,10 @@ - + - 5/30 (16.7%) + 6/30 (20.0%) 🌱 \ No newline at end of file From 6c793c111aae582b5034d3057f0ad1d6d8c4d96a Mon Sep 17 00:00:00 2001 From: Quang Long <39556130+longbui98@users.noreply.github.com> Date: Thu, 4 Sep 2025 12:10:03 +0700 Subject: [PATCH 35/58] Add solution for Challenge 19 by longbui98 (#341) --- .../longbui98/solution-template.go | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 challenge-19/submissions/longbui98/solution-template.go diff --git a/challenge-19/submissions/longbui98/solution-template.go b/challenge-19/submissions/longbui98/solution-template.go new file mode 100644 index 00000000..2e0b51aa --- /dev/null +++ b/challenge-19/submissions/longbui98/solution-template.go @@ -0,0 +1,76 @@ +package main + +import ( + "fmt" + "sort" +) + +func main() { + // Example slice for testing + numbers := []int{3, 1, 4, 1, 5, 9, 2, 6} + + // Test FindMax + max := FindMax(numbers) + fmt.Printf("Maximum value: %d\n", max) + + // Test RemoveDuplicates + unique := RemoveDuplicates(numbers) + fmt.Printf("After removing duplicates: %v\n", unique) + + // Test ReverseSlice + reversed := ReverseSlice(numbers) + fmt.Printf("Reversed: %v\n", reversed) + + // Test FilterEven + evenOnly := FilterEven(numbers) + fmt.Printf("Even numbers only: %v\n", evenOnly) +} + +// FindMax returns the maximum value in a slice of integers. +// If the slice is empty, it returns 0. +func FindMax(numbers []int) int { + // TODO: Implement this function + if len(numbers) == 0 { + return 0 + } + sort.Ints(numbers) + return numbers[len(numbers)-1] +} + +// RemoveDuplicates returns a new slice with duplicate values removed, +// preserving the original order of elements. +func RemoveDuplicates(numbers []int) []int { + // TODO: Implement this function + valueDupMap := make(map[int]int) + result := make([]int, 0, len(numbers)) + for _, num := range numbers { + if _, ok := valueDupMap[num]; !ok { + valueDupMap[num] = 1 + result = append(result, num) + } + } + return result +} + +// ReverseSlice returns a new slice with elements in reverse order. +func ReverseSlice(slice []int) []int { + // TODO: Implement this function + reverse := make([]int, 0, len(slice)) + for i := len(slice) - 1; i >= 0; i-- { + reverse = append(reverse, slice[i]) + } + return reverse +} + +// FilterEven returns a new slice containing only the even numbers +// from the original slice. +func FilterEven(numbers []int) []int { + // TODO: Implement this function + even := make([]int, 0, len(numbers)) + for _, n := range numbers { + if n%2 == 0 { + even = append(even, n) + } + } + return even +} From 0e25884dad8ae8fc25551ffb8ffe3714a5f8e2fc Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:10:32 +0000 Subject: [PATCH 36/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-19?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-19/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-19/SCOREBOARD.md b/challenge-19/SCOREBOARD.md index 47b63f00..d6424c76 100644 --- a/challenge-19/SCOREBOARD.md +++ b/challenge-19/SCOREBOARD.md @@ -13,6 +13,7 @@ | ashwinipatankar | 27 | 27 | | chenyao0910 | 27 | 27 | | lanmanul | 27 | 27 | +| longbui98 | 27 | 27 | | lyb88999 | 27 | 27 | | mick4711 | 27 | 27 | | odelbos | 27 | 27 | From fc3233ae3a6a1000a96aa3726251c738afd69137 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 05:10:58 +0000 Subject: [PATCH 37/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/longbui98.json | 2 +- badges/longbui98.svg | 4 ++-- badges/longbui98_badges.md | 6 +++--- badges/longbui98_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/longbui98.json b/badges/longbui98.json index d9ae943c..a985afb0 100644 --- a/badges/longbui98.json +++ b/badges/longbui98.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (6/30)", + "message": "\ud83c\udf31 Beginner (7/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/longbui98.svg b/badges/longbui98.svg index 83be711f..35ff5882 100644 --- a/badges/longbui98.svg +++ b/badges/longbui98.svg @@ -46,10 +46,10 @@ - + - 6/30 (20.0%) + 7/30 (23.3%) Ready for diff --git a/badges/longbui98_badges.md b/badges/longbui98_badges.md index 624a0faa..958125ae 100644 --- a/badges/longbui98_badges.md +++ b/badges/longbui98_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/longbui98.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-6%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-7%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-20.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-23.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @longbui98 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 6/30 (20.0% complete) +**📊 Classic Challenges:** 7/30 (23.3% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/longbui98_compact.svg b/badges/longbui98_compact.svg index beb271b7..abf573ac 100644 --- a/badges/longbui98_compact.svg +++ b/badges/longbui98_compact.svg @@ -33,10 +33,10 @@ - + - 6/30 (20.0%) + 7/30 (23.3%) 🌱 \ No newline at end of file From 4aef9af896e9f73b89f6b86a5b286e67f09cb51b Mon Sep 17 00:00:00 2001 From: Jan Vollmer Date: Thu, 4 Sep 2025 17:11:53 +0200 Subject: [PATCH 38/58] Add solution for Challenge 1 by jvllmr (#357) --- .../submissions/jvllmr/solution-template.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 challenge-1/submissions/jvllmr/solution-template.go diff --git a/challenge-1/submissions/jvllmr/solution-template.go b/challenge-1/submissions/jvllmr/solution-template.go new file mode 100644 index 00000000..aab16ac4 --- /dev/null +++ b/challenge-1/submissions/jvllmr/solution-template.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" +) + +func main() { + var a, b int + // Read two integers from standard input + _, err := fmt.Scanf("%d, %d", &a, &b) + if err != nil { + fmt.Println("Error reading input:", err) + return + } + + // Call the Sum function and print the result + result := Sum(a, b) + fmt.Println(result) +} + +// Sum returns the sum of a and b. +func Sum(a int, b int) int { + // TODO: Implement the function + return a+b +} From d469052d1a71150a41e8c946bdf14fd60a66b01b Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 15:12:52 +0000 Subject: [PATCH 39/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-1/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-1/SCOREBOARD.md b/challenge-1/SCOREBOARD.md index 6f0d1454..b257d440 100644 --- a/challenge-1/SCOREBOARD.md +++ b/challenge-1/SCOREBOARD.md @@ -64,6 +64,7 @@ | jin5335 | 6 | 6 | | joaovitoralvares | 6 | 6 | | jordanhimawan | 6 | 6 | +| jvllmr | 6 | 6 | | korranat9 | 6 | 6 | | krmaxwell | 6 | 6 | | kuzminprog | 6 | 6 | From a8bb00ce4402108a4fec1bc6d2709696e7601ed6 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 4 Sep 2025 15:13:14 +0000 Subject: [PATCH 40/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e57ef40..c2148771 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ Our most accomplished Go developers, ranked by number of challenges completed: ### Challenge Progress Overview - **Total Challenges Available**: 30 -- **Active Developers**: 113 +- **Active Developers**: 114 - **Most Challenges Solved**: 30 by odelbos From 824d84d8763c405dbac41092b3915eb978715270 Mon Sep 17 00:00:00 2001 From: FeatherZero Date: Fri, 5 Sep 2025 03:38:39 +0800 Subject: [PATCH 41/58] Add solution for Challenges by wxai2324 and add single-array comparison tests for FindInsertPosition (greater, smaller, equal) (#344) * Add solution for Challenge 2 by wxai2324 * Add solution for Challenge 1 by wxai2324 * Add solution for Challenge 3 by wxai2324 * Add solution for Challenge 4 by wxai2324 * Add solution for Challenge 18 by wxai2324 * Add solution for Challenge 21 by wxai2324 * Add solution for Challenge 2 by wxai2324 test: add single-array comparison tests for FindInsertPosition (greater, smaller, equal) --- .../submissions/wxai2324/solution-template.go | 24 ++++ .../submissions/wxai2324/solution-template.go | 38 ++++++ .../submissions/wxai2324/solution-template.go | 33 +++++ challenge-21/solution-template_test.go | 3 + .../submissions/wxai2324/solution-template.go | 115 ++++++++++++++++++ .../submissions/wxai2324/solution-template.go | 67 ++++++++++ .../submissions/wxai2324/solution-template.go | 84 +++++++++++++ 7 files changed, 364 insertions(+) create mode 100644 challenge-1/submissions/wxai2324/solution-template.go create mode 100644 challenge-18/submissions/wxai2324/solution-template.go create mode 100644 challenge-2/submissions/wxai2324/solution-template.go create mode 100644 challenge-21/submissions/wxai2324/solution-template.go create mode 100644 challenge-3/submissions/wxai2324/solution-template.go create mode 100644 challenge-4/submissions/wxai2324/solution-template.go diff --git a/challenge-1/submissions/wxai2324/solution-template.go b/challenge-1/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..479c1774 --- /dev/null +++ b/challenge-1/submissions/wxai2324/solution-template.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" +) + +func main() { + var a, b int + // Read two integers from standard input + _, err := fmt.Scanf("%d, %d", &a, &b) + if err != nil { + fmt.Println("Error reading input:", err) + return + } + + // Call the Sum function and print the result + result := Sum(a, b) + fmt.Println(result) +} + +// Sum returns the sum of a and b. +func Sum(a int, b int) int { + return a + b +} diff --git a/challenge-18/submissions/wxai2324/solution-template.go b/challenge-18/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..8939a81d --- /dev/null +++ b/challenge-18/submissions/wxai2324/solution-template.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + // Example usage + celsius := 25.0 + fahrenheit := CelsiusToFahrenheit(celsius) + fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit) + + fahrenheit = 68.0 + celsius = FahrenheitToCelsius(fahrenheit) + fmt.Printf("%.2f°F is equal to %.2f°C\n", fahrenheit, celsius) +} + +// CelsiusToFahrenheit converts a temperature from Celsius to Fahrenheit +// Formula: F = C × 9/5 + 32 +func CelsiusToFahrenheit(celsius float64) float64 { + + return Round(celsius*9.0/5.0+32.0, 2) +} + +// FahrenheitToCelsius converts a temperature from Fahrenheit to Celsius +// Formula: C = (F - 32) × 5/9 +func FahrenheitToCelsius(fahrenheit float64) float64 { + // TODO: Implement this function + // Remember to round to 2 decimal places + return Round((fahrenheit-32.0)*5.0/9.0, 2) +} + +// Round rounds a float64 value to the specified number of decimal places +func Round(value float64, decimals int) float64 { + precision := math.Pow10(decimals) + return math.Round(value*precision) / precision +} diff --git a/challenge-2/submissions/wxai2324/solution-template.go b/challenge-2/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..93249425 --- /dev/null +++ b/challenge-2/submissions/wxai2324/solution-template.go @@ -0,0 +1,33 @@ +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + // Read input from standard input + scanner := bufio.NewScanner(os.Stdin) + if scanner.Scan() { + input := scanner.Text() + + // Call the ReverseString function + output := ReverseString(input) + + // Print the result + fmt.Println(output) + } +} + +// ReverseString returns the reversed string of s. +func ReverseString(s string) string { + oldString := []rune(s) + newString := make([]rune, len(oldString)) + stringLen := len(oldString) + for i := 0; i < stringLen; i++ { + changI := stringLen - (i + 1) + newString[i] = oldString[changI] + } + return string(newString) +} diff --git a/challenge-21/solution-template_test.go b/challenge-21/solution-template_test.go index 0451ec9f..a8c0b473 100644 --- a/challenge-21/solution-template_test.go +++ b/challenge-21/solution-template_test.go @@ -77,6 +77,9 @@ func TestFindInsertPosition(t *testing.T) { expected int }{ {"Empty array", []int{}, 5, 0}, + {"Single element small", []int{5}, 3, 0}, + {"Single element bigger", []int{1}, 5, 1}, + {"Single element equal ", []int{1}, 1, 0}, {"Insert at beginning", []int{2, 4, 6, 8}, 1, 0}, {"Insert at end", []int{2, 4, 6, 8}, 10, 4}, {"Insert in middle", []int{2, 4, 6, 8}, 5, 2}, diff --git a/challenge-21/submissions/wxai2324/solution-template.go b/challenge-21/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..ad4fdd4d --- /dev/null +++ b/challenge-21/submissions/wxai2324/solution-template.go @@ -0,0 +1,115 @@ +package main + +import ( + "fmt" +) + +func main() { + // Example sorted array for testing + arr := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} + + // Test binary search + target := 7 + index := BinarySearch(arr, target) + fmt.Printf("BinarySearch: %d found at index %d\n", target, index) + + // Test recursive binary search + recursiveIndex := BinarySearchRecursive(arr, target, 0, len(arr)-1) + fmt.Printf("BinarySearchRecursive: %d found at index %d\n", target, recursiveIndex) + + // Test find insert position + insertTarget := 8 + insertPos := FindInsertPosition(arr, insertTarget) + fmt.Printf("FindInsertPosition: %d should be inserted at index %d\n", insertTarget, insertPos) +} + +// BinarySearch performs a standard binary search to find the target in the sorted array. +// Returns the index of the target if found, or -1 if not found. +func BinarySearch(arr []int, target int) int { + arrLen := len(arr) + if arrLen == 0 { + return -1 + } + if arrLen == 1 { + if target == arr[0] { + return 0 + } + return -1 + } + left := 0 + right := arrLen - 1 + for left <= right { + mid := left + (right-left)/2 + if mid >= arrLen { + return -1 + } + if target == arr[mid] { + return mid + } + if target < arr[mid] { + right = mid - 1 + } + if target > arr[mid] { + left = mid + 1 + } + } + return -1 +} + +// BinarySearchRecursive performs binary search using recursion. +// Returns the index of the target if found, or -1 if not found. +func BinarySearchRecursive(arr []int, target int, left int, right int) int { + arrLen := len(arr) + + if left > right || arrLen == 0 { + return -1 + } + if arrLen == 1 { + if target == arr[0] { + return 0 + } + return -1 + } + mid := left + (right-left)/2 + if left == right { + mid = right + } + if target == arr[mid] { + return mid + } + if target < arr[mid] { + return BinarySearchRecursive(arr, target, left, mid-1) + } + return BinarySearchRecursive(arr, target, mid+1, right) +} + +// FindInsertPosition returns the index where the target should be inserted +// to maintain the sorted order of the array. +func FindInsertPosition(arr []int, target int) int { + // 比left大 比right小 就行了 边界就是 比right还大了 + arrLen := len(arr) + if arrLen == 0 { + return 0 + } + if arrLen == 1 && target == arr[0] { + return 0 + } + left := 0 + right := arrLen - 1 + for left <= right { + mid := left + (right-left)/2 + if mid >= arrLen { + return mid + } + if target == arr[mid] { + return mid + } + if target < arr[mid] { + right = mid - 1 + } + if target > arr[mid] { + left = mid + 1 + } + } + return right + 1 +} diff --git a/challenge-3/submissions/wxai2324/solution-template.go b/challenge-3/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..a598292c --- /dev/null +++ b/challenge-3/submissions/wxai2324/solution-template.go @@ -0,0 +1,67 @@ +package main + +import "fmt" + +type Employee struct { + ID int + Name string + Age int + Salary float64 +} + +type Manager struct { + Employees []Employee +} + +// AddEmployee adds a new employee to the manager's list. +func (m *Manager) AddEmployee(e Employee) { + m.Employees = append(m.Employees, e) +} + +// RemoveEmployee removes an employee by ID from the manager's list. +func (m *Manager) RemoveEmployee(id int) { + for i, emp := range m.Employees { + if emp.ID == id { + m.Employees = append(m.Employees[:i], m.Employees[i+1:]...) + } + } +} + +// GetAverageSalary calculates the average salary of all employees. +func (m *Manager) GetAverageSalary() float64 { + if len(m.Employees) == 0 { + return 0 + } + salaries := float64(0) + for _, employee := range m.Employees { + salaries += employee.Salary + } + return salaries / float64(len(m.Employees)) +} + +// FindEmployeeByID finds and returns an employee by their ID. +func (m *Manager) FindEmployeeByID(id int) *Employee { + if len(m.Employees) == 0 { + return nil + } + for _, employee := range m.Employees { + if employee.ID == id { + return &employee + } + } + return nil +} + +func main() { + manager := Manager{} + manager.AddEmployee(Employee{ID: 1, Name: "Alice", Age: 30, Salary: 70000}) + manager.AddEmployee(Employee{ID: 2, Name: "Bob", Age: 25, Salary: 65000}) + manager.RemoveEmployee(1) + averageSalary := manager.GetAverageSalary() + employee := manager.FindEmployeeByID(2) + + fmt.Printf("Average Salary: %f\n", averageSalary) + if employee != nil { + fmt.Printf("Employee found: %+v\n", *employee) + } +} diff --git a/challenge-4/submissions/wxai2324/solution-template.go b/challenge-4/submissions/wxai2324/solution-template.go new file mode 100644 index 00000000..240a31bd --- /dev/null +++ b/challenge-4/submissions/wxai2324/solution-template.go @@ -0,0 +1,84 @@ +package main + +import ( + "fmt" +) + +// ConcurrentBFSQueries concurrently processes BFS queries on the provided graph. +// - graph: adjacency list, e.g., graph[u] = []int{v1, v2, ...} +// - queries: a list of starting nodes for BFS. +// - numWorkers: how many goroutines can process BFS queries simultaneously. +// +// Return a map from the query (starting node) to the BFS order as a slice of nodes. +// YOU MUST use concurrency (goroutines + channels) to pass the performance tests. + +type BFSResult struct { + StartNode int + Order []int +} + +func ConcurrentBFSQueries(graph map[int][]int, queries []int, numWorkers int) map[int][]int { + if numWorkers <= 0 { + return nil + } + jobs := make(chan int, len(queries)) + results := make(chan BFSResult, len(queries)) + // 创建任务 + for i := 0; i < numWorkers; i++ { + go worker(graph, jobs, results) + } + // 分发任务 + for _, query := range queries { + jobs <- query + } + close(jobs) + // 收集结果 + orderedResults := make(map[int][]int, len(queries)) + for range queries { + result := <-results + orderedResults[result.StartNode] = result.Order + } + return orderedResults +} + +func worker(graph map[int][]int, jobs <-chan int, results chan<- BFSResult) { + for start := range jobs { + order := query(graph, start) + results <- BFSResult{StartNode: start, Order: order} + } +} + +func query(graph map[int][]int, start int) []int { + queue := []int{start} + visited := make(map[int]bool) + var result []int + visited[start] = true + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + result = append(result, node) + for _, neighbor := range graph[node] { + if !visited[neighbor] { + visited[neighbor] = true + queue = append(queue, neighbor) + } + } + } + return result +} + +func main() { + graph := map[int][]int{ + 0: {1, 2}, + 1: {2, 3}, + 2: {3}, + 3: {4}, + 4: {}, + 5: {2}, + } + queries := []int{0, 1, 5} + numWorkers := 2 + + results := ConcurrentBFSQueries(graph, queries, numWorkers) + fmt.Println(results) +} From f121aae39541db1d9a19c3a0d9f39ad887cdf638 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 19:40:44 +0000 Subject: [PATCH 42/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-1=20challenge-18=20challenge-2=20challenge-21=20c?= =?UTF-8?q?hallenge-3=20challenge-4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-1/SCOREBOARD.md | 1 + challenge-18/SCOREBOARD.md | 1 + challenge-2/SCOREBOARD.md | 1 + challenge-21/SCOREBOARD.md | 57 +++++++++++++++++++------------------- challenge-3/SCOREBOARD.md | 1 + challenge-4/SCOREBOARD.md | 1 + 6 files changed, 34 insertions(+), 28 deletions(-) diff --git a/challenge-1/SCOREBOARD.md b/challenge-1/SCOREBOARD.md index b257d440..9f4ab015 100644 --- a/challenge-1/SCOREBOARD.md +++ b/challenge-1/SCOREBOARD.md @@ -96,5 +96,6 @@ | t4e1 | 6 | 6 | | timlkko | 6 | 6 | | tmsankaram | 6 | 6 | +| wxai2324 | 6 | 6 | | xavi5r | 6 | 6 | | y1hao | 6 | 6 | diff --git a/challenge-18/SCOREBOARD.md b/challenge-18/SCOREBOARD.md index 62d40b9e..ff1c2152 100644 --- a/challenge-18/SCOREBOARD.md +++ b/challenge-18/SCOREBOARD.md @@ -41,4 +41,5 @@ | t4e1 | 23 | 23 | | timlkko | 23 | 23 | | tmsankaram | 23 | 23 | +| wxai2324 | 23 | 23 | | y1hao | 23 | 23 | diff --git a/challenge-2/SCOREBOARD.md b/challenge-2/SCOREBOARD.md index ef5ca467..969330fa 100644 --- a/challenge-2/SCOREBOARD.md +++ b/challenge-2/SCOREBOARD.md @@ -76,4 +76,5 @@ | t4e1 | 7 | 7 | | timlkko | 7 | 7 | | tmsankaram | 7 | 7 | +| wxai2324 | 7 | 7 | | y1hao | 7 | 7 | diff --git a/challenge-21/SCOREBOARD.md b/challenge-21/SCOREBOARD.md index 744aa235..e68fa24d 100644 --- a/challenge-21/SCOREBOARD.md +++ b/challenge-21/SCOREBOARD.md @@ -1,31 +1,32 @@ # Scoreboard for challenge-21 | Username | Passed Tests | Total Tests | |------------|--------------|-------------| -| Gandook | 32 | 32 | -| GinVlad | 32 | 32 | -| IBraveMonkey | 32 | 32 | -| JackDalberg | 32 | 32 | -| JarhsonNing | 32 | 32 | -| JunLog | 32 | 32 | -| KhaledMosaad | 32 | 32 | -| MYK12397 | 32 | 32 | -| MuraliMohan-2000 | 32 | 32 | -| PolinaSvet | 32 | 32 | -| RezaSi | 32 | 32 | -| VFarsiyants | 32 | 32 | -| ZaharBorisenko | 32 | 32 | -| ashwinipatankar | 32 | 32 | -| binoymanoj | 32 | 32 | -| hodgechung | 32 | 32 | -| jordanhimawan | 32 | 32 | -| kuzminprog | 32 | 32 | -| lanmanul | 32 | 32 | -| liukw-go | 32 | 32 | -| lyb88999 | 32 | 32 | -| mick4711 | 32 | 32 | -| muhammedkucukaslan | 32 | 32 | -| odelbos | 32 | 32 | -| perekoshik | 32 | 32 | -| t4e1 | 32 | 32 | -| tmsankaram | 32 | 32 | -| y1hao | 32 | 32 | +| Gandook | 35 | 35 | +| GinVlad | 35 | 35 | +| IBraveMonkey | 35 | 35 | +| JackDalberg | 35 | 35 | +| JarhsonNing | 35 | 35 | +| JunLog | 35 | 35 | +| KhaledMosaad | 35 | 35 | +| MYK12397 | 35 | 35 | +| MuraliMohan-2000 | 35 | 35 | +| PolinaSvet | 35 | 35 | +| RezaSi | 35 | 35 | +| ZaharBorisenko | 35 | 35 | +| binoymanoj | 35 | 35 | +| hodgechung | 35 | 35 | +| jordanhimawan | 35 | 35 | +| kuzminprog | 35 | 35 | +| lanmanul | 35 | 35 | +| liukw-go | 35 | 35 | +| lyb88999 | 35 | 35 | +| mick4711 | 35 | 35 | +| muhammedkucukaslan | 35 | 35 | +| odelbos | 35 | 35 | +| perekoshik | 35 | 35 | +| t4e1 | 35 | 35 | +| tmsankaram | 35 | 35 | +| wxai2324 | 35 | 35 | +| y1hao | 35 | 35 | +| ashwinipatankar | 33 | 35 | +| VFarsiyants | 24 | 26 | diff --git a/challenge-3/SCOREBOARD.md b/challenge-3/SCOREBOARD.md index d3583185..8fa05ea0 100644 --- a/challenge-3/SCOREBOARD.md +++ b/challenge-3/SCOREBOARD.md @@ -55,4 +55,5 @@ | t4e1 | 5 | 5 | | timlkko | 5 | 5 | | tmsankaram | 5 | 5 | +| wxai2324 | 5 | 5 | | y1hao | 5 | 5 | diff --git a/challenge-4/SCOREBOARD.md b/challenge-4/SCOREBOARD.md index 2deea033..41320250 100644 --- a/challenge-4/SCOREBOARD.md +++ b/challenge-4/SCOREBOARD.md @@ -19,5 +19,6 @@ | mick4711 | 22 | 22 | | odelbos | 22 | 22 | | t4e1 | 22 | 22 | +| wxai2324 | 22 | 22 | | y1hao | 22 | 22 | | yz4230 | 22 | 22 | From e15e9d4685e39b96f808d3ae476203d4bc839bf1 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 4 Sep 2025 19:41:04 +0000 Subject: [PATCH 43/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c2148771..cbcef5c4 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Our most accomplished Go developers, ranked by number of challenges completed: | 4 |
**[Gandook](https://github.com/Gandook)** | **22**/30 | **73.3%** | Master | ✅✅✅✅✅✅✅✅✅✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅✅✅✅✅⬜⬜✅ | | 5 |
**[y1hao](https://github.com/y1hao)** | **21**/30 | **70.0%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
✅✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | | 6 |
**[JackDalberg](https://github.com/JackDalberg)** | **20**/30 | **66.7%** | Master | ✅✅✅✅✅✅✅✅⬜✅⬜⬜✅✅⬜
⬜✅✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅ | -| 7 |
**[ashwinipatankar](https://github.com/ashwinipatankar)** ❤️ | **18**/30 | **60.0%** | Expert | ✅✅✅⬜✅✅✅⬜✅✅⬜⬜✅✅⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜✅⬜⬜✅ | +| 7 |
**[ashwinipatankar](https://github.com/ashwinipatankar)** ❤️ | **17**/30 | **56.7%** | Expert | ✅✅✅⬜✅✅✅⬜✅✅⬜⬜✅✅⬜
⬜✅✅✅⬜⬜✅✅⬜⬜⬜✅⬜⬜✅ | | 8 |
**[t4e1](https://github.com/t4e1)** | **15**/30 | **50.0%** | Expert | ✅✅✅✅✅✅✅⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅⬜⬜⬜⬜✅⬜⬜⬜ | | 9 |
**[KhaledMosaad](https://github.com/KhaledMosaad)** | **14**/30 | **46.7%** | Advanced | ✅✅✅⬜⬜✅⬜⬜⬜⬜⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜✅✅⬜⬜✅ | | 10 |
**[RezaSi](https://github.com/RezaSi)** | **14**/30 | **46.7%** | Advanced | ✅✅✅✅✅✅⬜⬜⬜✅⬜⬜✅⬜⬜
⬜✅✅✅⬜✅✅✅⬜⬜⬜⬜⬜⬜⬜ | @@ -102,7 +102,7 @@ Our most accomplished Go developers, ranked by number of challenges completed: ### Challenge Progress Overview - **Total Challenges Available**: 30 -- **Active Developers**: 114 +- **Active Developers**: 115 - **Most Challenges Solved**: 30 by odelbos From 53f10f1ed0dd5b8d02ef76826d336356091179b1 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Thu, 4 Sep 2025 19:41:20 +0000 Subject: [PATCH 44/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/VFarsiyants.json | 2 +- badges/VFarsiyants.svg | 4 +-- badges/VFarsiyants_badges.md | 6 ++-- badges/VFarsiyants_compact.svg | 4 +-- badges/ashwinipatankar.json | 2 +- badges/ashwinipatankar.svg | 4 +-- badges/ashwinipatankar_badges.md | 6 ++-- badges/ashwinipatankar_compact.svg | 4 +-- badges/jvllmr.json | 7 ++++ badges/jvllmr.svg | 57 ++++++++++++++++++++++++++++++ badges/jvllmr_badges.md | 32 +++++++++++++++++ badges/jvllmr_compact.svg | 42 ++++++++++++++++++++++ badges/wxai2324.json | 7 ++++ badges/wxai2324.svg | 57 ++++++++++++++++++++++++++++++ badges/wxai2324_badges.md | 32 +++++++++++++++++ badges/wxai2324_compact.svg | 42 ++++++++++++++++++++++ 16 files changed, 292 insertions(+), 16 deletions(-) create mode 100644 badges/jvllmr.json create mode 100644 badges/jvllmr.svg create mode 100644 badges/jvllmr_badges.md create mode 100644 badges/jvllmr_compact.svg create mode 100644 badges/wxai2324.json create mode 100644 badges/wxai2324.svg create mode 100644 badges/wxai2324_badges.md create mode 100644 badges/wxai2324_compact.svg diff --git a/badges/VFarsiyants.json b/badges/VFarsiyants.json index 5df019ce..839b65e9 100644 --- a/badges/VFarsiyants.json +++ b/badges/VFarsiyants.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (9/30)", + "message": "\ud83c\udf31 Beginner (8/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/VFarsiyants.svg b/badges/VFarsiyants.svg index 954a541d..835e341b 100644 --- a/badges/VFarsiyants.svg +++ b/badges/VFarsiyants.svg @@ -46,10 +46,10 @@ - + - 9/30 (30.0%) + 8/30 (26.7%) Ready for diff --git a/badges/VFarsiyants_badges.md b/badges/VFarsiyants_badges.md index d93553f1..44f3bf5b 100644 --- a/badges/VFarsiyants_badges.md +++ b/badges/VFarsiyants_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/VFarsiyants.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-9%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-8%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-30.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-26.7%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @VFarsiyants **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 9/30 (30.0% complete) +**📊 Classic Challenges:** 8/30 (26.7% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/VFarsiyants_compact.svg b/badges/VFarsiyants_compact.svg index a723015a..a22e32b4 100644 --- a/badges/VFarsiyants_compact.svg +++ b/badges/VFarsiyants_compact.svg @@ -33,10 +33,10 @@ - + - 9/30 (30.0%) + 8/30 (26.7%) 🌱 \ No newline at end of file diff --git a/badges/ashwinipatankar.json b/badges/ashwinipatankar.json index 40203fba..c74b917c 100644 --- a/badges/ashwinipatankar.json +++ b/badges/ashwinipatankar.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udfaf Expert (18/30)", + "message": "\ud83c\udfaf Expert (17/30)", "color": "blue", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/ashwinipatankar.svg b/badges/ashwinipatankar.svg index 5fb9a985..16cd4f53 100644 --- a/badges/ashwinipatankar.svg +++ b/badges/ashwinipatankar.svg @@ -46,10 +46,10 @@ - + - 18/30 (60.0%) + 17/30 (56.7%) Package Challenges diff --git a/badges/ashwinipatankar_badges.md b/badges/ashwinipatankar_badges.md index 077f3555..0495cde3 100644 --- a/badges/ashwinipatankar_badges.md +++ b/badges/ashwinipatankar_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/ashwinipatankar.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-18%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-17%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🎯_Expert-blue?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-60.0%25-blue?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-56.7%25-blue?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Package Challenges](https://img.shields.io/badge/Package_Challenges-3_across_1_packages-purple?style=for-the-badge&logo=package&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,6 +28,6 @@ **👤 Username:** @ashwinipatankar **🏅 Achievement Level:** 🎯 **Expert Developer** -**📊 Classic Challenges:** 18/30 (60.0% complete) +**📊 Classic Challenges:** 17/30 (56.7% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) **Package Challenges:** 3 across 1 packages diff --git a/badges/ashwinipatankar_compact.svg b/badges/ashwinipatankar_compact.svg index f8d4106e..2803b2cc 100644 --- a/badges/ashwinipatankar_compact.svg +++ b/badges/ashwinipatankar_compact.svg @@ -33,10 +33,10 @@ - + - 18/30 (60.0%) + 17/30 (56.7%) 📦 3 package challenges 🎯 diff --git a/badges/jvllmr.json b/badges/jvllmr.json new file mode 100644 index 00000000..14b29c79 --- /dev/null +++ b/badges/jvllmr.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": 1, + "label": "Go Interview Practice", + "message": "\ud83c\udf31 Beginner (1/30)", + "color": "97ca00", + "style": "for-the-badge" +} \ No newline at end of file diff --git a/badges/jvllmr.svg b/badges/jvllmr.svg new file mode 100644 index 00000000..c8db6b3f --- /dev/null +++ b/badges/jvllmr.svg @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GO INTERVIEW PRACTICE + github.com/RezaSi/go-interview-practice + + + 🌱 + + + @jvllmr + 🌱 Beginner Developer + + + Classic Challenges + + + + + + + + 1/30 (3.3%) + + + Ready for + Package Challenges! + \ No newline at end of file diff --git a/badges/jvllmr_badges.md b/badges/jvllmr_badges.md new file mode 100644 index 00000000..72c3f481 --- /dev/null +++ b/badges/jvllmr_badges.md @@ -0,0 +1,32 @@ +## 🏆 Go Interview Practice Achievements + +### 🎨 Beautiful Custom Badges +*Click any badge to visit the Go Interview Practice repository!* + + +[![Go Interview Practice Achievement Card](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/jvllmr.svg)](https://github.com/RezaSi/go-interview-practice) + + +[![Go Interview Practice Compact](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/jvllmr_compact.svg)](https://github.com/RezaSi/go-interview-practice) + +### 🔄 Dynamic Shields.io Badge + +[![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/jvllmr.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +### 📊 Static Badges Collection +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-1%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-3.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + + +### 🔗 Repository Link Badge +[![Go Interview Practice Repository](https://img.shields.io/badge/View_Repository-Go_Interview_Practice-blue?style=for-the-badge&logo=github&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +--- + +### 📈 Your Achievement Summary + +**👤 Username:** @jvllmr +**🏅 Achievement Level:** 🌱 **Beginner Developer** +**📊 Classic Challenges:** 1/30 (3.3% complete) +**🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/jvllmr_compact.svg b/badges/jvllmr_compact.svg new file mode 100644 index 00000000..f9cad4ef --- /dev/null +++ b/badges/jvllmr_compact.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + 🐹 Go Interview Practice + + + @jvllmr + 🌱 Beginner Developer + + + Classic Progress + + + + + + + 1/30 (3.3%) + + 🌱 + \ No newline at end of file diff --git a/badges/wxai2324.json b/badges/wxai2324.json new file mode 100644 index 00000000..d9ae943c --- /dev/null +++ b/badges/wxai2324.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": 1, + "label": "Go Interview Practice", + "message": "\ud83c\udf31 Beginner (6/30)", + "color": "97ca00", + "style": "for-the-badge" +} \ No newline at end of file diff --git a/badges/wxai2324.svg b/badges/wxai2324.svg new file mode 100644 index 00000000..023bc042 --- /dev/null +++ b/badges/wxai2324.svg @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GO INTERVIEW PRACTICE + github.com/RezaSi/go-interview-practice + + + 🌱 + + + @wxai2324 + 🌱 Beginner Developer + + + Classic Challenges + + + + + + + + 6/30 (20.0%) + + + Ready for + Package Challenges! + \ No newline at end of file diff --git a/badges/wxai2324_badges.md b/badges/wxai2324_badges.md new file mode 100644 index 00000000..d16fd353 --- /dev/null +++ b/badges/wxai2324_badges.md @@ -0,0 +1,32 @@ +## 🏆 Go Interview Practice Achievements + +### 🎨 Beautiful Custom Badges +*Click any badge to visit the Go Interview Practice repository!* + + +[![Go Interview Practice Achievement Card](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/wxai2324.svg)](https://github.com/RezaSi/go-interview-practice) + + +[![Go Interview Practice Compact](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/wxai2324_compact.svg)](https://github.com/RezaSi/go-interview-practice) + +### 🔄 Dynamic Shields.io Badge + +[![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/wxai2324.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +### 📊 Static Badges Collection +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-6%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-20.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + + +### 🔗 Repository Link Badge +[![Go Interview Practice Repository](https://img.shields.io/badge/View_Repository-Go_Interview_Practice-blue?style=for-the-badge&logo=github&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +--- + +### 📈 Your Achievement Summary + +**👤 Username:** @wxai2324 +**🏅 Achievement Level:** 🌱 **Beginner Developer** +**📊 Classic Challenges:** 6/30 (20.0% complete) +**🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/wxai2324_compact.svg b/badges/wxai2324_compact.svg new file mode 100644 index 00000000..ffc66aa0 --- /dev/null +++ b/badges/wxai2324_compact.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + 🐹 Go Interview Practice + + + @wxai2324 + 🌱 Beginner Developer + + + Classic Progress + + + + + + + 6/30 (20.0%) + + 🌱 + \ No newline at end of file From e63446523e15e757df59d4341ee13b9c3a0e70a8 Mon Sep 17 00:00:00 2001 From: RezaSi Date: Thu, 4 Sep 2025 16:08:21 -0600 Subject: [PATCH 45/58] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index cbcef5c4..299cd948 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,14 @@ Welcome to the **Go Interview Practice** repository! Master Go programming and ace your technical interviews with our interactive coding challenges. +Our interactive platform is now live at **[gointerview.dev](https://gointerview.dev/)** 🎉 Explore challenges, track your progress, and elevate your Go skills with AI-powered mentorship. + + + --- ## Visual Overview From 04f0a083928fe7c627523dd745355899ce1156da Mon Sep 17 00:00:00 2001 From: Lahiru Malaka Gunawardhana Date: Fri, 5 Sep 2025 11:20:18 +1000 Subject: [PATCH 46/58] Add solution for Challenge 1 by malakagl (#358) --- .../submissions/malakagl/solution-template.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 challenge-1/submissions/malakagl/solution-template.go diff --git a/challenge-1/submissions/malakagl/solution-template.go b/challenge-1/submissions/malakagl/solution-template.go new file mode 100644 index 00000000..0a3c61d6 --- /dev/null +++ b/challenge-1/submissions/malakagl/solution-template.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" +) + +func main() { + var a, b int + // Read two integers from standard input + _, err := fmt.Scanf("%d, %d", &a, &b) + if err != nil { + fmt.Println("Error reading input:", err) + return + } + + // Call the Sum function and print the result + result := Sum(a, b) + fmt.Println(result) +} + +// Sum returns the sum of a and b. +func Sum(a int, b int) int { + return a+b +} From 96f2eb51340d486371586bea57db6d49d7ed3f79 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Fri, 5 Sep 2025 01:21:17 +0000 Subject: [PATCH 47/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-1/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-1/SCOREBOARD.md b/challenge-1/SCOREBOARD.md index 9f4ab015..a5dae651 100644 --- a/challenge-1/SCOREBOARD.md +++ b/challenge-1/SCOREBOARD.md @@ -72,6 +72,7 @@ | lanmanul | 6 | 6 | | levwap | 6 | 6 | | lyb88999 | 6 | 6 | +| malakagl | 6 | 6 | | mayconvm | 6 | 6 | | mick4711 | 6 | 6 | | mks-nerd | 6 | 6 | From db6ac3c1e00ea29eee9c71363db907b9ca884b7e Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 5 Sep 2025 01:21:35 +0000 Subject: [PATCH 48/58] Auto-update main scoreboard - Updated leaderboard rankings - Refreshed completion statistics - Synchronized with latest challenge scoreboards --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 299cd948..5d8a6751 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Our most accomplished Go developers, ranked by number of challenges completed: ### Challenge Progress Overview - **Total Challenges Available**: 30 -- **Active Developers**: 115 +- **Active Developers**: 116 - **Most Challenges Solved**: 30 by odelbos From 32e3dd9a683d29e604d8e1622315ece68f0228e8 Mon Sep 17 00:00:00 2001 From: Kerimberdi Saparow Date: Sun, 7 Sep 2025 05:36:41 +0500 Subject: [PATCH 49/58] Add solution for Challenges by Kesha005 (#345) * Add solution for Challenge 2 by Kesha005 * Add solution for Challenge 18 by Kesha005 * Add solution for Challenge 1 by Kesha005 --- .../submissions/Kesha005/solution-template.go | 25 +++++++++++ .../submissions/Kesha005/solution-template.go | 41 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 challenge-1/submissions/Kesha005/solution-template.go create mode 100644 challenge-18/submissions/Kesha005/solution-template.go diff --git a/challenge-1/submissions/Kesha005/solution-template.go b/challenge-1/submissions/Kesha005/solution-template.go new file mode 100644 index 00000000..b34fe408 --- /dev/null +++ b/challenge-1/submissions/Kesha005/solution-template.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" +) + +func main() { + var a, b int + // Read two integers from standard input + _, err := fmt.Scanf("%d, %d", &a, &b) + if err != nil { + fmt.Println("Error reading input:", err) + return + } + + // Call the Sum function and print the result + result := Sum(a, b) + fmt.Println(result) +} + +// Sum returns the sum of a and b. +func Sum(a int, b int) int { + + return a +b +} diff --git a/challenge-18/submissions/Kesha005/solution-template.go b/challenge-18/submissions/Kesha005/solution-template.go new file mode 100644 index 00000000..2e53a4ee --- /dev/null +++ b/challenge-18/submissions/Kesha005/solution-template.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + // Example usage + celsius := 25.0 + fahrenheit := CelsiusToFahrenheit(celsius) + fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit) + + fahrenheit = 68.0 + celsius = FahrenheitToCelsius(fahrenheit) + fmt.Printf("%.2f°F is equal to %.2f°C\n", fahrenheit, celsius) +} + +// CelsiusToFahrenheit converts a temperature from Celsius to Fahrenheit +// Formula: F = C × 9/5 + 32 +func CelsiusToFahrenheit(celsius float64) float64 { + // TODO: Implement this function + // Remember to round to 2 decimal places + f := celsius *9/5+32 + + return Round(f,2) +} + +// FahrenheitToCelsius converts a temperature from Fahrenheit to Celsius +// Formula: C = (F - 32) × 5/9 +func FahrenheitToCelsius(fahrenheit float64) float64 { + c := (fahrenheit-32)*5/9 + + return Round(c,2) +} + +// Round rounds a float64 value to the specified number of decimal places +func Round(value float64, decimals int) float64 { + precision := math.Pow10(decimals) + return math.Round(value*precision) / precision +} From 8fa331ba009a099cecbb74001f4adfced9c06868 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:37:48 +0000 Subject: [PATCH 50/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-1=20challenge-18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-1/SCOREBOARD.md | 1 + challenge-18/SCOREBOARD.md | 1 + 2 files changed, 2 insertions(+) diff --git a/challenge-1/SCOREBOARD.md b/challenge-1/SCOREBOARD.md index a5dae651..43ee7918 100644 --- a/challenge-1/SCOREBOARD.md +++ b/challenge-1/SCOREBOARD.md @@ -17,6 +17,7 @@ | JunLog | 6 | 6 | | K1tten2005 | 6 | 6 | | KaiserKun | 6 | 6 | +| Kesha005 | 6 | 6 | | KhaledMosaad | 6 | 6 | | KirthiInfra | 6 | 6 | | Linqi-Qin | 6 | 6 | diff --git a/challenge-18/SCOREBOARD.md b/challenge-18/SCOREBOARD.md index ff1c2152..83321b34 100644 --- a/challenge-18/SCOREBOARD.md +++ b/challenge-18/SCOREBOARD.md @@ -7,6 +7,7 @@ | JackDalberg | 23 | 23 | | JarhsonNing | 23 | 23 | | JunLog | 23 | 23 | +| Kesha005 | 23 | 23 | | KhaledMosaad | 23 | 23 | | MYK12397 | 23 | 23 | | MuraliMohan-2000 | 23 | 23 | From ea667888e1a97249f067ab85ac767aa4fb91de3b Mon Sep 17 00:00:00 2001 From: Quang Long <39556130+longbui98@users.noreply.github.com> Date: Sun, 7 Sep 2025 07:37:59 +0700 Subject: [PATCH 51/58] Add solution for Challenge 21 by longbui98 (#346) --- .../longbui98/solution-template.go | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 challenge-21/submissions/longbui98/solution-template.go diff --git a/challenge-21/submissions/longbui98/solution-template.go b/challenge-21/submissions/longbui98/solution-template.go new file mode 100644 index 00000000..474dcd52 --- /dev/null +++ b/challenge-21/submissions/longbui98/solution-template.go @@ -0,0 +1,80 @@ +package main + +import ( + "fmt" +) + +func main() { + // Example sorted array for testing + arr := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} + + // Test binary search + target := 7 + index := BinarySearch(arr, target) + fmt.Printf("BinarySearch: %d found at index %d\n", target, index) + + // Test recursive binary search + recursiveIndex := BinarySearchRecursive(arr, target, 0, len(arr)-1) + fmt.Printf("BinarySearchRecursive: %d found at index %d\n", target, recursiveIndex) + + // Test find insert position + insertTarget := 8 + insertPos := FindInsertPosition(arr, insertTarget) + fmt.Printf("FindInsertPosition: %d should be inserted at index %d\n", insertTarget, insertPos) +} + +// BinarySearch performs a standard binary search to find the target in the sorted array. +// Returns the index of the target if found, or -1 if not found. +func BinarySearch(arr []int, target int) int { + // TODO: Implement this function + lenArr := len(arr) - 1 + start, end := 0, lenArr + for start <= end { + mid := (start + end) / 2 + if arr[mid] == target { + return mid + } else if arr[mid] > target { + end = end - 1 + } else { + start = start + 1 + } + } + return -1 +} + +// BinarySearchRecursive performs binary search using recursion. +// Returns the index of the target if found, or -1 if not found. +func BinarySearchRecursive(arr []int, target int, left int, right int) int { + // TODO: Implement this function + if left > right { + return -1 + } + mid := (left + right) / 2 + if arr[mid] == target { + return mid + } else if arr[mid] > target { + return BinarySearchRecursive(arr, target, left, right-1) + } + return BinarySearchRecursive(arr, target, left+1, right) + +} + +// FindInsertPosition returns the index where the target should be inserted +// to maintain the sorted order of the array. +func FindInsertPosition(arr []int, target int) int { + // TODO: Implement this function + for i := 0; i < len(arr); i++ { + if (i == 0 && target <= arr[i]) || target == arr[i] { + return i + } + if i == len(arr)-1 && target > arr[i] { + return i + 1 + } + if i < len(arr)-1 { + if target > arr[i] && target < arr[i+1] { + return i + 1 + } + } + } + return 0 +} From 20130cb21ee036f86bbcd14bfd1630a84c362246 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:38:18 +0000 Subject: [PATCH 52/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/Kesha005.json | 2 +- badges/Kesha005.svg | 4 +-- badges/Kesha005_badges.md | 6 ++-- badges/Kesha005_compact.svg | 4 +-- badges/malakagl.json | 7 +++++ badges/malakagl.svg | 57 +++++++++++++++++++++++++++++++++++++ badges/malakagl_badges.md | 32 +++++++++++++++++++++ badges/malakagl_compact.svg | 42 +++++++++++++++++++++++++++ 8 files changed, 146 insertions(+), 8 deletions(-) create mode 100644 badges/malakagl.json create mode 100644 badges/malakagl.svg create mode 100644 badges/malakagl_badges.md create mode 100644 badges/malakagl_compact.svg diff --git a/badges/Kesha005.json b/badges/Kesha005.json index 14b29c79..0fbd6969 100644 --- a/badges/Kesha005.json +++ b/badges/Kesha005.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (1/30)", + "message": "\ud83c\udf31 Beginner (3/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/Kesha005.svg b/badges/Kesha005.svg index ce258a74..95aca2dc 100644 --- a/badges/Kesha005.svg +++ b/badges/Kesha005.svg @@ -46,10 +46,10 @@ - + - 1/30 (3.3%) + 3/30 (10.0%) Ready for diff --git a/badges/Kesha005_badges.md b/badges/Kesha005_badges.md index f577e38c..e1ab3c65 100644 --- a/badges/Kesha005_badges.md +++ b/badges/Kesha005_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/Kesha005.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-1%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-3%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-3.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-10.0%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @Kesha005 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 1/30 (3.3% complete) +**📊 Classic Challenges:** 3/30 (10.0% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/Kesha005_compact.svg b/badges/Kesha005_compact.svg index 50ba7f7a..fa6e6df6 100644 --- a/badges/Kesha005_compact.svg +++ b/badges/Kesha005_compact.svg @@ -33,10 +33,10 @@ - + - 1/30 (3.3%) + 3/30 (10.0%) 🌱 \ No newline at end of file diff --git a/badges/malakagl.json b/badges/malakagl.json new file mode 100644 index 00000000..14b29c79 --- /dev/null +++ b/badges/malakagl.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": 1, + "label": "Go Interview Practice", + "message": "\ud83c\udf31 Beginner (1/30)", + "color": "97ca00", + "style": "for-the-badge" +} \ No newline at end of file diff --git a/badges/malakagl.svg b/badges/malakagl.svg new file mode 100644 index 00000000..ba18a803 --- /dev/null +++ b/badges/malakagl.svg @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GO INTERVIEW PRACTICE + github.com/RezaSi/go-interview-practice + + + 🌱 + + + @malakagl + 🌱 Beginner Developer + + + Classic Challenges + + + + + + + + 1/30 (3.3%) + + + Ready for + Package Challenges! + \ No newline at end of file diff --git a/badges/malakagl_badges.md b/badges/malakagl_badges.md new file mode 100644 index 00000000..276e9124 --- /dev/null +++ b/badges/malakagl_badges.md @@ -0,0 +1,32 @@ +## 🏆 Go Interview Practice Achievements + +### 🎨 Beautiful Custom Badges +*Click any badge to visit the Go Interview Practice repository!* + + +[![Go Interview Practice Achievement Card](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/malakagl.svg)](https://github.com/RezaSi/go-interview-practice) + + +[![Go Interview Practice Compact](https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/malakagl_compact.svg)](https://github.com/RezaSi/go-interview-practice) + +### 🔄 Dynamic Shields.io Badge + +[![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/malakagl.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +### 📊 Static Badges Collection +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-1%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-3.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + + +### 🔗 Repository Link Badge +[![Go Interview Practice Repository](https://img.shields.io/badge/View_Repository-Go_Interview_Practice-blue?style=for-the-badge&logo=github&logoColor=white)](https://github.com/RezaSi/go-interview-practice) + +--- + +### 📈 Your Achievement Summary + +**👤 Username:** @malakagl +**🏅 Achievement Level:** 🌱 **Beginner Developer** +**📊 Classic Challenges:** 1/30 (3.3% complete) +**🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/malakagl_compact.svg b/badges/malakagl_compact.svg new file mode 100644 index 00000000..04a02849 --- /dev/null +++ b/badges/malakagl_compact.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + 🐹 Go Interview Practice + + + @malakagl + 🌱 Beginner Developer + + + Classic Progress + + + + + + + 1/30 (3.3%) + + 🌱 + \ No newline at end of file From dbde3f0c862a51d696476db8e03743054e0c9ae2 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:38:29 +0000 Subject: [PATCH 53/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-21?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-21/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-21/SCOREBOARD.md b/challenge-21/SCOREBOARD.md index e68fa24d..ad1e3753 100644 --- a/challenge-21/SCOREBOARD.md +++ b/challenge-21/SCOREBOARD.md @@ -19,6 +19,7 @@ | kuzminprog | 35 | 35 | | lanmanul | 35 | 35 | | liukw-go | 35 | 35 | +| longbui98 | 35 | 35 | | lyb88999 | 35 | 35 | | mick4711 | 35 | 35 | | muhammedkucukaslan | 35 | 35 | From f8cd427e6b8f4267ee69a38c6098ebf0d233d043 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:38:54 +0000 Subject: [PATCH 54/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/longbui98.json | 2 +- badges/longbui98.svg | 4 ++-- badges/longbui98_badges.md | 6 +++--- badges/longbui98_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/longbui98.json b/badges/longbui98.json index a985afb0..839b65e9 100644 --- a/badges/longbui98.json +++ b/badges/longbui98.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\ud83c\udf31 Beginner (7/30)", + "message": "\ud83c\udf31 Beginner (8/30)", "color": "97ca00", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/longbui98.svg b/badges/longbui98.svg index 35ff5882..cae25b16 100644 --- a/badges/longbui98.svg +++ b/badges/longbui98.svg @@ -46,10 +46,10 @@ - + - 7/30 (23.3%) + 8/30 (26.7%) Ready for diff --git a/badges/longbui98_badges.md b/badges/longbui98_badges.md index 958125ae..6d13e9b2 100644 --- a/badges/longbui98_badges.md +++ b/badges/longbui98_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/longbui98.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-7%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-8%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-🌱_Beginner-97ca00?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-23.3%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-26.7%25-97ca00?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @longbui98 **🏅 Achievement Level:** 🌱 **Beginner Developer** -**📊 Classic Challenges:** 7/30 (23.3% complete) +**📊 Classic Challenges:** 8/30 (26.7% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/longbui98_compact.svg b/badges/longbui98_compact.svg index abf573ac..c73e71a9 100644 --- a/badges/longbui98_compact.svg +++ b/badges/longbui98_compact.svg @@ -33,10 +33,10 @@ - + - 7/30 (23.3%) + 8/30 (26.7%) 🌱 \ No newline at end of file From 0968c1c6e81453b69a8463e8e5847a0dd8a9fb3f Mon Sep 17 00:00:00 2001 From: Ted Lee <118622427+Cpoing@users.noreply.github.com> Date: Sat, 6 Sep 2025 20:41:29 -0400 Subject: [PATCH 55/58] Add solution for Challenge 13 by Cpoing (#347) --- .../submissions/Cpoing/solution-template.go | 213 ++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 challenge-13/submissions/Cpoing/solution-template.go diff --git a/challenge-13/submissions/Cpoing/solution-template.go b/challenge-13/submissions/Cpoing/solution-template.go new file mode 100644 index 00000000..5c7f7d80 --- /dev/null +++ b/challenge-13/submissions/Cpoing/solution-template.go @@ -0,0 +1,213 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "github.com/mattn/go-sqlite3" +) + +// Product represents a product in the inventory system +type Product struct { + ID int64 + Name string + Price float64 + Quantity int + Category string +} + +// ProductStore manages product operations +type ProductStore struct { + db *sql.DB +} + +// NewProductStore creates a new ProductStore with the given database connection +func NewProductStore(db *sql.DB) *ProductStore { + return &ProductStore{db: db} +} + +// InitDB sets up a new SQLite database and creates the products table +func InitDB(dbPath string) (*sql.DB, error) { + // TODO: Open a SQLite database connection + // TODO: Create the products table if it doesn't exist + // The table should have columns: id, name, price, quantity, category + db, err := sql.Open("sqlite3", dbPath) + if err != nil { + return nil, err + } + + _, err = db.Exec(`CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL, quantity INTEGER DEFAULT 0, category TEXT NOT NULL);`) + if err != nil { + return nil, err + } + + return db, nil +} + +// CreateProduct adds a new product to the database +func (ps *ProductStore) CreateProduct(product *Product) error { + // TODO: Insert the product into the database + // TODO: Update the product.ID with the database-generated ID + result, err := ps.db.Exec( + `INSERT INTO products (name, price, quantity, category) VALUES (?, ?, ?, ?)`, + product.Name, product.Price, product.Quantity, product.Category, + ) + if err != nil { + return err + } + + id, err := result.LastInsertId() + if err != nil { + return err + } + + product.ID = id + return nil +} + +// GetProduct retrieves a product by ID +func (ps *ProductStore) GetProduct(id int64) (*Product, error) { + // TODO: Query the database for a product with the given ID + // TODO: Return a Product struct populated with the data or an error if not found + query := `SELECT id, name, price, quantity, category FROM products where id = ?` + + product := &Product{} + err := ps.db.QueryRow(query, id).Scan(&product.ID, &product.Name, &product.Price, &product.Quantity, &product.Category) + if err != nil { + return nil, err + } + + return product, nil +} + +// UpdateProduct updates an existing product +func (ps *ProductStore) UpdateProduct(product *Product) error { + // TODO: Update the product in the database + // TODO: Return an error if the product doesn't exist + _, err := ps.GetProduct(product.ID) + if err != nil { + return err + } + + query := `UPDATE products SET name = ?, price = ?, quantity = ?, category = ? where id = ?` + + result, err := ps.db.Exec(query, product.Name, product.Price, product.Quantity, product.Category, product.ID) + if err != nil { + return err + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return err + } + + if rowsAffected == 0 { + return fmt.Errorf("no rows were updated") + } + + return nil +} + +// DeleteProduct removes a product by ID +func (ps *ProductStore) DeleteProduct(id int64) error { + // TODO: Delete the product from the database + // TODO: Return an error if the product doesn't exist + query := `DELETE FROM products WHERE id = ?` + + result, err := ps.db.Exec(query, id) + if err != nil { + return err + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return err + } + + if rowsAffected == 0 { + return fmt.Errorf("no rows were affected") + } + + return nil +} + +// ListProducts returns all products with optional filtering by category +func (ps *ProductStore) ListProducts(category string) ([]*Product, error) { + // TODO: Query the database for products + // TODO: If category is not empty, filter by category + // TODO: Return a slice of Product pointers + query := `SELECT id, name, price, quantity, category FROM products` + if category != "" { + query += ` WHERE category = ?` + } + rows, err := ps.db.Query(query, category) + if err != nil { + return nil, err + } + defer rows.Close() + + var products []*Product + for rows.Next() { + p := &Product{} + err := rows.Scan(&p.ID, &p.Name, &p.Price, &p.Quantity, &p.Category) + if err != nil { + return nil, err + } + products = append(products, p) + } + + if err = rows.Err(); err != nil { + return nil, err + } + + return products, nil +} + +// BatchUpdateInventory updates the quantity of multiple products in a single transaction +func (ps *ProductStore) BatchUpdateInventory(updates map[int64]int) error { + // TODO: Start a transaction + // TODO: For each product ID in the updates map, update its quantity + // TODO: If any update fails, roll back the transaction + // TODO: Otherwise, commit the transaction + tx, err := ps.db.Begin() + if err != nil { + return err + } + + defer func() { + if r := recover(); r != nil { + tx.Rollback() + panic(r) + } + }() + + query := `UPDATE products SET quantity = ? WHERE id = ?` + stmt, err := tx.Prepare(query) + if err != nil { + tx.Rollback() + return err + } + defer stmt.Close() + + for id, quantity := range updates { + _, err := ps.GetProduct(id) + if err != nil { + return err + } + _, err = stmt.Exec(quantity, id) + if err != nil { + tx.Rollback() + return err + } + } + + if err := tx.Commit(); err != nil { + return err + } + + return nil +} + +func main() { + // Optional: you can write code here to test your implementation +} From cdc5700eba88fcb0ab6f859033c3cfa01fd08a9e Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:42:49 +0000 Subject: [PATCH 56/58] =?UTF-8?q?=F0=9F=93=8A=20Update=20scoreboards=20for?= =?UTF-8?q?:=20challenge-13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated test results for modified submissions - Refreshed completion statistics --- challenge-13/SCOREBOARD.md | 1 + 1 file changed, 1 insertion(+) diff --git a/challenge-13/SCOREBOARD.md b/challenge-13/SCOREBOARD.md index e638e738..bfb04033 100644 --- a/challenge-13/SCOREBOARD.md +++ b/challenge-13/SCOREBOARD.md @@ -1,6 +1,7 @@ # Scoreboard for challenge-13 | Username | Passed Tests | Total Tests | |------------|--------------|-------------| +| Cpoing | 15 | 15 | | Gandook | 15 | 15 | | JackDalberg | 15 | 15 | | KhaledMosaad | 15 | 15 | From 8d18b350ac5e0e1e675557472433b4c41f7c4b28 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sun, 7 Sep 2025 00:43:21 +0000 Subject: [PATCH 57/58] =?UTF-8?q?=F0=9F=8F=86=20Auto-update:=20Profile=20b?= =?UTF-8?q?adges=20regenerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Regenerated contributor profile badges from current scoreboards - Updated badge files: *.svg, *.json, *_badges.md - Auto-generated by GitHub Actions --- badges/Cpoing.json | 2 +- badges/Cpoing.svg | 4 ++-- badges/Cpoing_badges.md | 6 +++--- badges/Cpoing_compact.svg | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/badges/Cpoing.json b/badges/Cpoing.json index ae03dc38..c5f19eda 100644 --- a/badges/Cpoing.json +++ b/badges/Cpoing.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "label": "Go Interview Practice", - "message": "\u26a1 Advanced (11/30)", + "message": "\u26a1 Advanced (12/30)", "color": "orange", "style": "for-the-badge" } \ No newline at end of file diff --git a/badges/Cpoing.svg b/badges/Cpoing.svg index 164f66db..2dd43b5a 100644 --- a/badges/Cpoing.svg +++ b/badges/Cpoing.svg @@ -46,10 +46,10 @@ - + - 11/30 (36.7%) + 12/30 (40.0%) Ready for diff --git a/badges/Cpoing_badges.md b/badges/Cpoing_badges.md index e3f388e2..229fe65a 100644 --- a/badges/Cpoing_badges.md +++ b/badges/Cpoing_badges.md @@ -14,9 +14,9 @@ [![Go Interview Practice](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/RezaSi/go-interview-practice/main/badges/Cpoing.json&style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 📊 Static Badges Collection -[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-11%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Challenges Solved](https://img.shields.io/badge/Go_Challenges-12%2F30-brightgreen?style=for-the-badge&logo=go&logoColor=white)](https://github.com/RezaSi/go-interview-practice) [![Achievement Level](https://img.shields.io/badge/Level-⚡_Advanced-orange?style=for-the-badge&logo=trophy&logoColor=white)](https://github.com/RezaSi/go-interview-practice) -[![Completion Rate](https://img.shields.io/badge/Completion-36.7%25-orange?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) +[![Completion Rate](https://img.shields.io/badge/Completion-40.0%25-orange?style=for-the-badge&logo=checkmarx&logoColor=white)](https://github.com/RezaSi/go-interview-practice) ### 🔗 Repository Link Badge @@ -28,5 +28,5 @@ **👤 Username:** @Cpoing **🏅 Achievement Level:** ⚡ **Advanced Developer** -**📊 Classic Challenges:** 11/30 (36.7% complete) +**📊 Classic Challenges:** 12/30 (40.0% complete) **🔗 Repository:** [Go Interview Practice](https://github.com/RezaSi/go-interview-practice) diff --git a/badges/Cpoing_compact.svg b/badges/Cpoing_compact.svg index f54a4dca..d56f381a 100644 --- a/badges/Cpoing_compact.svg +++ b/badges/Cpoing_compact.svg @@ -33,10 +33,10 @@ - + - 11/30 (36.7%) + 12/30 (40.0%) \ No newline at end of file From 563d9424b8643ec3709678c9007b8fd6c48f058e Mon Sep 17 00:00:00 2001 From: t4e1 Date: Sun, 7 Sep 2025 23:54:35 +0900 Subject: [PATCH 58/58] Add solution for Challenge 30 by t4e1 --- .../submissions/t4e1/solution-template.go | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 challenge-30/submissions/t4e1/solution-template.go diff --git a/challenge-30/submissions/t4e1/solution-template.go b/challenge-30/submissions/t4e1/solution-template.go new file mode 100644 index 00000000..869a1bfc --- /dev/null +++ b/challenge-30/submissions/t4e1/solution-template.go @@ -0,0 +1,161 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +// ContextManager defines a simplified interface for basic context operations +type ContextManager interface { + // Create a cancellable context from a parent context + CreateCancellableContext(parent context.Context) (context.Context, context.CancelFunc) + + // Create a context with timeout + CreateTimeoutContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) + + // Add a value to context + AddValue(parent context.Context, key, value interface{}) context.Context + + // Get a value from context + GetValue(ctx context.Context, key interface{}) (interface{}, bool) + + // Execute a task with context cancellation support + ExecuteWithContext(ctx context.Context, task func() error) error + + // Wait for context cancellation or completion + WaitForCompletion(ctx context.Context, duration time.Duration) error +} + +// Simple context manager implementation +type simpleContextManager struct{} + +// NewContextManager creates a new context manager +func NewContextManager() ContextManager { + return &simpleContextManager{} +} + +// CreateCancellableContext creates a cancellable context +func (cm *simpleContextManager) CreateCancellableContext(parent context.Context) (context.Context, context.CancelFunc) { + // TODO: Implement cancellable context creation + // Hint: Use context.WithCancel(parent) + ctx, cancel := context.WithCancel(parent) + return ctx, cancel +} + +// CreateTimeoutContext creates a context with timeout +func (cm *simpleContextManager) CreateTimeoutContext(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) { + // TODO: Implement timeout context creation + // Hint: Use context.WithTimeout(parent, timeout) + ctx, cancel := context.WithTimeout(parent, timeout) + return ctx, cancel +} + +// AddValue adds a key-value pair to the context +func (cm *simpleContextManager) AddValue(parent context.Context, key, value interface{}) context.Context { + // TODO: Implement value context creation + // Hint: Use context.WithValue(parent, key, value) + ctx := context.WithValue(parent, key, value) + return ctx +} + +// GetValue retrieves a value from the context +func (cm *simpleContextManager) GetValue(ctx context.Context, key interface{}) (interface{}, bool) { + // TODO: Implement value retrieval from context + // Hint: Use ctx.Value(key) and check if it's nil + // Return the value and a boolean indicating if it was found + if val := ctx.Value(key); val != nil { + return val, true + } + return nil, false +} + +// ExecuteWithContext executes a task that can be cancelled via context +func (cm *simpleContextManager) ExecuteWithContext(ctx context.Context, task func() error) error { + // TODO: Implement task execution with context cancellation + // Hint: Run the task in a goroutine and use select with ctx.Done() + // Return context error if cancelled, task error if task fails + errCh := make(chan error, 1) + + go func() { + errCh <- task() + }() + + select { + case err := <-errCh: + return err + case <-ctx.Done(): + return ctx.Err() + } + +} + +// WaitForCompletion waits for a duration or until context is cancelled +func (cm *simpleContextManager) WaitForCompletion(ctx context.Context, duration time.Duration) error { + // TODO: Implement waiting with context awareness + // Hint: Use select with ctx.Done() and time.After(duration) + // Return context error if cancelled, nil if duration completes + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(duration): + return nil + } +} + +// Helper function - simulate work that can be cancelled +func SimulateWork(ctx context.Context, workDuration time.Duration, description string) error { + // TODO: Implement cancellable work simulation + // Hint: Use select with ctx.Done() and time.After(workDuration) + // Print progress messages and respect cancellation + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(workDuration): + fmt.Println(description) + return nil + } +} + +// Helper function - process multiple items with context +func ProcessItems(ctx context.Context, items []string) ([]string, error) { + // TODO: Implement batch processing with context awareness + // Process each item but check for cancellation between items + // Return partial results if cancelled + result := make([]string, 0, len(items)) + + for _, v := range items { + select { + case <-ctx.Done(): + return result, ctx.Err() + default: + } + + time.Sleep(50 * time.Millisecond) + + processedItem := fmt.Sprint("processed_", v) + result = append(result, processedItem) + } + + return result, nil +} + +// Example usage +func main() { + fmt.Println("Context Management Challenge") + fmt.Println("Implement the context manager methods!") + + // Example of how the context manager should work: + cm := NewContextManager() + + // Create a cancellable context + ctx, cancel := cm.CreateCancellableContext(context.Background()) + defer cancel() + + // Add some values + ctx = cm.AddValue(ctx, "user", "alice") + ctx = cm.AddValue(ctx, "requestID", "12345") + + // Use the context + fmt.Println("Context created with values!") +}