push all exercices

This commit is contained in:
lbenedar
2026-02-21 14:09:13 +03:00
commit a94d994b8c
72 changed files with 787 additions and 0 deletions

81
ch7/3/ch7_3.go Normal file
View File

@@ -0,0 +1,81 @@
package main
import (
"fmt"
"io"
"sort"
)
type Ranker interface {
Ranking() []string
}
type testWriter struct{}
func (p testWriter) Write(bs []byte) (int, error) {
if len(bs) == 0 {
return 0, nil
}
for i := 0; i < len(bs); i++ {
fmt.Print(string(bs[i]))
}
return len(bs), nil
}
func RankPrinter(ranker Ranker, writer io.Writer) {
rankSize := len(ranker.Ranking())
for i, teams := range ranker.Ranking() {
writer.Write([]byte(teams))
if i != rankSize-1 {
writer.Write([]byte("\n"))
}
}
}
type Team struct {
Name string
Players []string
}
type League struct {
name string
Teams map[string]Team
Wins map[string]int
}
func (l *League) MatchResult(firstTeam string, firstScore int, secondTeam string, secondScore int) {
if _, ok := l.Teams[firstTeam]; ok {
return
}
if _, ok := l.Teams[secondTeam]; ok {
return
}
if firstScore == secondScore {
return
}
if firstScore > secondScore {
l.Wins[firstTeam]++
} else if secondScore > firstScore {
l.Wins[secondTeam]++
}
}
func (l League) Ranking() []string {
teamRanking := make([]string, 0, len(l.Wins))
for winsK := range l.Wins {
teamRanking = append(teamRanking, winsK)
}
sort.Slice(teamRanking, func(i, j int) bool {
return l.Wins[teamRanking[i]] < l.Wins[teamRanking[j]]
})
return teamRanking
}
func main() {
league := League{"newLeague", map[string]Team{}, map[string]int{"first": 1, "second": 2, "third": 6, "fourth": 3, "fifth": 4}}
league.MatchResult("third", 5, "second", 4)
fmt.Println(league)
fmt.Println(league.Ranking())
writer := testWriter{}
RankPrinter(league, writer)
}