Skip to content

Instantly share code, notes, and snippets.

@daviesesiro
Last active December 31, 2022 17:33
Show Gist options
  • Save daviesesiro/e0c74e10ed4833a282cfada8a46ac511 to your computer and use it in GitHub Desktop.
Save daviesesiro/e0c74e10ed4833a282cfada8a46ac511 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"sort"
"strconv"
"time"
"github.com/olekukonko/tablewriter"
)
func main() {
names := FetchNames()
rand.Seed(time.Now().UnixNano())
const loops = 2023
frequency := make(map[string]int)
for i := 0; i < loops; i++ {
frequency[names[rand.Intn(len(names))]]++
}
PrintResults(os.Stdout, frequency, loops)
}
func PrintResults(output *os.File, frequency map[string]int, loops int) {
var namesAndCounts [][]string
for name, count := range frequency {
namesAndCounts = append(namesAndCounts, []string{name, fmt.Sprintf("%d", count)})
}
sort.Slice(namesAndCounts, func(i, j int) bool {
return namesAndCounts[i][1] > namesAndCounts[j][1]
})
table := tablewriter.NewWriter(output)
table.SetHeader([]string{"S/N", "Name", "Count", "Percentage"})
for i, nameAndCount := range namesAndCounts {
count, _ := strconv.Atoi(nameAndCount[1])
percentage := float64(count) / float64(loops) * 100
line := []string{fmt.Sprintf("%d", i+1), nameAndCount[0], nameAndCount[1], fmt.Sprintf("%.2f%%", percentage)}
table.Append(line)
}
table.Render()
}
func FetchNames() []string {
file, err := os.Open("names.txt")
if err != nil {
log.Fatalf("failed to open")
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var names []string
for scanner.Scan() {
names = append(names, scanner.Text())
}
return names
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment