The Folder struct definition below is given:
type Folder struct {
ID int
emailCount int
childFolderIDs []int
}
Description of the fields are:
Id
: folder idemailCount
: number of emails in the folderchildFolderIDS
: if the folder has subfolders, this list contains folder IDS of the subfolders.
I am trying to write a function:
- Function is taking two parameters:
- First parameter is a list of all folders in the email application
var folders = []Folder{ Folder{1, 30, []int{2, 4}}, Folder{2, 10, []int{3}}, Folder{4, 60, []int{}}, Folder{3, 20, []int{}}, }
- Second parameter is folder id of a folder
- First parameter is a list of all folders in the email application
- Function will return a total number of emails with ID=Folder Id and all of its children recursively.
For example:
If the second parameter is:
four, then the function should return 60 (there is no subfolder)
two, then the function should return 30
My code is below:
package main
import "fmt"
type Folder struct {
ID int
emailCount int
childFolderIDs []int
}
func InsertIntoMap(data_arr []Folder) map[int]Folder {
var retval = make(map[int]Folder)
var child_folders []int
for _, elem := range data_arr {
child_folders = elem.childFolderIDs
var folder Folder
folder.ID = elem.ID
folder.emailCount = elem.emailCount
folder.childFolderIDs = child_folders
retval[elem.ID] = folder
}
return retval
}
func GetTotalEmailCount(p_map map[int]Folder, folder_id int) int {
total := 0
var child_folders []int
child_folders = p_map[folder_id].childFolderIDs
total = total + p_map[folder_id].emailCount
if len(child_folders) == 0{
return total
}else{
for e := range child_folders {
return total + GetTotalEmailCount(p_map, child_folders[e])
}
}
return total
}
func main() {
var folders = []Folder{
Folder{1, 30, []int{2, 4}},
Folder{2, 10, []int{3}},
Folder{4, 60, []int{}},
Folder{3, 20, []int{}},
}
var m = InsertIntoMap(folders)
fmt.Println(GetTotalEmailCount(m,1)) // result is 60
fmt.Println(GetTotalEmailCount(m,2)) // result is 30
fmt.Println(GetTotalEmailCount(m,3)) // result is 20
fmt.Println(GetTotalEmailCount(m,4)) // result is 60
}
```
Second parameter is:
) ended up in a code block. You may want to fix this before reviewing starts. (Code in the question shall stay unchanged conce you got answers. Or serious time passed since asking (- 24 hours?)) \$\endgroup\$