Random Graphs
Graph Theory
Network Generation
Computational Methods
Algorithm Design

How to generate random graphs?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Generating random graphs is a foundational task in network science, algorithm benchmarking, and simulation. The right generator depends on what structure you need: uniform random edges, fixed degree sequences, small-world properties, or scale-free behavior. Choosing a model that does not match your research assumptions leads to misleading conclusions.

In practice, start by defining measurable properties (density, clustering, path length, degree distribution), then choose a generation model accordingly.

Core Sections

1. Erdős-Rényi random graph

Simple baseline with edge probability p.

python
1import networkx as nx
2
3n = 100
4p = 0.05
5G = nx.erdos_renyi_graph(n, p, seed=42)
6print(G.number_of_nodes(), G.number_of_edges())

Good for independent-edge assumptions, not for heavy-tailed degree networks.

2. Barabási-Albert scale-free graph

python
G = nx.barabasi_albert_graph(n=1000, m=3, seed=42)

Produces hubs via preferential attachment.

3. Watts-Strogatz small-world graph

python
G = nx.watts_strogatz_graph(n=200, k=6, p=0.2, seed=42)

Useful when you need high clustering with short path lengths.

4. Directed and weighted variants

Add orientation and weights after generation if base model does not include them:

python
for u, v in G.edges():
    G[u][v]['weight'] = 1.0

5. Validate generated properties

Always compute summary statistics (degree histogram, connected components, clustering coefficient) to ensure generator output matches intended regime.

Common Pitfalls

  • Using one random model for all experiments regardless of structural assumptions.
  • Ignoring random seeds and losing reproducibility.
  • Comparing algorithms on graphs with unintended disconnected components.
  • Treating generated graph properties as guaranteed without validation.
  • Confusing density-controlled and degree-sequence-controlled generation methods.

Summary

Random graph generation is model selection plus validation. Use Erdős-Rényi for independent edges, Barabási-Albert for scale-free hubs, and Watts-Strogatz for small-world structure. Set seeds, inspect graph statistics, and align generator choice with your experiment objectives. With this discipline, random-graph experiments become reproducible and meaningful.

A practical way to keep this guidance valuable over time is to convert it into an executable runbook rather than treating it as static prose. The runbook should include exact prerequisites, supported tool versions, expected environment settings, and a concise verification sequence that can be run from a clean machine. For each step, include a brief expected output and one common failure signature so engineers can quickly determine whether they are on a known-good path or a known-bad path. This reduces guesswork during incidents and shortens time-to-resolution when teams rotate ownership frequently.

It also helps to maintain one minimal reproducible fixture in source control for the specific scenario covered by the article. The fixture can be a tiny script, focused test case, sample dataset, or minimal manifest depending on topic. The point is to have an artifact that demonstrates both successful behavior and a realistic failure condition in isolation. When dependency versions or infrastructure behavior change, teams can run the fixture quickly and identify whether the regression is caused by environment drift, configuration mismatch, or application logic changes. This dramatically improves debugging speed compared to investigating only full production workflows.

For long-term reliability, add one lightweight CI guardrail that targets the most failure-prone step in the flow. Good examples include schema checks, startup smoke tests, deterministic unit tests, API contract assertions, and compatibility probes. Keep guardrails fast and specific so they run on every change and produce actionable failures. If a class of issue appears repeatedly, promote the manual troubleshooting step into automation so regressions are caught before deployment. Over time, this shifts effort from reactive debugging to preventive quality control and keeps operational knowledge aligned with real-world delivery practices.

As an additional safeguard, schedule periodic verification in a clean ephemeral environment and store the results as part of release evidence. This keeps assumptions current as dependencies evolve and helps detect subtle regressions before they reach production.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.