From 45a7c2784737812dc617b055235f6096e677d86f Mon Sep 17 00:00:00 2001 From: Kao9 Date: Wed, 6 Aug 2025 17:41:15 +0700 Subject: [PATCH 1/7] Add solution for Challenge 1 by korranat9 --- .../korranat9/solution-template.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 challenge-1/submissions/korranat9/solution-template.go diff --git a/challenge-1/submissions/korranat9/solution-template.go b/challenge-1/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..aab16ac4 --- /dev/null +++ b/challenge-1/submissions/korranat9/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 7e4923ec50df98242d2fcfe55fcabd11c57d4640 Mon Sep 17 00:00:00 2001 From: Kao9 Date: Wed, 6 Aug 2025 17:58:03 +0700 Subject: [PATCH 2/7] Add solution for Challenge 2 by korranat9 --- .../korranat9/solution-template.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 challenge-2/submissions/korranat9/solution-template.go diff --git a/challenge-2/submissions/korranat9/solution-template.go b/challenge-2/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..4b09c309 --- /dev/null +++ b/challenge-2/submissions/korranat9/solution-template.go @@ -0,0 +1,31 @@ +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 + slices := []rune(s) + for i, j := 0, len(slices)-1; i < j; i,j = i+1, j-1{ + slices[i], slices[j] = slices[j], slices[i] + } + return string(slices) +} From b7c5991385f61143eeb16cc995df4570345486c6 Mon Sep 17 00:00:00 2001 From: Kao9 Date: Wed, 6 Aug 2025 18:41:46 +0700 Subject: [PATCH 3/7] Add solution for Challenge 3 by korranat9 --- .../korranat9/solution-template.go | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 challenge-3/submissions/korranat9/solution-template.go diff --git a/challenge-3/submissions/korranat9/solution-template.go b/challenge-3/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..91caf481 --- /dev/null +++ b/challenge-3/submissions/korranat9/solution-template.go @@ -0,0 +1,70 @@ +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 + var newEmployees []Employee + for _, e := range m.Employees{ + if e.ID != id { + newEmployees = append(newEmployees, e) + } + } + m.Employees = newEmployees +} + +// GetAverageSalary calculates the average salary of all employees. +func (m *Manager) GetAverageSalary() float64 { + // TODO: Implement this method + if len(m.Employees) == 0{ + return 0.0 + } + avgSalary := 0.0 + for _, e := range m.Employees{ + avgSalary = avgSalary + e.Salary + } + return avgSalary/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 _, e := range m.Employees{ + if id == e.ID{ + return &e + } + } + 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 a2ea81aa34414d448ded4e4d22cd1f18315a516d Mon Sep 17 00:00:00 2001 From: Kao9 Date: Thu, 7 Aug 2025 01:41:56 +0700 Subject: [PATCH 4/7] Add solution for Challenge 4 by korranat9 --- .../korranat9/solution-template.go | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 challenge-4/submissions/korranat9/solution-template.go diff --git a/challenge-4/submissions/korranat9/solution-template.go b/challenge-4/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..3d884d83 --- /dev/null +++ b/challenge-4/submissions/korranat9/solution-template.go @@ -0,0 +1,95 @@ +package main +import ( + "sync" +) +// 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. +func bfs(graph map[int][]int, start int) []int { + visited := make(map[int]bool) + queue := []int{start} + visited[start] = true + order := []int{} + + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + order = append(order, node) + + for _, neighbor := range graph[node] { + if !visited[neighbor] { + visited[neighbor] = true + queue = append(queue, neighbor) + } + } + } + return order +} +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. + type job struct { + query int + } + type result struct { + query int + order []int + } + + jobs := make(chan job) + results := make(chan result) + + var wg sync.WaitGroup + + // Worker function + worker := func() { + defer wg.Done() + for j := range jobs { + order := bfs(graph, j.query) + results <- result{query: j.query, order: order} + } + } + + // Start workers + wg.Add(numWorkers) + for i := 0; i < numWorkers; i++ { + go worker() + } + + // Send jobs + go func() { + for _, q := range queries { + jobs <- job{query: q} + } + close(jobs) + }() + + // Collect results in another goroutine + done := make(chan struct{}) + resultMap := make(map[int][]int) + var mu sync.Mutex + + go func() { + for r := range results { + mu.Lock() + resultMap[r.query] = r.order + mu.Unlock() + } + close(done) + }() + + // Wait for all workers to finish + wg.Wait() + close(results) + <-done + + return resultMap +} + +func main() { + // You can insert optional local tests here if desired. +} From 17f0020bc9bdce837fa452748b4e1ee656bcbc9a Mon Sep 17 00:00:00 2001 From: Kao9 Date: Fri, 8 Aug 2025 01:27:30 +0700 Subject: [PATCH 5/7] Add solution for Challenge 5 by korranat9 --- .../korranat9/solution-template.go | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 challenge-5/submissions/korranat9/solution-template.go diff --git a/challenge-5/submissions/korranat9/solution-template.go b/challenge-5/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..0e2e2aa0 --- /dev/null +++ b/challenge-5/submissions/korranat9/solution-template.go @@ -0,0 +1,58 @@ +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 + token := r.Header.Get("X-Auth-Token") + + // 2) Compare against validToken + if token != validToken{ + http.Error(w, "", 401) + return + } + // 3) If mismatch or missing, respond with 401 + // 4) Otherwise pass to next handler + 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(":8080", SetupServer()) +} From d438eed7e0615e462f803ddba1e3da3082a9c78d Mon Sep 17 00:00:00 2001 From: Kao9 Date: Fri, 8 Aug 2025 01:45:19 +0700 Subject: [PATCH 6/7] Add solution for Challenge 6 by korranat9 --- .../korranat9/solution-template.go | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 challenge-6/submissions/korranat9/solution-template.go diff --git a/challenge-6/submissions/korranat9/solution-template.go b/challenge-6/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..8c920d6e --- /dev/null +++ b/challenge-6/submissions/korranat9/solution-template.go @@ -0,0 +1,44 @@ +// 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 + re := regexp.MustCompile(`[^a-zA-Z0-9 ]+`) + text = strings.ReplaceAll(text, "\n", " ") + text = strings.ReplaceAll(text, "\t", " ") + text = strings.ReplaceAll(text, "'", "") + cleaned := re.ReplaceAllString(text, " ") + wordFrequency := make(map[string]int) + words := strings.Split(cleaned, " ") + for _, word := range words{ + lowercase := strings.ToLower(word) + if len(lowercase) > 0{ + _, exists := wordFrequency[lowercase] + if exists { + wordFrequency[lowercase] += 1 + }else{ + wordFrequency[lowercase] = 1 + } + } + + } + + return wordFrequency +} \ No newline at end of file From c9d3fcb8697a07721d72c51a8c0cfe7d7b7bf3b5 Mon Sep 17 00:00:00 2001 From: Kao9 Date: Fri, 8 Aug 2025 15:50:40 +0700 Subject: [PATCH 7/7] Add solution for Challenge 7 by korranat9 --- .../korranat9/solution-template.go | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 challenge-7/submissions/korranat9/solution-template.go diff --git a/challenge-7/submissions/korranat9/solution-template.go b/challenge-7/submissions/korranat9/solution-template.go new file mode 100644 index 00000000..e7328d08 --- /dev/null +++ b/challenge-7/submissions/korranat9/solution-template.go @@ -0,0 +1,164 @@ +// Package challenge7 contains the solution for Challenge 7: Bank Account with Error Handling. +package challenge7 + +import ( + "sync" + "fmt" + // 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 + Message string +} + +func (e *AccountError) Error() string { + // Implement error message + return fmt.Sprintf("Account error: %s", e.Message) +} + +// InsufficientFundsError occurs when a withdrawal or transfer would bring the balance below minimum. +type InsufficientFundsError struct { + // Implement this error type + Required float64 + Available float64 +} + +func (e *InsufficientFundsError) Error() string { + // Implement error message + return fmt.Sprintf("Insufficient funds: need at least %.2f, but only %.2f is available", e.Required, e.Available) + +} + +// 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 fmt.Sprintf("Negative amount error: %.2f is not a valid amount", e.Amount) +} + +// ExceedsLimitError occurs when a deposit or withdrawal amount exceeds the defined limit. +type ExceedsLimitError struct { + // Implement this error type + Amount float64 + Limit float64 +} + +func (e *ExceedsLimitError) Error() string { + // Implement error message + return fmt.Sprintf("Amount %.2f exceeds transaction limit of %.2f", e.Amount, e.Limit) +} + +// 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 and Owner must not be empty"} + } + + + if initialBalance < 0 { + return nil, &NegativeAmountError{Amount: initialBalance} + } + if minBalance < 0 { + return nil, &NegativeAmountError{Amount: minBalance} + } + if initialBalance < minBalance { + return nil, &InsufficientFundsError{Required: minBalance,Available: initialBalance} + } + + 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 + if amount < 0 { + return &NegativeAmountError{Amount: amount} + } + if amount > MaxTransactionAmount { + return &ExceedsLimitError{Amount: amount, Limit: MaxTransactionAmount} + } + a.mu.Lock() + defer a.mu.Unlock() + 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 + if amount < 0 { + return &NegativeAmountError{Amount: amount} + } + if amount > MaxTransactionAmount { + return &ExceedsLimitError{Amount: amount, Limit: MaxTransactionAmount} + } + + a.mu.Lock() + defer a.mu.Unlock() + + if a.Balance-amount < a.MinBalance { + return &InsufficientFundsError{ + Required: a.MinBalance, + Available: a.Balance - amount, + } + } + + 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 + if a == target { + return &AccountError{"Cannot transfer to the same account"} + } + + // Try to withdraw first + if err := a.Withdraw(amount); err != nil { + return err + } + + // If withdraw succeeded, deposit to target + if err := target.Deposit(amount); err != nil { + // Rollback the withdrawal if deposit failed + a.Deposit(amount) + return err + } + + return nil +} \ No newline at end of file