1 of 12

Go : Set, Grid, Generics

Pierre-Etienne Moreau

2 of 12

Set

3 of 12

Set : pas de Set en Go

  • Utilisation d'une map :�var s = make(map[int]bool)�
  • Ajout : s[5] = true
  • Appartenance : if s[4] { … }
  • Est vide : if len(s)==0 { … }

4 of 12

Set : map de struct{}

  • Utilisation d'une map :�var s = make(map[int]struct{})�
  • Ajout : s[5] = struct{}{}
  • Appartenance : if _, ok := s[4]; ok { … }
  • Est vide : if len(s)==0 { … }

5 of 12

Grid

6 of 12

Grid : tableau de tableau ou map

  • Utilisation d'une map :�type Pos struct{ X, Y int }�type Grid map[Pos]uint8
  • Ajout : grid[Pos{3, 4}] = 'x'
  • Appartenance : if c, ok := grid[Pos{3, 4}]; ok { … }
  • Voisinage : �func (p Pos) Neighbors4() []Pos {� return []Pos{� {X: p.X, Y: p.Y - 1},� {X: p.X, Y: p.Y + 1},� {X: p.X - 1, Y: p.Y},� {X: p.X + 1, Y: p.Y},� }�}

7 of 12

Remarques sur les caractères

  • var c = 'A'�fmt.Println(c)
  • Quel est le type de c
  • Qu'affiche le Println ?
  • Comment savoir si c est un chiffre ?�if c>='0' && c<='9' ou unicode.IsDigit('5')
  • Comment convertir un chiffre en un entier ?
  • Comment convertir une chaine en un entier ?
  • Regardez les packages strings, unicode, strconv

8 of 12

Generics

9 of 12

Set : type set map[int]bool

  • T est une variable universellement quantifiée (pour tout T) :�type Set[T comparable] map[T]bool
  • Création : var s = make(Set[int])
  • Ajout : s[5] = true
  • Fonction pour créer un Set�func NewSet[T comparable]() Set[T] {� return make(Set[T])�}
  • Création : var s = NewSet[int]()

10 of 12

Set : définition de méthodes

  • T est une variable universellement quantifiée (pour tout T) :�type Set[T comparable] map[T]bool
  • Création : var s = make(Set[int])
  • Ajout :�func (s Set[T]) Add(value T) {� s[value] = true�}
  • s.Add(4)
  • Est vide�func (s Set[T]) IsEmpty() bool {� return len(s) == 0�}
  • if s.IsEmpty() { … }

11 of 12

Méthodologie

12 of 12

Votre ennemi

  • la complexité
  • votre pire ennemi : la recherche de bugs
  • comment l'éviter :
    • essayez de penser au cas général
    • utilisez des structure de données adaptées
    • écrivez (TOUJOURS) des jeux de tests
    • testez vos fonctions
  • si l'exemple passe mais pas l'input
    • pensez aux cas limites "oubliés"
    • relisez calmement votre code
  • Autre règle : Premature optimization is the root of all evil.� – Sir Tony Hoare
    • écrivez du code correct
    • optimisez seulement lorsque tout fonctionne