*** disclaimer : i'm not a professional developer, been tinkering with golang for about 8 month (udemy + youtube) and still got no idea how to simple problem like below..
Here's the summarize of the problem :
I'm trying to find the most frequent "age" from struct that comes from the decoded .json file (containing string "name" and integer "age").
After that i need to print the "name" based on the maximum occurence frequency of "age".
The printed "name" based on the maximum-occurence of "age" needs to be sorted alpabethically
Input (.json) :
[
{"name": "John","age": 15},
{"name": "Peter","age": 12},
{"name": "Roger","age": 12},
{"name": "Anne","age": 44},
{"name": "Marry","age": 15},
{"name": "Nancy","age": 15}
]
Output : ['John', 'Mary', 'Nancy'].
Explaination : Because the most occurring age in the data is 15 (occured 3 times), the output should be an array of strings with the three people's name, in this case it should be ['John', 'Mary', 'Nancy'].
Exception :
- In the case there are multiple "age" with the same maximum-occurence count, i need to split the data and print them into different arrays (i.e when 'Anne' age is 12, the result is: ['John', 'Mary', 'Nancy'], ['Anne','Peter','Roger']
This is what i've tried (in Golang) :
package main
{
import (
"encoding/json"
"fmt"
"os"
"sort"
)
// 1. preparing the empty struct for .json
type Passanger struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
// 2. load the json file
content, err := os.ReadFile("passanger.json")
if err != nil {
fmt.Println(err.Error())
}
// 3. parse json file to slice
var passangers []Passanger
err2 := json.Unmarshal(content, &passangers)
if err2 != nil {
fmt.Println("Error JSON Unmarshalling")
fmt.Println(err2.Error())
}
// 4. find most frequent age numbers (?)
for _, v := range passangers {
// this code only show the Age on every line
fmt.Println(v.Age)
}
// 5. print the name and sort them apabethically (?)
// use sort.slice package
// implement group based by "max-occurence-age"
}
Been stuck since yesterday, i've also tried to implement the solution from many coding challenge question like :
func majorityElement(arr int) int {
sort.Ints(arr)
return arr[len(arr)/2]
}
but i'm still struggling to understand how to handle the "age" value from the Passanger slice as an integer input(arr int) to code above.
others solution i've found online is by iterating trough map[int]int to find the maximum frequency :
func main(){
arr := []int{90, 70, 30, 30, 10, 80, 40, 50, 40, 30}
freq := make(map[int]int)
for _ , num := range arr {
freq[num] = freq[num]+1
}
fmt.Println("Frequency of the Array is : ", freq)
}
but then again, the .json file contain not only integer(age) but also string(name) format, i still don't know how to handle the "name" and "age" separately..
i really need a proper guidance here.
*** here's the source code (main.go) and (.json) file that i mentioned above : https://github.com/ariejanuarb/golang-json