Skip to content

Instantly share code, notes, and snippets.

@prettyirrelevant
Last active March 5, 2022 10:56
Show Gist options
  • Save prettyirrelevant/c7717b7fc3ca17049c35fd8a0c637108 to your computer and use it in GitHub Desktop.
Save prettyirrelevant/c7717b7fc3ca17049c35fd8a0c637108 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
)
type KeyValueSlice map[string]float64
func main() {
CalculateGPA()
}
func CalculateGPA() {
fmt.Println("CGPA Calculator v1.0")
for i := 1; i < 4; i++ {
// to store course grade and units
datastore := make([]KeyValueSlice, 0)
var numberOfCourses int
fmt.Printf("How many courses do you offer? (Min. of 3): ")
fmt.Scanln(&numberOfCourses)
if numberOfCourses < 3 {
fmt.Println("You should offer a minimum of three(53 courses!!!")
return
}
for j := 0; j < numberOfCourses; j++ {
var courseScore float64
var courseUnit int
fmt.Printf("Enter the score and unit of the course(e.g 49 5): ")
fmt.Scanln(&courseScore, &courseUnit)
if courseScore >= 70 && courseScore <= 100 {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 5})
} else if courseScore >= 60 && courseScore < 70 {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 4})
} else if courseScore >= 50 && courseScore < 60 {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 3})
} else if courseScore >= 45 && courseScore < 50 {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 2})
} else if courseScore >= 40 && courseScore < 45 {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 1})
} else {
datastore = append(datastore, KeyValueSlice{"courseUnit": float64(courseUnit), "coursePoint": 0})
}
}
studentGPA := sum(datastore, "") / sum(datastore, "courseUnit")
fmt.Printf("\nStudent #%v offered %v course(s) and has a GPA of %.2f/5\n\n\n", i, numberOfCourses, studentGPA)
datastore = nil
}
}
func sum(sliceToSum []KeyValueSlice, keyToSum string) float64 {
var _sum float64
if keyToSum == "" {
for _, item := range sliceToSum {
_sum += item["courseUnit"] * item["coursePoint"]
}
} else if _, ok := sliceToSum[0][keyToSum]; ok {
for _, item := range sliceToSum {
_sum += item[keyToSum]
}
} else {
panic(errors.New("invalid key provided"))
}
return _sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment