diff --git a/Lab04/content/part1/analyse/main.go b/Lab04/content/part1/analyse/main.go index 1152a17..e366ca0 100644 --- a/Lab04/content/part1/analyse/main.go +++ b/Lab04/content/part1/analyse/main.go @@ -1,14 +1,15 @@ package main import ( + "flag" "fmt" "github.com/dariubs/percent" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/plotutil" "gonum.org/v1/plot/vg" - "io/ioutil" "log" + "os" "sort" "strings" ) @@ -26,27 +27,39 @@ func (l letterList) Len() int { return len(l) } -func (l letterList) Less(i, j int) bool { - return l[i].frequency > l[j].frequency +func (l letterList) Less(firstIndex, secondIndex int) bool { + return l[firstIndex].frequency > l[secondIndex].frequency } -func (l letterList) Swap(i, j int) { - l[i], l[j] = l[j], l[i] +func (l letterList) Swap(firstIndex, secondIndex int) { + l[firstIndex], l[secondIndex] = l[secondIndex], l[firstIndex] } const lettersInTheAlphabet = 'Z' - 'A' + 1 var letters = make([]letter, lettersInTheAlphabet) -func initLetterStruct() { +func init() { for i := 0; i < lettersInTheAlphabet; i++ { letters[i].upperCase = string(rune('A' + i)) letters[i].lowerCase = string(rune('A' + i + 32)) } } +func parseArguments() string { + var inputFile string + flag.StringVar(&inputFile, "f", "", "Specify file to analyse.") + flag.Parse() + if inputFile == "" { + log.Print("No flag provided\n\nHelp:\n") + flag.PrintDefaults() + os.Exit(1) + } + return inputFile +} + func readFile(relativePath string) string { - content, err := ioutil.ReadFile(relativePath) + content, err := os.ReadFile(relativePath) if err != nil { log.Fatalln(err) } @@ -100,15 +113,14 @@ func plotResult() { xAxisNaming = append(xAxisNaming, letters[index].upperCase) } p.NominalX(xAxisNaming...) - if err := p.Save(25*vg.Centimeter, 15*vg.Centimeter, "barChart.png"); err != nil { + if err = p.Save(25*vg.Centimeter, 15*vg.Centimeter, "barChart.png"); err != nil { log.Fatalln(err) } } func main() { - initLetterStruct() - //totalCount := countLetters(readFile("plaintext.txt")) - totalCount := countLetters(readFile("../encrypt/output.txt")) + inputFile := parseArguments() + totalCount := countLetters(readFile(inputFile)) calculateFrequency(totalCount) plotResult() sort.Sort(letterList(letters)) diff --git a/Lab04/content/part1/encrypt/main.go b/Lab04/content/part1/encrypt/main.go index 00b43ec..11e5683 100644 --- a/Lab04/content/part1/encrypt/main.go +++ b/Lab04/content/part1/encrypt/main.go @@ -2,7 +2,6 @@ package main import ( "flag" - "io/ioutil" "log" "os" "regexp" @@ -27,7 +26,7 @@ func parseArguments() (string, string) { } func readFile(relativePath string) string { - content, err := ioutil.ReadFile(relativePath) + content, err := os.ReadFile(relativePath) if err != nil { log.Fatalln(err) }