From de23d61fc2f6409894c4f4a17ce026696926e039 Mon Sep 17 00:00:00 2001 From: NR Date: Fri, 17 Feb 2023 02:36:05 +0700 Subject: [PATCH] Practice 1 --- Assignment/Assignment1/p1.go | 7 +++++-- Assignment/Assignment1/p2.go | 29 +++++++++++++++++++++++++++-- Assignment/Assignment1/p3.go | 15 +++++++++++++-- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/Assignment/Assignment1/p1.go b/Assignment/Assignment1/p1.go index ae5421f..7cc4f81 100644 --- a/Assignment/Assignment1/p1.go +++ b/Assignment/Assignment1/p1.go @@ -24,6 +24,9 @@ Output: -1 func DivideWhole(a int, b int) int { // TODO: Your code here - return 0 + if b != 0 { + return a / b + } else { + return -1 + } } - diff --git a/Assignment/Assignment1/p2.go b/Assignment/Assignment1/p2.go index b0c0ea6..e88a4a0 100644 --- a/Assignment/Assignment1/p2.go +++ b/Assignment/Assignment1/p2.go @@ -1,5 +1,10 @@ package Assignment1 +import ( + "strings" + "unicode" +) + /* Clean up sentences. [WEIGHT = 1] @@ -32,6 +37,26 @@ Explanation: Replace the : and , and then remove all trailing/leading spaces func CleanUp(s string) string { // TODO: Your code here - return "" -} + var cleanedStr strings.Builder + prevCharWasSpace := false + for _, r := range s { + if unicode.IsLetter(r) || unicode.IsNumber(r) || r == ' ' { + if r == ' ' { + if !prevCharWasSpace { + cleanedStr.WriteRune(r) + } + prevCharWasSpace = true + } else { + cleanedStr.WriteRune(r) + prevCharWasSpace = false + } + } else { + if !prevCharWasSpace { + cleanedStr.WriteRune(' ') + } + prevCharWasSpace = true + } + } + return strings.TrimSpace(cleanedStr.String()) +} diff --git a/Assignment/Assignment1/p3.go b/Assignment/Assignment1/p3.go index 031362d..68c848f 100644 --- a/Assignment/Assignment1/p3.go +++ b/Assignment/Assignment1/p3.go @@ -21,6 +21,17 @@ Explanation: All numbers are odd, so return 0 func EvenSum(nums []int) int { // TODO: Your code here - return 0 -} + result := 0 + + for _, i := range nums { + if i%2 == 0 { + result += i + } + } + if result != 0 { + return result + } else { + return 0 + } +}