From 52b72ffb1b23ae5a94b5b6f2c21c11a570e73f27 Mon Sep 17 00:00:00 2001 From: nprimo Date: Mon, 29 Apr 2024 12:37:34 +0100 Subject: [PATCH] feat(gcd): make gcd solution a function instead of a program - update tests accordingly --- solutions/gcd.go | 12 ++++++++++++ solutions/gcd/main.go | 26 ------------------------- tests/gcd_test/main.go | 44 ++++++++++++++++++++++-------------------- 3 files changed, 35 insertions(+), 47 deletions(-) create mode 100644 solutions/gcd.go delete mode 100644 solutions/gcd/main.go diff --git a/solutions/gcd.go b/solutions/gcd.go new file mode 100644 index 00000000..bf9a2157 --- /dev/null +++ b/solutions/gcd.go @@ -0,0 +1,12 @@ +package solutions + +func Gcd(a, b uint) uint { + for a != b { + if a > b { + a -= b + } else { + b -= a + } + } + return a +} diff --git a/solutions/gcd/main.go b/solutions/gcd/main.go deleted file mode 100644 index 952865b2..00000000 --- a/solutions/gcd/main.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "os" - "strconv" -) - -func gcd(a, b int) int { - for a != b { - if a > b { - a -= b - } else { - b -= a - } - } - return a -} - -func main() { - if len(os.Args) == 3 { - a, _ := strconv.Atoi(os.Args[1]) - b, _ := strconv.Atoi(os.Args[2]) - fmt.Println(gcd(a, b)) - } -} diff --git a/tests/gcd_test/main.go b/tests/gcd_test/main.go index 23d15612..3db5d4d9 100644 --- a/tests/gcd_test/main.go +++ b/tests/gcd_test/main.go @@ -1,30 +1,32 @@ package main import ( - "strconv" - - "github.com/01-edu/go-tests/lib/challenge" - "github.com/01-edu/go-tests/lib/random" + "fmt" + "os" + student "student" ) func main() { - args := [][]string{ - {"42", "10"}, - {"42", "12"}, - {"14", "77"}, - {"17", "3"}, - {"23"}, - {"12", "23"}, - {"25", "15"}, - {"23043", "122"}, - {"11", "77"}, - } - for i := 0; i < 5; i++ { - a := strconv.Itoa(random.IntBetween(1, 100000)) - b := strconv.Itoa(random.IntBetween(1, 100)) - args = append(args, []string{a, b}) + testCases := []struct { + a uint + b uint + want uint + }{ + {42, 10, 2}, + {42, 12, 6}, + {14, 77, 7}, + {17, 3, 1}, + {12, 23, 1}, + {25, 15, 5}, + {23043, 122, 1}, + {11, 77, 11}, } - for _, v := range args { - challenge.Program("gcd", v...) + + for _, tc := range testCases { + got := student.Gcd(tc.a, tc.b) + if got != tc.want { + fmt.Printf("Gcd(%d, %d) = %d instead of %d\n", tc.a, tc.b, got, tc.want) + os.Exit(1) + } } }