Внутри цикла определяем родительские ссылки - PullRequest
0 голосов
/ 13 мая 2019

Я хотел бы зациклить имя своих таблиц, чтобы добавить ассоциации, определяемые символом "_".

Если таблица a_b и a, то b существует тогда a = [b], b = [a].Наконец, мне не нужно печатать таблицы, содержащие "_" в имени

Struct

// Table with Fields and Assoc
type Table struct {
    Name       string
    Assoc      []Assoc
}

// Assoc is a name of associated Table
type Assoc struct {
  Name string
}
tables := []string{
    "a",
    "b",
    "c",
    "d",
    "f",
    "a_b",
    "a_c",
    "a_d_f",
    "c_d",      
}

var tbls []Table

for _, t := range tables {
    if strings.Contains(t, "_") {
        // Split to find "_" like assoc := strings.Split(t, "_") ?
        // append in struct "Table{Name:a, Assoc:  [b,c,d,f]}"
        // append in struct "Table{Name:b, Assoc:  [a]}"
        // append in struct "Table{Name:c, Assoc:  [a,d]}"
        // append in struct "Table{Name:d, Assoc:  [a,c,f]}"
        // append in struct "Table{Name:f, Assoc:  [a,d]}"      
    } else {
        n := Table{
            Name: t,
        }
        tbls = append(tbls, n)
    }

}

Возврат, как fmt.Println(tbls):

[{a [b,c,d,f]} {b [a]} {c [a,d]} {d [a,c,f]} {f [a,d]}]

Игровая площадка Go

1 Ответ

0 голосов
/ 13 мая 2019

Выполнено вышеупомянутое с использованием карты https://play.golang.org/p/8C5M0L-es6o

package main

import (
    "fmt"
    "strings"
)

// Table with Fields and Assoc
type Table struct {
    Name  string
    Assoc map[string]int
}

// Assoc is a name of associated Table
// type Assoc struct {
//  Name string
// }

func main() {
    tables := []string{
        "a",
        "b",
        "c",
        "d",
        "f",
        "a_b",
        "a_c",
        "a_d_f",
        "c_d",
    }

    var tbls = make(map[string]map[string]int)

    for _, t := range tables {
        if strings.Contains(t, "_") {
            splitAssocs := strings.Split(t, "_")            
            for i:=0;i<=len(splitAssocs)-2;i++ {
                for j:=(i+1);j<=len(splitAssocs)-1;j++{
                    _, ok := tbls[splitAssocs[i]]
                    if !ok{
                        tbls[splitAssocs[i]] = make(map[string]int)
                    }
                     _, ok = tbls[splitAssocs[j]]
                    if !ok{
                        tbls[splitAssocs[j]] = make(map[string]int)
                    }
                    tbls[splitAssocs[i]][splitAssocs[j]] = 1
                    tbls[splitAssocs[j]][splitAssocs[i]] = 1
                }

            }

        } else {
            _, ok := tbls[t]            
            if !ok{
                tbls[t] = make(map[string]int)
            }
        }

    }

    fmt.Println(tbls)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...