Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- )
- type Node struct {
- name string
- children []Node
- }
- var data Node = Node{
- name: "var",
- children: []Node {
- Node {
- name: "lib",
- children: []Node {},
- },
- Node {
- name: "log",
- children: []Node {
- Node {
- name: "apt",
- children: []Node {},
- },
- Node {
- name: "exim4",
- children: []Node {},
- },
- },
- },
- Node {
- name: "www",
- children: []Node {
- Node {
- name: "html",
- children: []Node {
- Node {
- name: "assets",
- children: []Node {
- Node {
- name: "images",
- children: []Node {},
- },
- Node {
- name: "audio",
- children: []Node {},
- },
- },
- },
- Node {
- name: "sites",
- children: []Node {
- Node {
- name: "main",
- children: []Node {},
- },
- Node {
- name: "secondary",
- children: []Node {},
- },
- },
- },
- },
- },
- },
- },
- },
- }
- func recPrint(n *Node, depth int){
- for i := 0; i < depth; i++ {
- // to print pretty
- fmt.Printf("└─ ")
- }
- fmt.Printf("%s\n", n.name)
- for _, child := range n.children {
- recPrint(&child, (depth + 1))
- }
- }
- func recFind(n *Node, toFind []string) [][]string {
- // empty result array
- retStrings := [][]string {}
- if (len(toFind) == 1 && toFind[0] == n.name) || toFind == nil {
- // is it the last matching node?
- // or is it a child of the last matching node?
- retStrings = append(retStrings, []string {n.name})
- toFind = nil
- } else if len(toFind) > 1 {
- // search for next match in children
- toFind = toFind[1:]
- } else {
- return retStrings
- }
- for i := 0; i < len(n.children); i++ {
- // get all match children, and children of matches
- // toFind is contextual to the above
- childString := recFind(&n.children[i], toFind)
- for j := 0; j < len(childString); j++ {
- // if children were returned, create entries for them to be
- // appended to
- retStrings = append(retStrings, []string {n.name})
- // get last index of array
- lastRS := len(retStrings) - 1
- // append new child to last index of array
- retStrings[lastRS] = append(retStrings[lastRS], childString[j]...)
- }
- }
- return retStrings
- }
- func main () {
- fmt.Println("RAW: ")
- fmt.Println(data)
- fmt.Println()
- fmt.Println("PRETTY:")
- recPrint(&data, 0)
- fmt.Println()
- toFind := []string{ "var", "www", "html" }
- matches := recFind(&data, toFind)
- fmt.Println()
- fmt.Println("MATCHES:")
- for i := 0; i < len(matches); i++ {
- fmt.Println(matches[i])
- }
- }
Add Comment
Please, Sign In to add comment