Logo

Programming-Idioms

Declare a Graph data structure in which each Vertex has a collection of its neighbouring vertices.
Implementation
Kotlin

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Kotlin implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
type Vertex struct{
	Id int
	Label string
	Neighbours map[*Vertex]bool
}

type Graph []*Vertex
struct Vertex
{
	float x, y, z;
	Vertex* [] adjacentVertices;
}
Vertex = Struct.new(:x, :y, :z)
Graph = Struct.new(:vertex, :neighbours)

v = Vertex.new(1, 2, 3)
neighbours = [ Vertex.new(2, 3, 4), Vertex.new(4, 5, 6) ]
graph = Graph.new(v, neighbours)
datatype Node = Int
datatype Adjacencies = [ Node ]
datatype Graph = [ Adjacencies ]
import java.util.List;
class Graph{
  List<Vertex> vertices;

  static class Vertex{
    int id;
    List<Vertex> neighbours;
  }
}
import java.util.Set;
class Graph{
  Set<Vertex> vertices;

  static class Vertex{
    int id;
    Set<Vertex> neighbours;
  }
}
from collections import defaultdict
class Vertex(set): pass
class Graph(defaultdict):
  def __init__(self, *paths):
    self.default_factory = Vertex
    for path in paths:
      self.make_path(path)

  def make_path(self, labels):
    for l1, l2 in zip(labels, labels[1:]):
      self[l1].add(l2)
      self[l2].add(l1)

G = Graph((0, 1, 2, 3), (1, 4, 2))
use Graph::Undirected qw();
my $G = Graph::Undirected->new(edges => [
    [1,3], [2,4], [3,4], [3,5], [4,5]
]);
type Graph[L any] []*Vertex[L]

type Vertex[L any] struct {
	Label      L
	Neighbours map[*Vertex[L]]bool
}