Created
June 22, 2017 19:29
-
-
Save dnutiu/4d94d29c7465d8fa8da1f5bddc9a1ebf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Compare the Triplets | |
| // Metonimie 22 Jun 2017 | |
| package main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "os" | |
| ) | |
| type triplet struct { | |
| first int | |
| second int | |
| third int | |
| } | |
| // readTriplets reads triplets from stdin and returns an array of them. | |
| func readTriplets() ([]string, error) { | |
| scanner := bufio.NewScanner(os.Stdin) | |
| triplets := make([]string, 0, 2) | |
| for scanner.Scan() { | |
| triplets = append(triplets, scanner.Text()) | |
| } | |
| return triplets, scanner.Err() | |
| } | |
| func addScore(a, b int, as, bs *uint) { | |
| if a > b { | |
| *as++ | |
| } else if a < b { | |
| *bs++ | |
| } | |
| } | |
| func (this *triplet) calculateScore(other *triplet) (uint, uint) { | |
| var a, b uint | |
| addScore(this.first, other.first, &a, &b) | |
| addScore(this.second, other.second, &a, &b) | |
| addScore(this.third, other.third, &a, &b) | |
| return a, b | |
| } | |
| func compareTriplets(triplets []string) (uint, uint, error) { | |
| if len(triplets) < 2 { | |
| return 0, 0, fmt.Errorf("compareTriplets: got less than two triplets") | |
| } | |
| alice := new(triplet) | |
| bob := new(triplet) | |
| var aliceScore, bobScore uint | |
| // Extract triplets from string | |
| fmt.Sscanf(triplets[0], "%d %d %d", &alice.first, &alice.second, &alice.third) | |
| fmt.Sscanf(triplets[1], "%d %d %d", &bob.first, &bob.second, &bob.third) | |
| aliceScore, bobScore = alice.calculateScore(bob) | |
| return aliceScore, bobScore, nil | |
| } | |
| func main() { | |
| triplets, err := readTriplets() | |
| if err != nil { | |
| fmt.Errorf("main: %s", err) | |
| os.Exit(1) | |
| } | |
| a, b, _ := compareTriplets(triplets[:]) | |
| fmt.Println(a, b) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment